Files
golib/jwt/generator.go
2026-01-01 20:33:16 +11:00

63 lines
1.9 KiB
Go

package jwt
import (
"database/sql"
"errors"
)
type TokenGenerator struct {
accessExpireAfter int64 // Access Token expiry time in minutes
refreshExpireAfter int64 // Refresh Token expiry time in minutes
freshExpireAfter int64 // Token freshness expiry time in minutes
trustedHost string // Trusted hostname to use for the tokens
secretKey string // Secret key to use for token hashing
dbConn *sql.DB // Database handle for token blacklisting
}
// CreateGenerator creates and returns a new TokenGenerator using the provided configuration.
// All expiry times should be provided in minutes.
// trustedHost and secretKey strings must be provided.
// dbConn can be nil, but doing this will disable token revocation
func CreateGenerator(
accessExpireAfter int64,
refreshExpireAfter int64,
freshExpireAfter int64,
trustedHost string,
secretKey string,
dbConn *sql.DB,
) (gen *TokenGenerator, err error) {
if accessExpireAfter <= 0 {
return nil, errors.New("accessExpireAfter must be greater than 0")
}
if refreshExpireAfter <= 0 {
return nil, errors.New("refreshExpireAfter must be greater than 0")
}
if freshExpireAfter <= 0 {
return nil, errors.New("freshExpireAfter must be greater than 0")
}
if trustedHost == "" {
return nil, errors.New("trustedHost cannot be an empty string")
}
if secretKey == "" {
return nil, errors.New("secretKey cannot be an empty string")
}
if dbConn != nil {
err := dbConn.Ping()
if err != nil {
return nil, errors.New("Failed to ping database")
}
// TODO: check if jwtblacklist table exists
// TODO: create jwtblacklist table if not existing
}
return &TokenGenerator{
accessExpireAfter: accessExpireAfter,
refreshExpireAfter: refreshExpireAfter,
freshExpireAfter: freshExpireAfter,
trustedHost: trustedHost,
secretKey: secretKey,
dbConn: dbConn,
}, nil
}