62 lines
1.2 KiB
Go
62 lines
1.2 KiB
Go
package utils
|
|
|
|
import (
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
var jwtSecret = []byte(os.Getenv("JWT_SECRET"))
|
|
|
|
type Claims struct {
|
|
UUID string `json:"uuid"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
// GenerateJWT generates a new JWT token for a user
|
|
func GenerateJWT(uuid string) (string, error) {
|
|
// Set expiration time (24 hours from now)
|
|
expirationTime := time.Now().Add(24 * time.Hour)
|
|
|
|
// Create claims
|
|
claims := &Claims{
|
|
UUID: uuid,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(expirationTime),
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
},
|
|
}
|
|
|
|
// Create token with claims
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
|
// Generate encoded token
|
|
tokenString, err := token.SignedString(jwtSecret)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return tokenString, nil
|
|
}
|
|
|
|
// ParseJWT parses and validates a JWT token
|
|
func ParseJWT(tokenString string) (*Claims, error) {
|
|
claims := &Claims{}
|
|
|
|
// Parse token
|
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
|
return jwtSecret, nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Check if token is valid
|
|
if !token.Valid {
|
|
return nil, jwt.ErrTokenMalformed
|
|
}
|
|
|
|
return claims, nil
|
|
} |