49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const UserContextKey contextKey = contextKey("user")
|
|
|
|
func AuthMiddleware(secret []byte) func(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 == "" {
|
|
http.Error(w, "Missing token", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
|
|
|
|
claims, err := ValidateJWT(tokenStr, secret)
|
|
if err != nil {
|
|
http.Error(w, "Invalid token", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
ctx := context.WithValue(r.Context(), UserContextKey, claims)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
})
|
|
}
|
|
}
|
|
func RequireRole(role string) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
claims := r.Context().Value(UserContextKey).(*Claims)
|
|
if claims.Role != role {
|
|
http.Error(w, "Forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|