package utils import ( "time" "github.com/golang-jwt/jwt/v4" ) type JWTUtil struct { secretKey string } type Claims struct { UserID uint `json:"user_id"` Email string `json:"email"` Role string `json:"role"` jwt.RegisteredClaims } func NewJWTUtil(secretKey string) *JWTUtil { return &JWTUtil{secretKey: secretKey} } func (j *JWTUtil) GenerateToken(userID uint, email, role string) (string, error) { claims := Claims{ UserID: userID, Email: email, Role: role, RegisteredClaims: jwt.RegisteredClaims{ ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), IssuedAt: jwt.NewNumericDate(time.Now()), }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) return token.SignedString([]byte(j.secretKey)) } func (j *JWTUtil) ValidateToken(tokenString string) (*Claims, error) { token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) { return []byte(j.secretKey), nil }) if err != nil { return nil, err } if claims, ok := token.Claims.(*Claims); ok && token.Valid { return claims, nil } return nil, jwt.ErrInvalidKey }