You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
956 B
40 lines
956 B
package auth
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func GenerateToken(username string, secret []byte, duration time.Duration) (string, time.Time, error) {
|
|
now := time.Now().UTC()
|
|
expiresAt := now.Add(duration)
|
|
claims := jwt.MapClaims{
|
|
"sub": username,
|
|
"iat": now.Unix(),
|
|
"exp": expiresAt.Unix(),
|
|
}
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
tokenStr, err := token.SignedString(secret)
|
|
if err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
return tokenStr, expiresAt, nil
|
|
}
|
|
|
|
func ValidateToken(tokenStr string, secret []byte) (*jwt.MapClaims, error) {
|
|
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (any, error) {
|
|
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, jwt.ErrSignatureInvalid
|
|
}
|
|
return secret, nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|
if !ok || !token.Valid {
|
|
return nil, jwt.ErrSignatureInvalid
|
|
}
|
|
return &claims, nil
|
|
}
|
|
|