2023-01-14 16:29:52 +08:00
|
|
|
|
package req
|
2020-09-01 10:34:11 +08:00
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"errors"
|
2022-06-02 17:41:11 +08:00
|
|
|
|
"mayfly-go/pkg/config"
|
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
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// 创建用户token
|
2023-10-26 17:15:49 +08:00
|
|
|
|
func CreateToken(userId uint64, username string) (string, error) {
|
2020-09-01 10:34:11 +08:00
|
|
|
|
// 带权限创建令牌
|
|
|
|
|
|
// 设置有效期,过期需要重新登录获取token
|
|
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
|
|
|
|
|
"id": userId,
|
|
|
|
|
|
"username": username,
|
2023-09-02 17:24:18 +08:00
|
|
|
|
"exp": time.Now().Add(time.Minute * time.Duration(config.Conf.Jwt.ExpireTime)).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
|
2023-09-02 17:24:18 +08:00
|
|
|
|
tokenString, err := token.SignedString([]byte(config.Conf.Jwt.Key))
|
2023-10-26 17:15:49 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return "", err
|
|
|
|
|
|
}
|
|
|
|
|
|
return tokenString, nil
|
2020-09-01 10:34:11 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 解析token,并返回登录者账号信息
|
2023-10-18 15:24:29 +08:00
|
|
|
|
func ParseToken(tokenStr string) (uint64, string, error) {
|
2020-09-01 10:34:11 +08:00
|
|
|
|
if tokenStr == "" {
|
2023-10-18 15:24:29 +08:00
|
|
|
|
return 0, "", errors.New("token error")
|
2020-09-01 10:34:11 +08:00
|
|
|
|
}
|
2023-07-31 17:34:32 +08:00
|
|
|
|
|
2020-09-01 10:34:11 +08:00
|
|
|
|
// Parse token
|
2023-06-01 12:31:32 +08:00
|
|
|
|
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (any, error) {
|
2023-09-02 17:24:18 +08:00
|
|
|
|
return []byte(config.Conf.Jwt.Key), nil
|
2020-09-01 10:34:11 +08:00
|
|
|
|
})
|
|
|
|
|
|
if err != nil || token == nil {
|
2023-10-18 15:24:29 +08:00
|
|
|
|
return 0, "", err
|
2020-09-01 10:34:11 +08:00
|
|
|
|
}
|
2023-10-26 17:15:49 +08:00
|
|
|
|
if !token.Valid {
|
|
|
|
|
|
return 0, "", errors.New("token invalid")
|
|
|
|
|
|
}
|
2020-09-01 10:34:11 +08:00
|
|
|
|
i := token.Claims.(jwt.MapClaims)
|
2023-10-18 15:24:29 +08:00
|
|
|
|
return uint64(i["id"].(float64)), i["username"].(string), nil
|
2020-09-01 10:34:11 +08:00
|
|
|
|
}
|