49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
package crypto
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
// JWTConfig holds JWT configuration
|
|
type JWTConfig struct {
|
|
Secret []byte
|
|
ExpiryHours int
|
|
RefreshExpiryHours int
|
|
}
|
|
|
|
// GenerateToken creates a new JWT access token
|
|
func GenerateToken(cfg JWTConfig, userID uint, email string, userType string) (string, error) {
|
|
claims := jwt.MapClaims{
|
|
"user_id": userID,
|
|
"email": email,
|
|
"type": userType,
|
|
"exp": time.Now().Add(time.Duration(cfg.ExpiryHours) * time.Hour).Unix(),
|
|
"iat": time.Now().Unix(),
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString(cfg.Secret)
|
|
}
|
|
|
|
// ValidateToken validates and parses a JWT token
|
|
func ValidateToken(cfg JWTConfig, tokenString string) (jwt.MapClaims, error) {
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, jwt.ErrSignatureInvalid
|
|
}
|
|
return cfg.Secret, nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
|
return claims, nil
|
|
}
|
|
|
|
return nil, jwt.ErrSignatureInvalid
|
|
}
|