任务一完成
This commit is contained in:
+29
-10
@@ -16,13 +16,20 @@ var (
|
||||
|
||||
// CustomClaims 自定义Claims
|
||||
type CustomClaims struct {
|
||||
UserID uint `json:"userId"`
|
||||
Username string `json:"username"`
|
||||
AuthorityID uint `json:"authorityId"`
|
||||
BufferTime int64 `json:"bufferTime"`
|
||||
BaseClaims
|
||||
BufferTime int64 `json:"bufferTime"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// BaseClaims 基础Claims
|
||||
type BaseClaims struct {
|
||||
UUID string `json:"uuid"`
|
||||
ID uint `json:"userId"`
|
||||
Username string `json:"username"`
|
||||
NickName string `json:"nickName"`
|
||||
AuthorityID uint `json:"authorityId"`
|
||||
}
|
||||
|
||||
// JWT JWT工具
|
||||
type JWT struct {
|
||||
SigningKey []byte
|
||||
@@ -42,12 +49,10 @@ func NewJWT(signingKey, issuer string, expiresAt, bufferTime time.Duration) *JWT
|
||||
}
|
||||
|
||||
// CreateToken 创建token
|
||||
func (j *JWT) CreateToken(userID uint, username string, authorityID uint) (string, error) {
|
||||
func (j *JWT) CreateToken(baseClaims BaseClaims) (string, error) {
|
||||
claims := CustomClaims{
|
||||
UserID: userID,
|
||||
Username: username,
|
||||
AuthorityID: authorityID,
|
||||
BufferTime: int64(j.BufferTime / time.Second),
|
||||
BaseClaims: baseClaims,
|
||||
BufferTime: int64(j.BufferTime / time.Second),
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: j.Issuer,
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(j.ExpiresAt)),
|
||||
@@ -59,6 +64,20 @@ func (j *JWT) CreateToken(userID uint, username string, authorityID uint) (strin
|
||||
return token.SignedString(j.SigningKey)
|
||||
}
|
||||
|
||||
// CreateClaims 创建Claims
|
||||
func (j *JWT) CreateClaims(baseClaims BaseClaims) CustomClaims {
|
||||
return CustomClaims{
|
||||
BaseClaims: baseClaims,
|
||||
BufferTime: int64(j.BufferTime / time.Second),
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Issuer: j.Issuer,
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(j.ExpiresAt)),
|
||||
NotBefore: jwt.NewNumericDate(time.Now().Add(-1000)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ParseToken 解析token
|
||||
func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
@@ -84,5 +103,5 @@ func (j *JWT) ParseToken(tokenString string) (*CustomClaims, error) {
|
||||
|
||||
// NeedRefresh 判断是否需要刷新token
|
||||
func (j *JWT) NeedRefresh(claims *CustomClaims) bool {
|
||||
return claims.ExpiresAt.Time.Sub(time.Now()) < j.BufferTime
|
||||
return time.Until(claims.ExpiresAt.Time) < j.BufferTime
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user