madipo2611 62aea84fcb
All checks were successful
continuous-integration/drone/push Build is passing
reset to v0.0.19
2025-08-19 14:12:16 +03:00

41 lines
1.1 KiB
Go

package middleware
import (
"context"
"net/http"
"tailly_back_v2/pkg/auth"
)
// WSAuthMiddleware проверяет JWT токен для WebSocket соединений
func WSAuthMiddleware(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) {
// Проверяем, что это WebSocket запрос
if r.Header.Get("Upgrade") == "websocket" {
// Извлекаем токен из query параметров или заголовков
token := extractTokenFromRequest(r)
if token != "" {
userID, err := tokenAuth.ValidateAccessToken(token)
if err == nil {
// Добавляем userID в контекст
ctx := context.WithValue(r.Context(), userIDKey, userID)
r = r.WithContext(ctx)
}
}
}
next.ServeHTTP(w, r)
})
}
}
func extractTokenFromRequest(r *http.Request) string {
// Только проверка кук (как в вашем коде)
cookie, err := r.Cookie("accessToken")
if err == nil {
return cookie.Value
}
return ""
}