Files
mayfly-go/server/pkg/req/token.go

78 lines
1.9 KiB
Go
Raw Permalink Normal View History

2023-01-14 16:29:52 +08:00
package req
2020-09-01 10:34:11 +08:00
import (
"errors"
"mayfly-go/pkg/utils/stringx"
2020-09-01 10:34:11 +08:00
"time"
2021-01-08 15:37:32 +08:00
2023-05-24 12:32:17 +08:00
"github.com/golang-jwt/jwt/v5"
2020-09-01 10:34:11 +08:00
)
// JwtConf jwt配置
type JwtConf struct {
Key string
ExpireTime uint64 // 过期时间,单位分钟
RefreshTokenExpireTime uint64 // 刷新token的过期时间单位分钟
}
// 默认jwt配置
var jwtConf = JwtConf{
Key: stringx.RandUUID(),
ExpireTime: 60,
RefreshTokenExpireTime: 360,
}
// SetJwtConf 设置jwt配置
func SetJwtConf(conf JwtConf) {
jwtConf = conf
}
2020-09-01 10:34:11 +08:00
// 创建用户token
func CreateToken(userId uint64, username string) (accessToken string, refreshToken string, err error) {
now := time.Now()
2020-09-01 10:34:11 +08:00
// 带权限创建令牌
// 设置有效期过期需要重新登录获取token
accessJwt := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": userId,
"username": username,
"exp": now.Add(time.Minute * time.Duration(jwtConf.ExpireTime)).Unix(),
})
// refresh token
refreshJwt := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
2020-09-01 10:34:11 +08:00
"id": userId,
"username": username,
"exp": now.Add(time.Minute * time.Duration(jwtConf.RefreshTokenExpireTime)).Unix(),
2020-09-01 10:34:11 +08:00
})
2022-08-10 19:46:17 +08:00
2020-09-01 10:34:11 +08:00
// 使用自定义字符串加密 and get the complete encoded token as a string
accessToken, err = accessJwt.SignedString([]byte(jwtConf.Key))
if err != nil {
return
}
refreshToken, err = refreshJwt.SignedString([]byte(jwtConf.Key))
return
2020-09-01 10:34:11 +08:00
}
// 解析token并返回登录者账号信息
func ParseToken(tokenStr string) (uint64, string, error) {
2020-09-01 10:34:11 +08:00
if tokenStr == "" {
return 0, "", errors.New("token error")
2020-09-01 10:34:11 +08:00
}
2020-09-01 10:34:11 +08:00
// Parse token
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (any, error) {
return []byte(jwtConf.Key), nil
2020-09-01 10:34:11 +08:00
})
if err != nil || token == nil {
return 0, "", err
2020-09-01 10:34:11 +08:00
}
if !token.Valid {
return 0, "", errors.New("token invalid")
}
2020-09-01 10:34:11 +08:00
i := token.Claims.(jwt.MapClaims)
return uint64(i["id"].(float64)), i["username"].(string), nil
2020-09-01 10:34:11 +08:00
}