imc-vibe/backend/internal/api/handlers/middleware.go
2026-03-21 22:41:23 +01:00

72 lines
1.7 KiB
Go

package handlers
import (
"context"
"net/http"
"strings"
"github.com/imc-vibe/backend/internal/auth"
)
type contextKey string
const AuthContextKey contextKey = "auth"
func AuthMiddleware(jwtManager *auth.JWTManager, 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":"authorization header required"}`, http.StatusUnauthorized)
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
http.Error(w, `{"error":"invalid authorization header format"}`, http.StatusUnauthorized)
return
}
claims, err := jwtManager.ValidateToken(parts[1])
if err != nil {
http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)
return
}
authCtx := &auth.Context{
UserID: claims.UserID,
Username: claims.Username,
Role: auth.Role(claims.Role),
}
ctx := context.WithValue(r.Context(), AuthContextKey, authCtx)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func GetAuthContext(r *http.Request) *auth.Context {
if ctx := r.Context().Value(AuthContextKey); ctx != nil {
if authCtx, ok := ctx.(*auth.Context); ok {
return authCtx
}
}
return nil
}
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authCtx := GetAuthContext(r)
if authCtx == nil || !authCtx.IsAdmin() {
http.Error(w, `{"error":"admin access required"}`, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func extractID(path string) string {
parts := strings.Split(path, "/")
if len(parts) > 0 {
return parts[len(parts)-1]
}
return ""
}