29 lines
572 B
Go
29 lines
572 B
Go
package auth
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func GenerateToken(userID uint, jwtSecret string, options TokenOptions) (string, error) {
|
|
ttl := options.TTL
|
|
if ttl <= 0 {
|
|
ttl = 24 * time.Hour
|
|
}
|
|
|
|
now := time.Now()
|
|
claims := JWTClaims{
|
|
UserID: userID,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
Subject: fmt.Sprintf("%d", userID),
|
|
IssuedAt: jwt.NewNumericDate(now),
|
|
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
|
|
},
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
return token.SignedString([]byte(jwtSecret))
|
|
}
|