Files
spsays-bff/internal/middleware/auth.go
T
2026-05-09 23:19:19 +05:30

58 lines
1.4 KiB
Go

package middleware
import (
"context"
"net/http"
"strings"
"github.com/prabhupadasays/spsays-bff/pkg/response"
)
type contextKey string
const UserIDKey contextKey = "user_id"
// Auth is a placeholder middleware for JWT authentication.
// It extracts the Bearer token from the Authorization header,
// validates it, and sets the user ID in the request context.
func Auth(jwtSecret string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
response.Error(w, http.StatusUnauthorized, "missing authorization header")
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
response.Error(w, http.StatusUnauthorized, "invalid authorization format")
return
}
token := parts[1]
// TODO: validate JWT token and extract user ID
_ = token
_ = jwtSecret
userID := "" // placeholder
if userID == "" {
response.Error(w, http.StatusUnauthorized, "invalid or expired token")
return
}
ctx := context.WithValue(r.Context(), UserIDKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// GetUserID extracts the user ID from the request context.
func GetUserID(ctx context.Context) string {
if v, ok := ctx.Value(UserIDKey).(string); ok {
return v
}
return ""
}