72 lines
1.5 KiB
Go
72 lines
1.5 KiB
Go
|
package utils
|
||
|
|
||
|
import (
|
||
|
"Lee-WineList/config"
|
||
|
"time"
|
||
|
|
||
|
"github.com/golang-jwt/jwt"
|
||
|
)
|
||
|
|
||
|
type JWT struct {
|
||
|
claims jwt.MapClaims
|
||
|
}
|
||
|
|
||
|
// GenerateToken 根据UserId生成并返回Token
|
||
|
func GenerateToken(userId uint64) string {
|
||
|
jwtConfig := config.Scd.JWT
|
||
|
now := time.Now().Unix()
|
||
|
claims := make(jwt.MapClaims)
|
||
|
claims["exp"] = now + jwtConfig.AccessExpire
|
||
|
claims["iat"] = now
|
||
|
claims["rft"] = now + jwtConfig.RefreshAfter
|
||
|
claims["userId"] = userId
|
||
|
|
||
|
token := jwt.New(jwt.SigningMethodHS256)
|
||
|
token.Claims = claims
|
||
|
tokenStr, _ := token.SignedString([]byte(jwtConfig.AccessSecret))
|
||
|
|
||
|
return tokenStr
|
||
|
}
|
||
|
|
||
|
// ParseToken 解析Token
|
||
|
func ParseToken(tokenStr string) (*JWT, error) {
|
||
|
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
|
||
|
return []byte(config.Scd.JWT.AccessSecret), nil
|
||
|
})
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return &JWT{claims: token.Claims.(jwt.MapClaims)}, nil
|
||
|
}
|
||
|
|
||
|
// Valid 验证token是否有效
|
||
|
func (jwt *JWT) Valid() bool {
|
||
|
if err := jwt.claims.Valid(); err != nil {
|
||
|
return false
|
||
|
}
|
||
|
return true
|
||
|
}
|
||
|
|
||
|
// CheckRefresh 检查是否可以刷新
|
||
|
func (jwt *JWT) CheckRefresh() bool {
|
||
|
if time.Now().Unix() > jwt.GetRefreshTime() {
|
||
|
return true
|
||
|
}
|
||
|
return false
|
||
|
}
|
||
|
|
||
|
func (jwt *JWT) RefreshToken() string {
|
||
|
return GenerateToken(jwt.GetUserId())
|
||
|
}
|
||
|
|
||
|
// GetUserId 从Token中解析userId
|
||
|
func (jwt *JWT) GetUserId() uint64 {
|
||
|
return uint64(jwt.claims["userId"].(float64))
|
||
|
}
|
||
|
|
||
|
// GetRefreshTime 从Token中解析refreshTime
|
||
|
func (jwt *JWT) GetRefreshTime() int64 {
|
||
|
return int64(jwt.claims["rft"].(float64))
|
||
|
}
|