Files
2026-02-09 17:54:46 +08:00

43 lines
1.1 KiB
Go

package httpx
import (
"context"
"net/http"
"strings"
"common/auth"
"common/logger"
)
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 ") {
logger.WithPrefix("rid="+RequestIDFromContext(r)).Printf("auth missing header path=%s", r.URL.Path)
Unauthorized(w, r, "unauthorized")
return
}
token := strings.TrimSpace(strings.TrimPrefix(ah, "Bearer "))
sub, err := auth.ParseToken(token)
if err != nil || sub == "" {
logger.WithPrefix("rid="+RequestIDFromContext(r)).Printf("auth invalid token path=%s", r.URL.Path)
Unauthorized(w, r, "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 ""
}