feat: update template
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"server/internal/config"
|
||||
"server/internal/pkg/errs"
|
||||
@@ -19,32 +19,42 @@ type JWTMiddleware struct {
|
||||
cfg *config.JWTConfig
|
||||
}
|
||||
|
||||
type contextKey string
|
||||
|
||||
const UserContextKey contextKey = "user"
|
||||
|
||||
const RefreshTokenType = "refresh"
|
||||
|
||||
type Claims struct {
|
||||
UserID int32 `json:"user_id"`
|
||||
UserID int32 `json:"user_id"`
|
||||
TokenVersion int32 `json:"token_version"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type RefreshClaims struct {
|
||||
UserID int32 `json:"user_id"`
|
||||
Type string `json:"type"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func NewJWTMiddleware(cfg *config.Config) *JWTMiddleware {
|
||||
func NewJWTMiddleware(cfg *config.Config) (*JWTMiddleware, error) {
|
||||
jwtCfg := cfg.JWTConfig
|
||||
|
||||
return &JWTMiddleware{cfg: &jwtCfg}
|
||||
// 不允许空密钥
|
||||
if jwtCfg.Secret == "" {
|
||||
return nil, fmt.Errorf("jwt.secret 未配置:请在 %s.yaml 中设置 jwt.secret", config.GetEnv())
|
||||
}
|
||||
|
||||
m := &JWTMiddleware{cfg: &jwtCfg}
|
||||
|
||||
// 启动时校验签名算法配置
|
||||
if _, err := m.signingMethod(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func GetClaims(ctx context.Context) (*Claims, bool) {
|
||||
claims, ok := ctx.Value(UserContextKey).(*Claims)
|
||||
return claims, ok
|
||||
// signingMethod 返回配置的签名算法(仅支持 HMAC 家族)
|
||||
func (m *JWTMiddleware) signingMethod() (jwt.SigningMethod, error) {
|
||||
switch strings.ToUpper(m.cfg.SigningMethod) {
|
||||
case "", "HS256":
|
||||
return jwt.SigningMethodHS256, nil
|
||||
case "HS384":
|
||||
return jwt.SigningMethodHS384, nil
|
||||
case "HS512":
|
||||
return jwt.SigningMethodHS512, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("不支持的 jwt.signing_method: %q(仅支持 HS256/HS384/HS512)", m.cfg.SigningMethod)
|
||||
}
|
||||
}
|
||||
|
||||
// ParseToken 解析accessToken
|
||||
@@ -52,7 +62,7 @@ func (m *JWTMiddleware) ParseToken(tokenStr string) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(
|
||||
tokenStr,
|
||||
&Claims{},
|
||||
func(token *jwt.Token) (interface{}, error) {
|
||||
func(token *jwt.Token) (any, error) {
|
||||
return []byte(m.cfg.Secret), nil
|
||||
},
|
||||
)
|
||||
@@ -96,25 +106,34 @@ func (m *JWTMiddleware) Middleware(next http.Handler) http.Handler {
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), UserContextKey, claims)
|
||||
userCtx := GetUserContext(r.Context())
|
||||
userCtx.UserID = claims.UserID
|
||||
userCtx.TokenVersion = claims.TokenVersion
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (m *JWTMiddleware) GenerateAccessToken(userID int32) (string, time.Time, error) {
|
||||
func (m *JWTMiddleware) GenerateAccessToken(userID int32, tokenVersion int32) (string, time.Time, error) {
|
||||
method, err := m.signingMethod()
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
expiresAt := now.Add(m.cfg.Expire)
|
||||
|
||||
accessClaims := Claims{
|
||||
UserID: userID,
|
||||
UserID: userID,
|
||||
TokenVersion: tokenVersion,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(expiresAt),
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
},
|
||||
}
|
||||
|
||||
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, accessClaims)
|
||||
// 使用配置的签名算法,与 ParseToken 的校验保持一致
|
||||
accessToken := jwt.NewWithClaims(method, accessClaims)
|
||||
token, err := accessToken.SignedString([]byte(m.cfg.Secret))
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
|
||||
Reference in New Issue
Block a user