Files
mayfly-go/base/ctx/token.go

48 lines
1.1 KiB
Go
Raw Normal View History

2021-03-24 17:18:39 +08:00
package ctx
2020-09-01 10:34:11 +08:00
import (
"errors"
2021-03-24 17:18:39 +08:00
"mayfly-go/base/biz"
2020-09-01 10:34:11 +08:00
"time"
2021-01-08 15:37:32 +08:00
"github.com/dgrijalva/jwt-go"
2020-09-01 10:34:11 +08:00
)
const (
JwtKey = "mykey"
ExpTime = time.Hour * 24 * 7
)
// 创建用户token
func CreateToken(userId uint64, username string) string {
// 带权限创建令牌
// 设置有效期过期需要重新登录获取token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": userId,
"username": username,
"exp": time.Now().Add(ExpTime).Unix(),
})
// 使用自定义字符串加密 and get the complete encoded token as a string
tokenString, err := token.SignedString([]byte(JwtKey))
2021-03-24 17:18:39 +08:00
biz.BizErrIsNil(err, "token创建失败")
2020-09-01 10:34:11 +08:00
return tokenString
}
// 解析token并返回登录者账号信息
2021-03-24 17:18:39 +08:00
func ParseToken(tokenStr string) (*LoginAccount, error) {
2020-09-01 10:34:11 +08:00
if tokenStr == "" {
return nil, errors.New("token error")
}
// Parse token
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
return []byte(JwtKey), nil
})
if err != nil || token == nil {
return nil, err
}
i := token.Claims.(jwt.MapClaims)
2021-03-24 17:18:39 +08:00
return &LoginAccount{Id: uint64(i["id"].(float64)), Username: i["username"].(string)}, nil
2020-09-01 10:34:11 +08:00
}