59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
"tailly_back_v2/pkg/auth"
|
|
)
|
|
|
|
const (
|
|
authorizationHeader = "Authorization"
|
|
bearerPrefix = "Bearer "
|
|
userIDKey = "userID" // Ключ для хранения userID в контексте
|
|
)
|
|
|
|
// AuthMiddleware проверяет JWT токен и добавляет userID в контекст
|
|
func AuthMiddleware(tokenAuth *auth.TokenAuth) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Пропускаем OPTIONS запросы (для CORS)
|
|
if r.Method == http.MethodOptions {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Извлекаем заголовок Authorization
|
|
header := r.Header.Get(authorizationHeader)
|
|
if header == "" {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Проверяем формат заголовка
|
|
if !strings.HasPrefix(header, bearerPrefix) {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Извлекаем токен
|
|
token := strings.TrimPrefix(header, bearerPrefix)
|
|
if token == "" {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Валидируем токен
|
|
userID, err := tokenAuth.ValidateAccessToken(token)
|
|
if err != nil {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Добавляем userID в контекст
|
|
ctx := context.WithValue(r.Context(), userIDKey, userID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|