new file: internal/middleware/auth.go
add middleware for authenticate
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
// middleware/auth.go
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"serv_golang_rest_api/internal/utils"
|
||||
)
|
||||
|
||||
func AuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
utils.WriteError(w, http.StatusUnauthorized, "Authorization header required")
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.Split(authHeader, " ")
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
utils.WriteError(w, http.StatusUnauthorized, "Invalid authorization format")
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := utils.ValidateJWT(parts[1])
|
||||
if err != nil {
|
||||
utils.WriteError(w, http.StatusUnauthorized, "Invalid token")
|
||||
return
|
||||
}
|
||||
|
||||
// Добавляем claims в контекст
|
||||
ctx := context.WithValue(r.Context(), "userClaims", claims)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user