27 lines
604 B
Go
27 lines
604 B
Go
package internal
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const UserContext contextKey = "user"
|
|
|
|
func AuthMiddleware(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, "Authorization header is required", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
authToken := strings.Split(authHeader, "Bearer ")[1]
|
|
ctx := context.WithValue(r.Context(), UserContext, ParseJWT(authToken))
|
|
req := r.WithContext(ctx)
|
|
next.ServeHTTP(w, req)
|
|
})
|
|
}
|