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

52 lines
1.2 KiB

3 years ago
package app
import (
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/model"
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 *model.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: conf.JWTSetting.Issuer + ":" + User.Salt,
3 years ago
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(GetJWTSecret())
return token, err
}
func ParseToken(token string) (*Claims, error) {
tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (any, error) {
3 years ago
return GetJWTSecret(), nil
})
if err != nil {
return nil, err
}
if tokenClaims != nil {
if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
return claims, nil
}
}
return nil, err
}