Files
nl-game-api/pkg/jwtutil/jwtutil.go
2026-08-14 13:17:03 +08:00

49 lines
1.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package jwtutil 封装 JWT Token 的签发与解析
package jwtutil
import (
"errors"
"time"
"github.com/golang-jwt/jwt/v5"
"nl-game-api-gin/internal/config"
)
// Claims 自定义 JWT 载荷用户ID与角色
type Claims struct {
UserID int `json:"user_id"` // 用户ID
Role int `json:"role"` // 角色1超管 2普通
jwt.RegisteredClaims
}
// Generate 为用户签发 Token
func Generate(userID, role int) (string, error) {
claims := Claims{
UserID: userID,
Role: role,
RegisteredClaims: jwt.RegisteredClaims{
// 过期时间从配置文件读取
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(config.C.JWT.ExpireHours) * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(config.C.JWT.Secret))
}
// Parse 解析并校验 Token返回载荷
func Parse(tokenStr string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenStr, &Claims{}, func(t *jwt.Token) (any, error) {
return []byte(config.C.JWT.Secret), nil
})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(*Claims)
if !ok || !token.Valid {
return nil, errors.New("无效的 Token")
}
return claims, nil
}