This commit is contained in:
vipg
2026-02-09 17:54:46 +08:00
parent 65353ee4a2
commit cc8dfdad80
3 changed files with 47 additions and 16 deletions

View File

@@ -6,6 +6,7 @@ import (
"strings"
"common/auth"
"common/logger"
)
type userIDKey struct{}
@@ -15,13 +16,15 @@ func AuthRequired() func(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")
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 == "" {
Unauthorized(w, "unauthorized")
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)