package jwt import ( "mangezmieux-backend/internal/responses" "time" jwtLib "github.com/golang-jwt/jwt/v5" ) type Service struct { SecretKey string } func NewService() *Service { return &Service{SecretKey: "hard-coded-temp"} } type Claims struct { ID string `json:"username"` jwtLib.RegisteredClaims } func (s *Service) ValidateToken(token string) (*Claims, error) { claims := &Claims{} tkn, err := jwtLib.ParseWithClaims(token, claims, func(token *jwtLib.Token) (any, error) { return []byte(s.SecretKey), nil }) if err != nil { return nil, err } if !tkn.Valid { return nil, err } return claims, nil } func (s *Service) GenerateJWTToken(userId string) (string, error) { expirationTime := time.Now().Add(10 * time.Minute) claims := &Claims{ ID: userId, RegisteredClaims: jwtLib.RegisteredClaims{ // In JWT, the expiry time is expressed as unix milliseconds ExpiresAt: jwtLib.NewNumericDate(expirationTime), }, } token := jwtLib.NewWithClaims(jwtLib.SigningMethodHS256, claims) // Create the JWT string tokenString, err := token.SignedString([]byte(s.SecretKey)) if err != nil { return "", &responses.ErrInternalServer } return tokenString, nil } func (s *Service) Refresh(oldToken string) (string, error) { claims := &Claims{} tkn, err := jwtLib.ParseWithClaims(oldToken, claims, func(token *jwtLib.Token) (any, error) { return []byte(s.SecretKey), nil }) if err != nil { return "", err } if !tkn.Valid { return "", err } // Now, create a new token for the current use, with a renewed expiration time expirationTime := time.Now().Add(10 * time.Minute) claims.ExpiresAt = jwtLib.NewNumericDate(expirationTime) token := jwtLib.NewWithClaims(jwtLib.SigningMethodHS256, claims) tokenString, err := token.SignedString([]byte(s.SecretKey)) return tokenString, nil }