mirror of
https://gitee.com/shikong-sk/gofiber-study
synced 2025-02-23 23:32:15 +08:00
45 lines
965 B
Go
45 lines
965 B
Go
package global
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
"gofiber.study.skcks.cn/common/config"
|
|
"time"
|
|
)
|
|
|
|
var JwtConfig *config.JwtConfig
|
|
|
|
type UserClaims struct {
|
|
Id string `json:"id"`
|
|
Account string `json:"account"`
|
|
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func GetToken(claims UserClaims) (string, error) {
|
|
iat := time.Now().Unix()
|
|
claims.IssuedAt = jwt.NewNumericDate(time.Unix(iat, 0))
|
|
|
|
expire := iat + JwtConfig.Expire
|
|
claims.ExpiresAt = jwt.NewNumericDate(time.Unix(expire, 0))
|
|
|
|
token := jwt.New(jwt.SigningMethodHS256)
|
|
return token.SignedString([]byte(JwtConfig.Secret))
|
|
}
|
|
|
|
func ParseToken(tokenStr string) (*UserClaims, error) {
|
|
token, err := jwt.ParseWithClaims(tokenStr, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
|
|
return JwtConfig.Secret, nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if claims, ok := token.Claims.(*UserClaims); ok && token.Valid {
|
|
return claims, nil
|
|
}
|
|
|
|
return nil, errors.New("无效的令牌")
|
|
}
|