feat: fully featured token checks
All checks were successful
Build and Deploy Go App / build (push) Successful in 6m39s
Build and Deploy Go App / deploy (push) Successful in 46s

This commit is contained in:
nihonium 2025-12-06 06:25:21 +03:00
parent 7956a8a961
commit 713c0adc14
Signed by: nihonium
GPG key ID: 0251623741027CFC
6 changed files with 226 additions and 77 deletions

View file

@ -3,8 +3,11 @@ package middleware
import (
"context"
"errors"
"fmt"
"net/http"
"nyanimedb/auth"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
@ -37,12 +40,18 @@ func JWTAuthMiddleware(secret string) gin.HandlerFunc {
}
// 2. Парсим токен с MapClaims
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
if t.Method != jwt.SigningMethodHS256 {
return nil, errors.New("unexpected signing method: " + t.Method.Alg())
token, err := jwt.ParseWithClaims(tokenStr, &auth.TokenClaims{}, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method")
}
return []byte(secret), nil // ← конвертируем string → []byte
return []byte(secret), nil
})
// token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
// if t.Method != jwt.SigningMethodHS256 {
// return nil, errors.New("unexpected signing method: " + t.Method.Alg())
// }
// return []byte(secret), nil // ← конвертируем string → []byte
// })
if err != nil {
abortWithJSON(c, http.StatusUnauthorized, "invalid token: "+err.Error())
return
@ -55,20 +64,23 @@ func JWTAuthMiddleware(secret string) gin.HandlerFunc {
}
// 4. Извлекаем user_id из claims
claims, ok := token.Claims.(jwt.MapClaims)
claims, ok := token.Claims.(*auth.TokenClaims)
if !ok {
abortWithJSON(c, http.StatusUnauthorized, "invalid claims format")
return
}
userID, ok := claims["user_id"].(string)
if !ok || userID == "" {
if claims.UserID == "" {
abortWithJSON(c, http.StatusUnauthorized, "user_id claim missing or invalid")
return
}
if claims.Type != "access" {
abortWithJSON(c, http.StatusUnauthorized, "token type is not access")
return
}
// 5. Сохраняем в контексте
c.Set("user_id", userID)
c.Set("user_id", claims.UserID)
// 6. Для oapi-codegen — кладём gin.Context в request context
GinContextToContext(c)