small fixes

This commit is contained in:
2025-06-18 09:01:14 +03:00
parent 42f2b68848
commit 5e609017f0
15 changed files with 55 additions and 108 deletions

View File

@@ -9,7 +9,6 @@ import (
"github.com/golang-jwt/jwt/v5"
)
// contextKey - это тип для ключей контекста, чтобы избежать коллизий.
type contextKey string
const UserIDContextKey = contextKey("userID")
@@ -24,7 +23,7 @@ func AuthMiddleware(next http.Handler) http.Handler {
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader { // Префикс "Bearer " не найден
if tokenString == authHeader {
http.Error(w, "Invalid token format", http.StatusUnauthorized)
return
}
@@ -36,7 +35,6 @@ func AuthMiddleware(next http.Handler) http.Handler {
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Проверяем, что метод подписи HMAC
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
@@ -54,7 +52,6 @@ func AuthMiddleware(next http.Handler) http.Handler {
return
}
// Получаем user_id из claims. JWT хранит числа как float64.
userIDFloat, ok := claims["user_id"].(float64)
if !ok {
http.Error(w, "Invalid user_id in token", http.StatusUnauthorized)
@@ -62,7 +59,6 @@ func AuthMiddleware(next http.Handler) http.Handler {
}
userID := int(userIDFloat)
// Добавляем userID в контекст запроса для использования в хендлере
ctx := context.WithValue(r.Context(), UserIDContextKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})