alai-server/backend/utils/jwt.go

55 lines
1.2 KiB
Go
Raw Permalink Normal View History

2022-06-29 21:26:05 -04:00
package utils
import (
"errors"
"os"
"time"
"github.com/golang-jwt/jwt/v4"
)
type JWTClaim struct {
2023-02-10 22:04:01 -03:00
Id uint64 `json:"id"`
2022-06-29 21:26:05 -04:00
Username string `json:"username"`
Email string `json:"email"`
jwt.RegisteredClaims
}
2023-02-10 22:04:01 -03:00
func GenerateJWT(id uint64, email string, username string) (tokenString string, err error) {
2023-01-28 20:59:53 -03:00
expirationTime := time.Now().Add(24 * time.Hour)
2022-06-29 21:26:05 -04:00
claims := &JWTClaim{
2023-02-10 22:04:01 -03:00
Id: id,
2022-06-29 21:26:05 -04:00
Email: email,
Username: username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expirationTime),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err = token.SignedString([]byte(os.Getenv("JWT_SECRET")))
2022-06-29 21:26:05 -04:00
return
}
2023-02-09 01:07:31 -03:00
func ValidateToken(signedToken string) (claims *JWTClaim, err error) {
2022-06-29 21:26:05 -04:00
token, err := jwt.ParseWithClaims(
signedToken,
&JWTClaim{},
func(token *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("JWT_SECRET")), nil
},
)
if err != nil {
return
}
claims, ok := token.Claims.(*JWTClaim)
if !ok {
err = errors.New("couldn't parse claims")
return
}
if claims.ExpiresAt.Unix() < jwt.NewNumericDate(time.Now().Local()).Unix() {
err = errors.New("token expired")
return
}
return
}