feat: fully featured token checks
This commit is contained in:
parent
7956a8a961
commit
713c0adc14
6 changed files with 226 additions and 77 deletions
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue