37 lines
787 B
Go
37 lines
787 B
Go
package auth
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func GenerateJWT(key string, user User, expiryTimestamp uint64) (string, error) {
|
|
claims := jwt.MapClaims{
|
|
"user": user,
|
|
"exp": expiryTimestamp,
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString([]byte(key))
|
|
}
|
|
|
|
func ValidateJWT(jwtString, key string) (jwt.MapClaims, error) {
|
|
token, err := jwt.Parse(jwtString, func(token *jwt.Token) (any, error) {
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, fmt.Errorf("Invalid signing method!")
|
|
}
|
|
|
|
return []byte(key), nil
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
|
return claims, nil
|
|
}
|
|
|
|
return nil, fmt.Errorf("Invalid token!")
|
|
}
|