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.
|
|
|
package jwt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Claims struct {
|
|
|
|
UserID uint `json:"user_id"`
|
|
|
|
jwt.RegisteredClaims
|
|
|
|
}
|
|
|
|
|
|
|
|
func GenerateToken(userID uint, secret string, expireHours int) (string, error) {
|
|
|
|
expireTime := time.Now().Add(time.Hour * time.Duration(expireHours))
|
|
|
|
|
|
|
|
claims := Claims{
|
|
|
|
UserID: userID,
|
|
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
|
|
ExpiresAt: jwt.NewNumericDate(expireTime),
|
|
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
|
|
Issuer: "go-admin-platform",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
|
return token.SignedString([]byte(secret))
|
|
|
|
}
|
|
|
|
|
|
|
|
func ParseToken(tokenString, secret string) (*Claims, error) {
|
|
|
|
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
|
|
|
return []byte(secret), nil
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
|
|
|
return claims, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, jwt.ErrInvalidKey
|
|
|
|
}
|