package middleware import ( "context" "net/http" "strings" "github.com/golang-jwt/jwt/v5" ) type contextKey string const UserIDKey contextKey = "user_id" type AuthMiddleware struct { jwtSecret string } func NewAuthMiddleware(jwtSecret string) *AuthMiddleware { return &AuthMiddleware{jwtSecret: jwtSecret} } func (m *AuthMiddleware) Authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { authHeader := r.Header.Get("Authorization") if authHeader == "" { http.Error(w, `{"error":"missing authorization header"}`, http.StatusUnauthorized) return } parts := strings.Split(authHeader, " ") if len(parts) != 2 || parts[0] != "Bearer" { http.Error(w, `{"error":"invalid authorization header"}`, http.StatusUnauthorized) return } tokenString := parts[1] token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, jwt.ErrSignatureInvalid } return []byte(m.jwtSecret), nil }) if err != nil || !token.Valid { http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized) return } claims, ok := token.Claims.(jwt.MapClaims) if !ok { http.Error(w, `{"error":"invalid token claims"}`, http.StatusUnauthorized) return } // Check token type tokenType, _ := claims["type"].(string) if tokenType != "access" { http.Error(w, `{"error":"invalid token type"}`, http.StatusUnauthorized) return } userID, ok := claims["user_id"].(float64) if !ok { http.Error(w, `{"error":"invalid user id in token"}`, http.StatusUnauthorized) return } ctx := context.WithValue(r.Context(), UserIDKey, int64(userID)) next.ServeHTTP(w, r.WithContext(ctx)) }) } func GetUserID(ctx context.Context) int64 { userID, ok := ctx.Value(UserIDKey).(int64) if !ok { return 0 } return userID }