alai-server/backend/utils/jwt.go

53 lines
1.1 KiB
Go
Raw 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 {
Username string `json:"username"`
Email string `json:"email"`
jwt.RegisteredClaims
}
func GenerateJWT(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{
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
}
func ValidateToken(signedToken string) (err error) {
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
}