You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
paopao-ce/pkg/app/jwt.go

64 lines
1.6 KiB

// Copyright 2022 ROC. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
3 years ago
package app
import (
"crypto/md5"
"encoding/binary"
"encoding/hex"
3 years ago
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/core/ms"
3 years ago
)
type Claims struct {
UID int64 `json:"uid"`
Username string `json:"username"`
jwt.RegisteredClaims
3 years ago
}
func GetJWTSecret() []byte {
return []byte(conf.JWTSetting.Secret)
3 years ago
}
func GenerateToken(user *ms.User) (string, error) {
expireTime := time.Now().Add(conf.JWTSetting.Expire)
3 years ago
claims := Claims{
UID: user.ID,
Username: user.Username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expireTime),
Issuer: IssuerFrom(user.CreatedOn),
3 years ago
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(GetJWTSecret())
return token, err
}
func ParseToken(token string) (res *Claims, err error) {
var tokenClaims *jwt.Token
tokenClaims, err = jwt.ParseWithClaims(token, &Claims{}, func(_ *jwt.Token) (any, error) {
3 years ago
return GetJWTSecret(), nil
})
if err == nil && tokenClaims != nil && tokenClaims.Valid {
res, _ = tokenClaims.Claims.(*Claims)
} else {
err = jwt.ErrTokenNotValidYet
3 years ago
}
return
3 years ago
}
func IssuerFrom(num int64) string {
contents := make([]byte, len(conf.JWTSetting.Issuer)+8)
copy(contents, []byte(conf.JWTSetting.Issuer))
binary.LittleEndian.PutUint64(contents[len(contents)-8:], uint64(num))
res := md5.Sum(contents)
return hex.EncodeToString(res[:])
}