internal/authentication/authentication.go (27 lines of code) (raw):
// Package authentication provides JWT token generation functionality.
// It implements a simple authentication mechanism using HS256-signed JWTs
// with configurable issuer, expiration time, and signing secret.
// The package uses github.com/golang-jwt/jwt/v5 for token creation and signing.
package authentication
import (
"time"
"github.com/golang-jwt/jwt/v5"
)
type Auth struct {
jwtIssuer string
jwtTTL time.Duration
secretBytes []byte
timeNowFunc func() time.Time
}
func NewAuth(jwtIssuer string, jwtTTL time.Duration, secret []byte) Auth {
return Auth{
jwtIssuer: jwtIssuer,
jwtTTL: jwtTTL,
secretBytes: secret,
timeNowFunc: time.Now,
}
}
func (a Auth) GenerateJWT() (string, error) {
claims := jwt.RegisteredClaims{
Issuer: a.jwtIssuer,
IssuedAt: jwt.NewNumericDate(a.timeNowFunc()),
ExpiresAt: jwt.NewNumericDate(a.timeNowFunc().Add(a.jwtTTL)),
}
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(a.secretBytes)
}