feat(*): go 后端项目脚手架
This commit is contained in:
81
pkg/utils/jwt.go
Normal file
81
pkg/utils/jwt.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/zhilv666/navsite/pkg/config"
|
||||
"github.com/zhilv666/navsite/pkg/logger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type MyCustomClaims struct {
|
||||
ID uint `json:"id"`
|
||||
Email string `json:"Email"`
|
||||
SsoID string `json:"sso_id"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// GenerateJwtToken 生成 JWT Token
|
||||
func GenerateJwtToken(id uint, email, sso_id string) string {
|
||||
jwtConf := config.GetConfig().JWT
|
||||
claims := MyCustomClaims{
|
||||
id,
|
||||
email,
|
||||
sso_id,
|
||||
jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(jwtConf.ExpireDurationHour * time.Hour)),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
ss, err := token.SignedString([]byte(jwtConf.SecretKey))
|
||||
if err != nil {
|
||||
logger.Error("generate jwt token error", zap.String("jwt", err.Error()))
|
||||
}
|
||||
return ss
|
||||
}
|
||||
|
||||
// ParseJwtToken 解析 JWT 并返回自定义 Claims,同时返回错误信息
|
||||
func ParseJwtToken(tokenString string) (*MyCustomClaims, error) {
|
||||
jwtConf := config.GetConfig().JWT
|
||||
|
||||
token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (any, error) {
|
||||
return []byte(jwtConf.SecretKey), nil
|
||||
}, jwt.WithLeeway(5*time.Second))
|
||||
|
||||
if err != nil {
|
||||
logger.Error("parse jwt token error", zap.String("jwt", err.Error()))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*MyCustomClaims)
|
||||
if !ok || !token.Valid {
|
||||
logger.Error("invalid jwt claims")
|
||||
return nil, errors.New("jwt token invalid")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// ValidJwtToken 验证 JWT Token
|
||||
func ValidJwtToken(tokenString string) bool {
|
||||
jwtConf := config.GetConfig().JWT
|
||||
|
||||
token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (any, error) {
|
||||
return []byte(jwtConf.SecretKey), nil
|
||||
}, jwt.WithLeeway(5*time.Second))
|
||||
|
||||
if err != nil {
|
||||
logger.Error("parse jwt token error", zap.String("jwt", err.Error()))
|
||||
return false
|
||||
}
|
||||
|
||||
_, ok := token.Claims.(*MyCustomClaims)
|
||||
if !ok || !token.Valid {
|
||||
logger.Error("invalid jwt claims")
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user