Files
2023-09-16 20:14:20 +08:00

84 lines
2.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package jwtx
import (
"errors"
"time"
"github.com/dgrijalva/jwt-go"
)
var (
TokenExpired error = errors.New("token is expired")
TokenNotValidYet error = errors.New("token not active yet")
TokenMalformed error = errors.New("that's not even a token")
TokenInvalid error = errors.New("couldn't handle this token")
TokenGenerateFailed error = errors.New("generate token failed!")
// defaultSignKey string = "hcVI@Nm4cjhjPVvCpL5^1%jY"
defaultSignKey = "arcsine(0.728)≈46°438″"
RedisUserKey string = "user:%d"
)
type jwtx struct {
SigningKey []byte
}
type Claims struct {
UserId int64 `json:"user_id"`
jwt.StandardClaims
}
func NewJWT() *jwtx {
return &jwtx{
[]byte(defaultSignKey),
}
}
// 仅解析Token
func (j *jwtx) Decode(tokenString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return j.SigningKey, nil
})
if err != nil {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed == jwt.ValidationErrorMalformed {
return nil, TokenMalformed
} else if ve.Errors&jwt.ValidationErrorExpired == jwt.ValidationErrorExpired {
// Token is expired
return nil, TokenExpired
} else if ve.Errors&jwt.ValidationErrorNotValidYet == jwt.ValidationErrorNotValidYet {
return nil, TokenNotValidYet
} else {
return nil, TokenInvalid
}
}
}
claims, ok := token.Claims.(*Claims)
if !ok || !token.Valid {
return nil, TokenInvalid
}
return claims, nil
}
// 根据参数生成和设置 token
func (j *jwtx) Encode(claims *Claims, expiresTime time.Time) (string, error) {
expSecond := expiresTime.Unix()
nowSecond := time.Now().Unix()
if expSecond-nowSecond < 0 {
return "", errors.New("时间无效")
}
// 设置有效时间
claims.StandardClaims.ExpiresAt = expiresTime.Unix()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(j.SigningKey)
if err != nil {
return "", TokenGenerateFailed
}
return tokenString, nil
}