58 lines
1.4 KiB
Go
Executable file
58 lines
1.4 KiB
Go
Executable file
package utils
|
|
|
|
import (
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
var jwtSecret = []byte("your-secret-key-change-this-in-production") // TODO: Move to env var
|
|
|
|
// Claims represents JWT custom claims
|
|
type Claims struct {
|
|
UserID int `json:"userId"`
|
|
Identifier string `json:"identifier"`
|
|
Role string `json:"role"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
// GenerateJWT generates a new JWT token for a user
|
|
func GenerateJWT(userID int, identifier string, role string) (string, error) {
|
|
expirationTime := time.Now().Add(24 * time.Hour) // 24 hours
|
|
|
|
claims := &Claims{
|
|
UserID: userID,
|
|
Identifier: identifier,
|
|
Role: role,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(expirationTime),
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
},
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString(jwtSecret)
|
|
}
|
|
|
|
// ValidateJWT validates a JWT token and returns the claims
|
|
func ValidateJWT(tokenString string) (*Claims, error) {
|
|
claims := &Claims{}
|
|
|
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, errors.New("invalid signing method")
|
|
}
|
|
return jwtSecret, nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if !token.Valid {
|
|
return nil, errors.New("invalid token")
|
|
}
|
|
|
|
return claims, nil
|
|
}
|