Skip to content

Commit

Permalink
add some comments
Browse files Browse the repository at this point in the history
  • Loading branch information
dreth committed Aug 15, 2024
1 parent 38c157c commit eadb0da
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions backend/auth/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (

var jwtKey = []byte(env.MK)

// GenerateJWT generates a JWT token with the given email and duration
func GenerateJWT(email string, duration int) (string, error) {
// If the duration is 0, default to 720
if duration == 0 {
Expand All @@ -31,31 +32,43 @@ func GenerateJWT(email string, duration int) (string, error) {
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

return token.SignedString(jwtKey)
}

// ValidateJWT validates a JWT token and returns the claims
func ValidateJWT(tokenStr string) (*structs.Claims, error) {
// Parse the JWT token
claims := &structs.Claims{}
token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {
return jwtKey, nil
})

// Check if the token is valid
if err != nil {
return nil, err
}

if !token.Valid {
return nil, errors.New("invalid token")
}

return claims, nil
}

// GetJWTDurationFromHeader gets the JWT duration from the header
func GetJWTDurationFromHeader(c *gin.Context, defaultDuration int) (int, error) {
// Get the JWT duration from the header
jwtDurationStr := c.GetHeader("X-Jwt-Token-Duration")

// If the duration is not provided, return the default duration
if jwtDurationStr != "" {
jwtDuration, err := strconv.Atoi(jwtDurationStr)
if err != nil {
return 0, fmt.Errorf("invalid JWT duration")
}
return jwtDuration, nil
}

return defaultDuration, nil
}

0 comments on commit eadb0da

Please sign in to comment.