31 lines
761 B
Go
31 lines
761 B
Go
package utils
|
|
|
|
import (
|
|
"errors"
|
|
"gitea.zjmud.xyz/phyer/rbac/config"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"time"
|
|
)
|
|
|
|
func GenerateJWT(userID string) (string, error) {
|
|
claims := jwt.MapClaims{
|
|
"user_id": userID,
|
|
"exp": time.Now().Add(time.Hour * 24).Unix(),
|
|
}
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString([]byte(config.AppConfig.JWTSecret))
|
|
}
|
|
|
|
func ParseJWT(tokenString string) (jwt.MapClaims, error) {
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(config.AppConfig.JWTSecret), nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
|
return claims, nil
|
|
}
|
|
return nil, errors.New("invalid token")
|
|
}
|