add
This commit is contained in:
39
trading_assistant_api/common/httpx/auth.go
Normal file
39
trading_assistant_api/common/httpx/auth.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"common/auth"
|
||||
)
|
||||
|
||||
type userIDKey struct{}
|
||||
|
||||
func AuthRequired() func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ah := r.Header.Get("Authorization")
|
||||
if ah == "" || !strings.HasPrefix(ah, "Bearer ") {
|
||||
Unauthorized(w, "unauthorized")
|
||||
return
|
||||
}
|
||||
token := strings.TrimSpace(strings.TrimPrefix(ah, "Bearer "))
|
||||
sub, err := auth.ParseToken(token)
|
||||
if err != nil || sub == "" {
|
||||
Unauthorized(w, "unauthorized")
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), userIDKey{}, sub)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func UserID(r *http.Request) string {
|
||||
v := r.Context().Value(userIDKey{})
|
||||
if id, ok := v.(string); ok {
|
||||
return id
|
||||
}
|
||||
return ""
|
||||
}
|
||||
Reference in New Issue
Block a user