Documentation
¶
Index ¶
- Variables
- func ErrorCodeForError(err error) string
- func HTTPStatusForError(err error) int
- func NewConfigError(msg string, err error) error
- func NewCredentialError(msg string, err error) error
- func NewInternalError(msg string, err error) error
- func NewNotFoundError(msg string, err error) error
- func NewRateLimitError(msg string, retryAfter time.Duration) error
- func NewSessionError(msg string, sessionID string, err error) error
- func NewTokenError(msg string, err error) error
- func NewValidationError(msg string, fields map[string]string) error
- func ReplaceSingletonForTest(ga *GoAuth) (restore func())
- func RetryAfterForError(err error) time.Duration
- func WithContext(err error, format string, args ...any) error
- type AuthEventHooks
- type AuthParams
- type AuthResult
- type Authenticatable
- type CheckRevokedFunc
- type ConfigError
- type ConvertAccessTokenClaimsFunc
- type ConvertClaimsFunc
- type CredentialError
- type DefaultTokenIssuer
- func (ti *DefaultTokenIssuer) ConvertAccessTokenClaims(ctx context.Context, claims *TokenClaims) (Authenticatable, error)
- func (ti *DefaultTokenIssuer) ConvertAccessTokenClaimsWith(convertAccessTokenClaimsWith ConvertAccessTokenClaimsFunc)
- func (ti *DefaultTokenIssuer) CreateAccessToken(ctx context.Context, authenticatable Authenticatable) (*Token, error)
- func (ti *DefaultTokenIssuer) CreateRefreshToken(ctx context.Context, authenticatable Authenticatable, oldToken *string) (*Token, error)
- func (ti *DefaultTokenIssuer) DecodeAccessToken(ctx context.Context, token string) (*TokenClaims, error)
- func (ti *DefaultTokenIssuer) RevokeRefreshToken(ctx context.Context, token string) error
- func (ti *DefaultTokenIssuer) RevokeRefreshTokenWith(revokeRefreshTokenWith RevokeRefreshTokenFunc)
- func (ti *DefaultTokenIssuer) SetAccessTokenExpiresIn(expiresIn time.Duration)
- func (ti *DefaultTokenIssuer) SetAudience(audience []string)
- func (ti *DefaultTokenIssuer) SetExtraClaimsWith(setExtraClaimsWith SetExtraClaimsFunc)
- func (ti *DefaultTokenIssuer) SetIssuer(issuer string)
- func (ti *DefaultTokenIssuer) SetRefreshTokenExpiresIn(expiresIn time.Duration)
- func (ti *DefaultTokenIssuer) SetRegisteredClaimsWith(setRegisteredClaimsWith SetRegisteredClaimsFunc)
- func (ti *DefaultTokenIssuer) SetSecret(secret string)
- func (ti *DefaultTokenIssuer) StoreRefreshTokenWith(storeRefreshTokenWith StoreRefreshTokenFunc)
- func (ti *DefaultTokenIssuer) ValidateRefreshToken(ctx context.Context, token string) (Authenticatable, error)
- func (ti *DefaultTokenIssuer) ValidateRefreshTokenWith(validateRefreshTokenWith ValidateRefreshTokenFunc)
- type ECDSAKeyProvider
- type ErrorResponse
- type ExtractSessionMetadataFunc
- type GenerateSessionIDFunc
- type GetHashedPasswordFunc
- type GetSessionFunc
- type GoAuth
- func (ga *GoAuth) Authenticate(ctx context.Context, strategy string, params AuthParams) (*AuthResult, error)
- func (ga *GoAuth) AuthenticateAndIssueTokenPair(ctx context.Context, strategy string, params AuthParams) (*AuthResult, *TokenPair, error)
- func (ga *GoAuth) AuthenticateAndIssueTokens(ctx context.Context, strategy string, params AuthParams) (authResult *AuthResult, accessToken *Token, refreshToken *Token, err error)
- func (ga *GoAuth) GetTokenIssuer() TokenIssuer
- func (ga *GoAuth) HasStrategy(name string) bool
- func (ga *GoAuth) IssueTokenPair(ctx context.Context, authenticatable Authenticatable) (*TokenPair, error)
- func (ga *GoAuth) IssueTokens(ctx context.Context, authenticatable Authenticatable) (accessToken *Token, refreshToken *Token, err error)
- func (ga *GoAuth) ListSessions(ctx context.Context, authenticatable Authenticatable) ([]*SessionInfo, error)
- func (ga *GoAuth) ListStrategies() []string
- func (ga *GoAuth) RefreshToken(ctx context.Context, token string) (accessToken *Token, refreshToken *Token, err error)
- func (ga *GoAuth) RefreshTokenPair(ctx context.Context, token string) (*TokenPair, error)
- func (ga *GoAuth) RegisterSingleton()
- func (ga *GoAuth) RegisterSingletonOnce() error
- func (ga *GoAuth) RegisterStrategy(strategy Strategy)
- func (ga *GoAuth) RevokeAllTokens(ctx context.Context, authenticatable Authenticatable) error
- func (ga *GoAuth) RevokeSession(ctx context.Context, authenticatable Authenticatable, sessionID string) error
- func (ga *GoAuth) RevokeToken(ctx context.Context, token string) error
- func (ga *GoAuth) SetEventHooks(hooks AuthEventHooks)
- func (ga *GoAuth) SetTokenIssuer(tokenIssuer TokenIssuer)
- func (ga *GoAuth) UnregisterStrategy(name string) error
- type HMACKeyProvider
- type InternalError
- type JWTStrategy
- func (js *JWTStrategy) Authenticate(ctx context.Context, params AuthParams) (Authenticatable, error)
- func (js *JWTStrategy) GetTokenIssuer() TokenIssuer
- func (js *JWTStrategy) Name() string
- func (js *JWTStrategy) SetTokenIssuer(ti TokenIssuer)
- func (js *JWTStrategy) WithClaimsConverter(convert ConvertClaimsFunc) *JWTStrategy
- func (js *JWTStrategy) WithExpectedType(tokenType TokenType) *JWTStrategy
- func (js *JWTStrategy) WithName(name string) *JWTStrategy
- func (js *JWTStrategy) WithRevocationCheck(check CheckRevokedFunc) *JWTStrategy
- type KeyProvider
- type ListSessionsFunc
- type LocalStrategy
- func (ls *LocalStrategy) Authenticate(ctx context.Context, params AuthParams) (Authenticatable, error)
- func (ls *LocalStrategy) Name() string
- func (ls *LocalStrategy) SetLookupUser(fn LookupUserFunc)
- func (ls *LocalStrategy) WithName(name string) *LocalStrategy
- func (ls *LocalStrategy) WithPasswordValidator(validate ValidatePasswordFunc, getHashed GetHashedPasswordFunc) *LocalStrategy
- func (ls *LocalStrategy) WithRateLimiter(check RateLimitCheckFunc, record RecordAttemptFunc) *LocalStrategy
- func (ls *LocalStrategy) WithUsernameNormalizer(normalize NormalizeUsernameFunc) *LocalStrategy
- type LookupUserFunc
- type NoOpEventHooks
- func (h *NoOpEventHooks) OnAfterAuthenticate(ctx context.Context, strategy string, result *AuthResult, err error)
- func (h *NoOpEventHooks) OnBeforeAuthenticate(ctx context.Context, strategy string, params AuthParams) error
- func (h *NoOpEventHooks) OnSessionCreated(ctx context.Context, authenticatable Authenticatable, session *SessionInfo)
- func (h *NoOpEventHooks) OnSessionRevoked(ctx context.Context, authenticatable Authenticatable, session *SessionInfo)
- func (h *NoOpEventHooks) OnTokenIssued(ctx context.Context, authenticatable Authenticatable, tokens *TokenPair)
- func (h *NoOpEventHooks) OnTokenRevoked(ctx context.Context, authenticatable Authenticatable, token string)
- type NormalizeUsernameFunc
- type NotFoundError
- type PasswordValidator
- type PasswordValidatorFunc
- type RSAKeyProvider
- type RateLimitCheckFunc
- type RateLimitError
- type RateLimiter
- type RecordAttemptFunc
- type RevokeAllSessionsFunc
- type RevokeRefreshTokenFunc
- type RevokeSessionFunc
- type SessionAwareTokenIssuer
- type SessionError
- type SessionInfo
- type SessionTokenIssuer
- func (ti *SessionTokenIssuer) ConvertAccessTokenClaims(ctx context.Context, claims *TokenClaims) (Authenticatable, error)
- func (ti *SessionTokenIssuer) CreateAccessToken(ctx context.Context, auth Authenticatable) (*Token, error)
- func (ti *SessionTokenIssuer) CreateAccessTokenWithSession(ctx context.Context, auth Authenticatable, sessionID string) (*Token, error)
- func (ti *SessionTokenIssuer) CreateRefreshToken(ctx context.Context, auth Authenticatable, oldToken *string) (*Token, error)
- func (ti *SessionTokenIssuer) DecodeAccessToken(ctx context.Context, tokenStr string) (*TokenClaims, error)
- func (ti *SessionTokenIssuer) GetSession(ctx context.Context, token string) (*SessionInfo, error)
- func (ti *SessionTokenIssuer) IssueTokenPair(ctx context.Context, auth Authenticatable, oldRefreshToken *string) (*TokenPair, error)
- func (ti *SessionTokenIssuer) ListSessions(ctx context.Context, auth Authenticatable) ([]*SessionInfo, error)
- func (ti *SessionTokenIssuer) RevokeAllSessions(ctx context.Context, auth Authenticatable) error
- func (ti *SessionTokenIssuer) RevokeRefreshToken(ctx context.Context, token string) error
- func (ti *SessionTokenIssuer) RevokeSession(ctx context.Context, auth Authenticatable, sessionID string) error
- func (ti *SessionTokenIssuer) ValidateRefreshToken(ctx context.Context, token string) (Authenticatable, error)
- type SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) Build() (*SessionTokenIssuer, error)
- func (b *SessionTokenIssuerBuilder) WithAccessTokenTTL(ttl time.Duration) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithAudience(audience []string) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithClaimsConverter(fn ConvertAccessTokenClaimsFunc) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithExtraClaims(fn SetExtraClaimsFunc) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithGetSession(fn GetSessionFunc) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithHMACSecret(secret []byte, method SigningMethod) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithIssuer(issuer string) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithKeyProvider(kp KeyProvider) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithListSessions(fn ListSessionsFunc) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithRSAKeys(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey, method SigningMethod) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithRefreshTokenTTL(ttl time.Duration) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithRegisteredClaims(fn SetRegisteredClaimsFunc) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithSessionIDGenerator(fn GenerateSessionIDFunc) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithSessionMetadataExtractor(fn ExtractSessionMetadataFunc) *SessionTokenIssuerBuilder
- func (b *SessionTokenIssuerBuilder) WithSessionStore(store StoreSessionFunc, validate ValidateSessionFunc, revoke RevokeSessionFunc, ...) *SessionTokenIssuerBuilder
- type SetExtraClaimsFunc
- type SetRegisteredClaimsFunc
- type SigningMethod
- type StoreRefreshTokenFunc
- type StoreSessionFunc
- type Strategy
- type Token
- type TokenClaims
- type TokenError
- type TokenIssuer
- type TokenPair
- type TokenRevoker
- type TokenType
- type User
- type ValidatePasswordFunc
- type ValidateRefreshTokenFunc
- type ValidateSessionFunc
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
var ( // Credential errors ErrInvalidCredentials = &CredentialError{Msg: "invalid credentials"} ErrUserNotFound = &CredentialError{Msg: "user not found"} // Token errors ErrMissingToken = &TokenError{Msg: "token is required"} ErrInvalidToken = &TokenError{Msg: "invalid token"} ErrExpiredToken = &TokenError{Msg: "expired token"} ErrTokenRevoked = &TokenError{Msg: "token has been revoked"} ErrTokenTypeMismatch = &TokenError{Msg: "unexpected token type"} // Config errors ErrTokenIssuerUnset = &ConfigError{Msg: "token issuer is not set"} ErrKeyProviderUnset = &ConfigError{Msg: "key provider is not set"} ErrSessionStoreUnset = &ConfigError{Msg: "session store is not set"} // Not found errors ErrStrategyNotFound = &NotFoundError{Msg: "strategy not found"} ErrSessionNotFound = &NotFoundError{Msg: "session not found"} // Rate limit errors ErrRateLimitExceeded = &RateLimitError{Msg: "rate limit exceeded"} )
Convenience sentinels for common cases (use errors.As to match by type).
Functions ¶
func ErrorCodeForError ¶
ErrorCodeForError returns a stable, client-facing error code string. Use alongside HTTPStatusForError to build consistent error responses.
func HTTPStatusForError ¶
HTTPStatusForError maps typed goauth errors to an HTTP status code. Fallthrough defaults to 500 for unknown error types.
func NewConfigError ¶
func NewInternalError ¶
func NewNotFoundError ¶
func NewTokenError ¶
func ReplaceSingletonForTest ¶
func ReplaceSingletonForTest(ga *GoAuth) (restore func())
ReplaceSingletonForTest replaces the current singleton and returns a restore function that reverts to the previous instance. Intended for tests.
func RetryAfterForError ¶
RetryAfterForError returns the Retry-After header value for rate limit errors Returns 0 if the error is not a rate limit error
Types ¶
type AuthEventHooks ¶
type AuthEventHooks interface {
// OnBeforeAuthenticate is called before authentication
// Return an error to prevent authentication (e.g., rate limiting)
OnBeforeAuthenticate(ctx context.Context, strategy string, params AuthParams) error
// OnAfterAuthenticate is called after authentication (success or failure)
OnAfterAuthenticate(ctx context.Context, strategy string, result *AuthResult, err error)
// OnTokenIssued is called when tokens are issued
OnTokenIssued(ctx context.Context, authenticatable Authenticatable, tokens *TokenPair)
// OnTokenRevoked is called when a token is revoked
OnTokenRevoked(ctx context.Context, authenticatable Authenticatable, token string)
// OnSessionCreated is called when a new session is created
OnSessionCreated(ctx context.Context, authenticatable Authenticatable, session *SessionInfo)
// OnSessionRevoked is called when a session is revoked
OnSessionRevoked(ctx context.Context, authenticatable Authenticatable, session *SessionInfo)
}
AuthEventHooks provides hooks for authentication events Implement this interface to add custom logic (logging, audit, rate limiting, etc.)
type AuthParams ¶
AuthParams contains authentication parameters passed to strategies
func (*AuthParams) GetExtra ¶
func (ap *AuthParams) GetExtra(key string) (any, bool)
GetExtra returns the value for a key from Extra map
func (*AuthParams) GetExtraBool ¶
func (ap *AuthParams) GetExtraBool(key string) (bool, bool)
GetExtraBool returns a bool value from Extra map
func (*AuthParams) GetExtraInt ¶
func (ap *AuthParams) GetExtraInt(key string) (int, bool)
GetExtraInt returns an int value from Extra map
func (*AuthParams) GetExtraString ¶
func (ap *AuthParams) GetExtraString(key string) (string, bool)
GetExtraString returns a string value from Extra map
func (*AuthParams) Validate ¶
func (ap *AuthParams) Validate() error
Validate checks if the AuthParams has valid data for authentication
type AuthResult ¶
type AuthResult struct {
Authenticatable Authenticatable
Strategy string
Metadata map[string]any // NEW: additional context from authentication
}
AuthResult contains the result of a successful authentication
type Authenticatable ¶
type Authenticatable interface {
GetID() string
GetUsername() string
GetEmail() string
GetExtra() map[string]any
}
Authenticatable represents an authenticated entity (user, service, etc.)
type CheckRevokedFunc ¶
CheckRevokedFunc checks if a token has been revoked
type ConfigError ¶
ConfigError indicates misconfiguration or missing required setup.
func (*ConfigError) Error ¶
func (e *ConfigError) Error() string
func (*ConfigError) Unwrap ¶
func (e *ConfigError) Unwrap() error
type ConvertAccessTokenClaimsFunc ¶
type ConvertAccessTokenClaimsFunc func(ctx context.Context, claims *TokenClaims) (Authenticatable, error)
ConvertAccessTokenClaimsFunc converts token claims to an Authenticatable entity
type ConvertClaimsFunc ¶
type ConvertClaimsFunc func(ctx context.Context, claims *TokenClaims) (Authenticatable, error)
ConvertClaimsFunc converts token claims to an Authenticatable
type CredentialError ¶
CredentialError indicates a problem with user-provided credentials such as invalid username/password.
func (*CredentialError) Error ¶
func (e *CredentialError) Error() string
func (*CredentialError) Unwrap ¶
func (e *CredentialError) Unwrap() error
type DefaultTokenIssuer ¶
type DefaultTokenIssuer struct {
// contains filtered or unexported fields
}
DefaultTokenIssuer is a basic implementation of TokenIssuer For multi-session support, use SessionAwareTokenIssuer instead
func NewDefaultTokenIssuer ¶
func NewDefaultTokenIssuer(secret string) *DefaultTokenIssuer
NewDefaultTokenIssuer creates a new DefaultTokenIssuer with sensible defaults
func (*DefaultTokenIssuer) ConvertAccessTokenClaims ¶
func (ti *DefaultTokenIssuer) ConvertAccessTokenClaims(ctx context.Context, claims *TokenClaims) (Authenticatable, error)
ConvertAccessTokenClaims converts token claims to an Authenticatable entity
func (*DefaultTokenIssuer) ConvertAccessTokenClaimsWith ¶
func (ti *DefaultTokenIssuer) ConvertAccessTokenClaimsWith(convertAccessTokenClaimsWith ConvertAccessTokenClaimsFunc)
ConvertAccessTokenClaimsWith sets the callback for converting claims to Authenticatable
func (*DefaultTokenIssuer) CreateAccessToken ¶
func (ti *DefaultTokenIssuer) CreateAccessToken(ctx context.Context, authenticatable Authenticatable) (*Token, error)
CreateAccessToken creates a new JWT access token
func (*DefaultTokenIssuer) CreateRefreshToken ¶
func (ti *DefaultTokenIssuer) CreateRefreshToken(ctx context.Context, authenticatable Authenticatable, oldToken *string) (*Token, error)
CreateRefreshToken creates a new refresh token oldToken is the previous refresh token being rotated (nil for initial login)
func (*DefaultTokenIssuer) DecodeAccessToken ¶
func (ti *DefaultTokenIssuer) DecodeAccessToken(ctx context.Context, token string) (*TokenClaims, error)
DecodeAccessToken parses and validates a JWT access token
func (*DefaultTokenIssuer) RevokeRefreshToken ¶
func (ti *DefaultTokenIssuer) RevokeRefreshToken(ctx context.Context, token string) error
RevokeRefreshToken revokes a refresh token
func (*DefaultTokenIssuer) RevokeRefreshTokenWith ¶
func (ti *DefaultTokenIssuer) RevokeRefreshTokenWith(revokeRefreshTokenWith RevokeRefreshTokenFunc)
RevokeRefreshTokenWith sets the callback for revoking refresh tokens
func (*DefaultTokenIssuer) SetAccessTokenExpiresIn ¶
func (ti *DefaultTokenIssuer) SetAccessTokenExpiresIn(expiresIn time.Duration)
SetAccessTokenExpiresIn sets the access token expiration duration
func (*DefaultTokenIssuer) SetAudience ¶
func (ti *DefaultTokenIssuer) SetAudience(audience []string)
SetAudience sets the JWT audience claim
func (*DefaultTokenIssuer) SetExtraClaimsWith ¶
func (ti *DefaultTokenIssuer) SetExtraClaimsWith(setExtraClaimsWith SetExtraClaimsFunc)
SetExtraClaimsWith sets the callback for adding extra claims to access tokens
func (*DefaultTokenIssuer) SetIssuer ¶
func (ti *DefaultTokenIssuer) SetIssuer(issuer string)
SetIssuer sets the JWT issuer claim
func (*DefaultTokenIssuer) SetRefreshTokenExpiresIn ¶
func (ti *DefaultTokenIssuer) SetRefreshTokenExpiresIn(expiresIn time.Duration)
SetRefreshTokenExpiresIn sets the refresh token expiration duration
func (*DefaultTokenIssuer) SetRegisteredClaimsWith ¶
func (ti *DefaultTokenIssuer) SetRegisteredClaimsWith(setRegisteredClaimsWith SetRegisteredClaimsFunc)
SetRegisteredClaimsWith sets the callback for customizing registered claims
func (*DefaultTokenIssuer) SetSecret ¶
func (ti *DefaultTokenIssuer) SetSecret(secret string)
SetSecret sets the JWT signing secret
func (*DefaultTokenIssuer) StoreRefreshTokenWith ¶
func (ti *DefaultTokenIssuer) StoreRefreshTokenWith(storeRefreshTokenWith StoreRefreshTokenFunc)
StoreRefreshTokenWith sets the callback for storing refresh tokens
func (*DefaultTokenIssuer) ValidateRefreshToken ¶
func (ti *DefaultTokenIssuer) ValidateRefreshToken(ctx context.Context, token string) (Authenticatable, error)
ValidateRefreshToken validates a refresh token and returns the associated user
func (*DefaultTokenIssuer) ValidateRefreshTokenWith ¶
func (ti *DefaultTokenIssuer) ValidateRefreshTokenWith(validateRefreshTokenWith ValidateRefreshTokenFunc)
ValidateRefreshTokenWith sets the callback for validating refresh tokens
type ECDSAKeyProvider ¶
type ECDSAKeyProvider struct {
// contains filtered or unexported fields
}
ECDSAKeyProvider implements KeyProvider for ECDSA-based signing (ES256, ES384, ES512)
func NewECDSAKeyProvider ¶
func NewECDSAKeyProvider(privateKey *ecdsa.PrivateKey, publicKey *ecdsa.PublicKey, method SigningMethod) (*ECDSAKeyProvider, error)
NewECDSAKeyProvider creates a new ECDSA key provider privateKey is required for signing, publicKey is required for verification If only verification is needed, privateKey can be nil
func (*ECDSAKeyProvider) Algorithm ¶
func (p *ECDSAKeyProvider) Algorithm() SigningMethod
func (*ECDSAKeyProvider) Method ¶
func (p *ECDSAKeyProvider) Method() jwt.SigningMethod
func (*ECDSAKeyProvider) SignKey ¶
func (p *ECDSAKeyProvider) SignKey() any
func (*ECDSAKeyProvider) VerifyKey ¶
func (p *ECDSAKeyProvider) VerifyKey() any
type ErrorResponse ¶
type ErrorResponse struct {
Status int `json:"status"`
Code string `json:"code"`
Message string `json:"message"`
Fields map[string]string `json:"fields,omitempty"` // For validation errors
RetryAfter int `json:"retry_after,omitempty"` // For rate limit errors (seconds)
}
ErrorResponse represents a structured HTTP error response
func ErrorResponseForError ¶
func ErrorResponseForError(err error) ErrorResponse
ErrorResponseForError creates a structured error response from an error
type ExtractSessionMetadataFunc ¶
ExtractSessionMetadataFunc extracts session metadata from context (device, IP, etc.)
type GenerateSessionIDFunc ¶
GenerateSessionIDFunc generates a unique session ID
type GetHashedPasswordFunc ¶
type GetHashedPasswordFunc func(user Authenticatable) string
GetHashedPasswordFunc retrieves the hashed password from an Authenticatable Used when password validation is enabled
type GetSessionFunc ¶
type GetSessionFunc func(ctx context.Context, token string) (*SessionInfo, error)
GetSessionFunc gets session info by refresh token
type GoAuth ¶
type GoAuth struct {
// contains filtered or unexported fields
}
GoAuth is the main orchestrator for authentication and token management
func GetInstance ¶
func GetInstance() *GoAuth
GetInstance returns the registered package-wide GoAuth instance, or nil if no instance has been registered.
func (*GoAuth) Authenticate ¶
func (ga *GoAuth) Authenticate(ctx context.Context, strategy string, params AuthParams) (*AuthResult, error)
Authenticate authenticates using the specified strategy
func (*GoAuth) AuthenticateAndIssueTokenPair ¶
func (ga *GoAuth) AuthenticateAndIssueTokenPair(ctx context.Context, strategy string, params AuthParams) (*AuthResult, *TokenPair, error)
AuthenticateAndIssueTokenPair authenticates and issues tokens as a TokenPair
func (*GoAuth) AuthenticateAndIssueTokens ¶
func (ga *GoAuth) AuthenticateAndIssueTokens(ctx context.Context, strategy string, params AuthParams) (authResult *AuthResult, accessToken *Token, refreshToken *Token, err error)
AuthenticateAndIssueTokens authenticates and issues tokens in one call Returns individual tokens (for backward compatibility)
func (*GoAuth) GetTokenIssuer ¶
func (ga *GoAuth) GetTokenIssuer() TokenIssuer
GetTokenIssuer returns the current token issuer
func (*GoAuth) HasStrategy ¶
HasStrategy checks if a strategy is registered
func (*GoAuth) IssueTokenPair ¶
func (ga *GoAuth) IssueTokenPair(ctx context.Context, authenticatable Authenticatable) (*TokenPair, error)
IssueTokenPair creates access and refresh tokens as a TokenPair
func (*GoAuth) IssueTokens ¶
func (ga *GoAuth) IssueTokens(ctx context.Context, authenticatable Authenticatable) (accessToken *Token, refreshToken *Token, err error)
IssueTokens creates access and refresh tokens for an authenticated entity Returns individual tokens (for backward compatibility)
func (*GoAuth) ListSessions ¶
func (ga *GoAuth) ListSessions(ctx context.Context, authenticatable Authenticatable) ([]*SessionInfo, error)
ListSessions lists all active sessions for an authenticated entity Only works if the token issuer implements SessionAwareTokenIssuer
func (*GoAuth) ListStrategies ¶
ListStrategies returns the names of all registered strategies
func (*GoAuth) RefreshToken ¶
func (ga *GoAuth) RefreshToken(ctx context.Context, token string) (accessToken *Token, refreshToken *Token, err error)
RefreshToken validates the old refresh token and issues new tokens Returns individual tokens (for backward compatibility)
func (*GoAuth) RefreshTokenPair ¶
RefreshTokenPair validates the old refresh token and issues new tokens as a TokenPair
func (*GoAuth) RegisterSingleton ¶
func (ga *GoAuth) RegisterSingleton()
RegisterSingleton sets the current GoAuth as the package-wide instance. It overwrites any previously registered instance.
func (*GoAuth) RegisterSingletonOnce ¶
RegisterSingletonOnce sets the singleton only if it hasn't been set yet. Returns an error if an instance is already registered and differs from ga.
func (*GoAuth) RegisterStrategy ¶
RegisterStrategy registers an authentication strategy If a strategy with the same name already exists, it will not be replaced
func (*GoAuth) RevokeAllTokens ¶
func (ga *GoAuth) RevokeAllTokens(ctx context.Context, authenticatable Authenticatable) error
RevokeAllTokens revokes all sessions for an authenticated entity Only works if the token issuer implements SessionAwareTokenIssuer
func (*GoAuth) RevokeSession ¶
func (ga *GoAuth) RevokeSession(ctx context.Context, authenticatable Authenticatable, sessionID string) error
RevokeSession revokes a specific session by ID Only works if the token issuer implements SessionAwareTokenIssuer
func (*GoAuth) RevokeToken ¶
RevokeToken revokes a refresh token
func (*GoAuth) SetEventHooks ¶
func (ga *GoAuth) SetEventHooks(hooks AuthEventHooks)
SetEventHooks sets the event hooks for authentication events
func (*GoAuth) SetTokenIssuer ¶
func (ga *GoAuth) SetTokenIssuer(tokenIssuer TokenIssuer)
SetTokenIssuer sets the token issuer for the GoAuth instance
func (*GoAuth) UnregisterStrategy ¶
UnregisterStrategy removes a registered strategy by name
type HMACKeyProvider ¶
type HMACKeyProvider struct {
// contains filtered or unexported fields
}
HMACKeyProvider implements KeyProvider for HMAC-based signing (HS256, HS384, HS512)
func NewHMACKeyProvider ¶
func NewHMACKeyProvider(secret []byte, method SigningMethod) (*HMACKeyProvider, error)
NewHMACKeyProvider creates a new HMAC key provider
func (*HMACKeyProvider) Algorithm ¶
func (p *HMACKeyProvider) Algorithm() SigningMethod
func (*HMACKeyProvider) Method ¶
func (p *HMACKeyProvider) Method() jwt.SigningMethod
func (*HMACKeyProvider) SignKey ¶
func (p *HMACKeyProvider) SignKey() any
func (*HMACKeyProvider) VerifyKey ¶
func (p *HMACKeyProvider) VerifyKey() any
type InternalError ¶
InternalError indicates an unexpected internal failure (e.g., IO/DB/signing).
func (*InternalError) Error ¶
func (e *InternalError) Error() string
func (*InternalError) Unwrap ¶
func (e *InternalError) Unwrap() error
type JWTStrategy ¶
type JWTStrategy struct {
// contains filtered or unexported fields
}
JWTStrategy implements JWT token-based authentication
func NewJWTStrategy ¶
func NewJWTStrategy(tokenIssuer TokenIssuer) *JWTStrategy
NewJWTStrategy creates a new JWTStrategy with the given token issuer
func (*JWTStrategy) Authenticate ¶
func (js *JWTStrategy) Authenticate(ctx context.Context, params AuthParams) (Authenticatable, error)
Authenticate authenticates using a JWT token
func (*JWTStrategy) GetTokenIssuer ¶
func (js *JWTStrategy) GetTokenIssuer() TokenIssuer
GetTokenIssuer returns the underlying token issuer Deprecated: Access TokenIssuer directly
func (*JWTStrategy) SetTokenIssuer ¶
func (js *JWTStrategy) SetTokenIssuer(ti TokenIssuer)
SetTokenIssuer sets the token issuer (for backward compatibility) Deprecated: Use NewJWTStrategy instead
func (*JWTStrategy) WithClaimsConverter ¶
func (js *JWTStrategy) WithClaimsConverter(convert ConvertClaimsFunc) *JWTStrategy
WithClaimsConverter sets a custom claims to Authenticatable converter This overrides the TokenIssuer's ConvertAccessTokenClaims
func (*JWTStrategy) WithExpectedType ¶
func (js *JWTStrategy) WithExpectedType(tokenType TokenType) *JWTStrategy
WithExpectedType sets the expected token type When set, the strategy will reject tokens that don't match
func (*JWTStrategy) WithName ¶
func (js *JWTStrategy) WithName(name string) *JWTStrategy
WithName sets a custom name for the strategy
func (*JWTStrategy) WithRevocationCheck ¶
func (js *JWTStrategy) WithRevocationCheck(check CheckRevokedFunc) *JWTStrategy
WithRevocationCheck sets the revocation check function
type KeyProvider ¶
type KeyProvider interface {
// Method returns the JWT signing method
Method() jwt.SigningMethod
// SignKey returns the key used for signing tokens
SignKey() any
// VerifyKey returns the key used for verifying tokens
VerifyKey() any
// Algorithm returns the signing method name
Algorithm() SigningMethod
}
KeyProvider abstracts the signing key management for JWT tokens
type ListSessionsFunc ¶
type ListSessionsFunc func(ctx context.Context, auth Authenticatable) ([]*SessionInfo, error)
ListSessionsFunc lists all active sessions for a user
type LocalStrategy ¶
type LocalStrategy struct {
// contains filtered or unexported fields
}
LocalStrategy implements username/password authentication
func NewLocalStrategy ¶
func NewLocalStrategy(lookupUser LookupUserFunc) *LocalStrategy
NewLocalStrategy creates a new LocalStrategy with the given lookup function
func (*LocalStrategy) Authenticate ¶
func (ls *LocalStrategy) Authenticate(ctx context.Context, params AuthParams) (Authenticatable, error)
Authenticate authenticates a user with username/email and password
func (*LocalStrategy) SetLookupUser ¶
func (ls *LocalStrategy) SetLookupUser(fn LookupUserFunc)
LookupUserWith is kept for backward compatibility Deprecated: Use NewLocalStrategy instead
func (*LocalStrategy) WithName ¶
func (ls *LocalStrategy) WithName(name string) *LocalStrategy
WithName sets a custom name for the strategy
func (*LocalStrategy) WithPasswordValidator ¶
func (ls *LocalStrategy) WithPasswordValidator(validate ValidatePasswordFunc, getHashed GetHashedPasswordFunc) *LocalStrategy
WithPasswordValidator sets the password validation function When set, the strategy will validate the password from AuthParams against the hashed password retrieved via GetHashedPassword
func (*LocalStrategy) WithRateLimiter ¶
func (ls *LocalStrategy) WithRateLimiter(check RateLimitCheckFunc, record RecordAttemptFunc) *LocalStrategy
WithRateLimiter sets the rate limiting functions
func (*LocalStrategy) WithUsernameNormalizer ¶
func (ls *LocalStrategy) WithUsernameNormalizer(normalize NormalizeUsernameFunc) *LocalStrategy
WithUsernameNormalizer sets a custom username normalization function
type LookupUserFunc ¶
type LookupUserFunc func(ctx context.Context, params AuthParams) (Authenticatable, error)
LookupUserFunc looks up a user by credentials and returns an Authenticatable The returned user should have a hashed password available if password validation is used
type NoOpEventHooks ¶
type NoOpEventHooks struct{}
NoOpEventHooks is a default implementation of AuthEventHooks that does nothing Embed this in your custom hooks to only override the methods you need
func (*NoOpEventHooks) OnAfterAuthenticate ¶
func (h *NoOpEventHooks) OnAfterAuthenticate(ctx context.Context, strategy string, result *AuthResult, err error)
func (*NoOpEventHooks) OnBeforeAuthenticate ¶
func (h *NoOpEventHooks) OnBeforeAuthenticate(ctx context.Context, strategy string, params AuthParams) error
func (*NoOpEventHooks) OnSessionCreated ¶
func (h *NoOpEventHooks) OnSessionCreated(ctx context.Context, authenticatable Authenticatable, session *SessionInfo)
func (*NoOpEventHooks) OnSessionRevoked ¶
func (h *NoOpEventHooks) OnSessionRevoked(ctx context.Context, authenticatable Authenticatable, session *SessionInfo)
func (*NoOpEventHooks) OnTokenIssued ¶
func (h *NoOpEventHooks) OnTokenIssued(ctx context.Context, authenticatable Authenticatable, tokens *TokenPair)
func (*NoOpEventHooks) OnTokenRevoked ¶
func (h *NoOpEventHooks) OnTokenRevoked(ctx context.Context, authenticatable Authenticatable, token string)
type NormalizeUsernameFunc ¶
NormalizeUsernameFunc normalizes a username (e.g., trim whitespace, lowercase)
type NotFoundError ¶
NotFoundError indicates a required element was not found (e.g., strategy).
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
func (*NotFoundError) Unwrap ¶
func (e *NotFoundError) Unwrap() error
type PasswordValidator ¶
type PasswordValidator interface {
// ValidatePassword checks if the plain password matches the hashed password
ValidatePassword(plain, hashed string) bool
}
PasswordValidator defines the contract for password validation
type PasswordValidatorFunc ¶
PasswordValidatorFunc is a function adapter for PasswordValidator
func (PasswordValidatorFunc) ValidatePassword ¶
func (f PasswordValidatorFunc) ValidatePassword(plain, hashed string) bool
type RSAKeyProvider ¶
type RSAKeyProvider struct {
// contains filtered or unexported fields
}
RSAKeyProvider implements KeyProvider for RSA-based signing (RS256, RS384, RS512)
func NewRSAKeyProvider ¶
func NewRSAKeyProvider(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey, method SigningMethod) (*RSAKeyProvider, error)
NewRSAKeyProvider creates a new RSA key provider privateKey is required for signing, publicKey is required for verification If only verification is needed, privateKey can be nil
func (*RSAKeyProvider) Algorithm ¶
func (p *RSAKeyProvider) Algorithm() SigningMethod
func (*RSAKeyProvider) Method ¶
func (p *RSAKeyProvider) Method() jwt.SigningMethod
func (*RSAKeyProvider) SignKey ¶
func (p *RSAKeyProvider) SignKey() any
func (*RSAKeyProvider) VerifyKey ¶
func (p *RSAKeyProvider) VerifyKey() any
type RateLimitCheckFunc ¶
RateLimitCheckFunc checks if an authentication attempt should be rate limited Returns nil if allowed, RateLimitError if exceeded
type RateLimitError ¶
RateLimitError indicates that rate limit has been exceeded.
func (*RateLimitError) Error ¶
func (e *RateLimitError) Error() string
func (*RateLimitError) Unwrap ¶
func (e *RateLimitError) Unwrap() error
type RateLimiter ¶
type RateLimiter interface {
// CheckRateLimit checks if the authentication attempt is allowed
// Returns nil if allowed, RateLimitError if exceeded
CheckRateLimit(ctx context.Context, identifier string) error
// RecordAttempt records an authentication attempt (success or failure)
RecordAttempt(ctx context.Context, identifier string, success bool)
}
RateLimiter defines the contract for rate limiting authentication attempts
type RecordAttemptFunc ¶
RecordAttemptFunc records an authentication attempt for rate limiting
type RevokeAllSessionsFunc ¶
type RevokeAllSessionsFunc func(ctx context.Context, auth Authenticatable) error
RevokeAllSessionsFunc revokes all sessions for a user
type RevokeRefreshTokenFunc ¶
RevokeRefreshTokenFunc revokes a refresh token
type RevokeSessionFunc ¶
type RevokeSessionFunc func(ctx context.Context, auth Authenticatable, sessionID string) error
RevokeSessionFunc revokes a specific session
type SessionAwareTokenIssuer ¶
type SessionAwareTokenIssuer interface {
TokenIssuer
// GetSession returns session information for a refresh token
GetSession(ctx context.Context, token string) (*SessionInfo, error)
// RevokeSession revokes a specific session by ID
RevokeSession(ctx context.Context, authenticatable Authenticatable, sessionID string) error
// RevokeAllSessions revokes all sessions for an authenticated entity
RevokeAllSessions(ctx context.Context, authenticatable Authenticatable) error
// ListSessions returns all active sessions for an authenticated entity
ListSessions(ctx context.Context, authenticatable Authenticatable) ([]*SessionInfo, error)
}
SessionAwareTokenIssuer extends TokenIssuer with session management capabilities
type SessionError ¶
SessionError indicates session-related problems.
func (*SessionError) Error ¶
func (e *SessionError) Error() string
func (*SessionError) Unwrap ¶
func (e *SessionError) Unwrap() error
type SessionInfo ¶
type SessionInfo struct {
ID string
UserID string
CreatedAt time.Time
ExpiresAt time.Time
Metadata map[string]any // device, IP, user agent, location, etc.
}
SessionInfo contains session metadata for multi-session support
func (*SessionInfo) GetMetadata ¶
func (s *SessionInfo) GetMetadata(key string) (any, bool)
GetMetadata returns a value from session metadata
func (*SessionInfo) GetMetadataString ¶
func (s *SessionInfo) GetMetadataString(key string) (string, bool)
GetMetadataString returns a string value from session metadata
func (*SessionInfo) IsExpired ¶
func (s *SessionInfo) IsExpired() bool
IsExpired checks if the session has expired
type SessionTokenIssuer ¶
type SessionTokenIssuer struct {
// contains filtered or unexported fields
}
SessionTokenIssuer implements TokenIssuer and SessionAwareTokenIssuer interfaces with full multi-session support and configurable signing methods
func (*SessionTokenIssuer) ConvertAccessTokenClaims ¶
func (ti *SessionTokenIssuer) ConvertAccessTokenClaims(ctx context.Context, claims *TokenClaims) (Authenticatable, error)
ConvertAccessTokenClaims converts token claims to an Authenticatable entity
func (*SessionTokenIssuer) CreateAccessToken ¶
func (ti *SessionTokenIssuer) CreateAccessToken(ctx context.Context, auth Authenticatable) (*Token, error)
CreateAccessToken creates a new JWT access token with session ID
func (*SessionTokenIssuer) CreateAccessTokenWithSession ¶
func (ti *SessionTokenIssuer) CreateAccessTokenWithSession(ctx context.Context, auth Authenticatable, sessionID string) (*Token, error)
CreateAccessTokenWithSession creates a new JWT access token with a specific session ID
func (*SessionTokenIssuer) CreateRefreshToken ¶
func (ti *SessionTokenIssuer) CreateRefreshToken(ctx context.Context, auth Authenticatable, oldToken *string) (*Token, error)
CreateRefreshToken creates a new refresh token with session
func (*SessionTokenIssuer) DecodeAccessToken ¶
func (ti *SessionTokenIssuer) DecodeAccessToken(ctx context.Context, tokenStr string) (*TokenClaims, error)
DecodeAccessToken parses and validates a JWT access token
func (*SessionTokenIssuer) GetSession ¶
func (ti *SessionTokenIssuer) GetSession(ctx context.Context, token string) (*SessionInfo, error)
GetSession returns session information for a refresh token
func (*SessionTokenIssuer) IssueTokenPair ¶
func (ti *SessionTokenIssuer) IssueTokenPair(ctx context.Context, auth Authenticatable, oldRefreshToken *string) (*TokenPair, error)
IssueTokenPair creates both access and refresh tokens in one call This is a convenience method that ensures tokens share the same session ID
func (*SessionTokenIssuer) ListSessions ¶
func (ti *SessionTokenIssuer) ListSessions(ctx context.Context, auth Authenticatable) ([]*SessionInfo, error)
ListSessions returns all active sessions for an authenticated entity
func (*SessionTokenIssuer) RevokeAllSessions ¶
func (ti *SessionTokenIssuer) RevokeAllSessions(ctx context.Context, auth Authenticatable) error
RevokeAllSessions revokes all sessions for an authenticated entity
func (*SessionTokenIssuer) RevokeRefreshToken ¶
func (ti *SessionTokenIssuer) RevokeRefreshToken(ctx context.Context, token string) error
RevokeRefreshToken revokes a refresh token by revoking its session
func (*SessionTokenIssuer) RevokeSession ¶
func (ti *SessionTokenIssuer) RevokeSession(ctx context.Context, auth Authenticatable, sessionID string) error
RevokeSession revokes a specific session by ID
func (*SessionTokenIssuer) ValidateRefreshToken ¶
func (ti *SessionTokenIssuer) ValidateRefreshToken(ctx context.Context, token string) (Authenticatable, error)
ValidateRefreshToken validates a refresh token and returns the associated user
type SessionTokenIssuerBuilder ¶
type SessionTokenIssuerBuilder struct {
// contains filtered or unexported fields
}
SessionTokenIssuerBuilder provides a fluent API for building SessionTokenIssuer
func NewSessionAwareTokenIssuer ¶
func NewSessionAwareTokenIssuer() *SessionTokenIssuerBuilder
NewSessionAwareTokenIssuer creates a new builder for SessionTokenIssuer
func (*SessionTokenIssuerBuilder) Build ¶
func (b *SessionTokenIssuerBuilder) Build() (*SessionTokenIssuer, error)
Build creates the SessionTokenIssuer, returning any configuration errors
func (*SessionTokenIssuerBuilder) WithAccessTokenTTL ¶
func (b *SessionTokenIssuerBuilder) WithAccessTokenTTL(ttl time.Duration) *SessionTokenIssuerBuilder
WithAccessTokenTTL sets the access token time-to-live
func (*SessionTokenIssuerBuilder) WithAudience ¶
func (b *SessionTokenIssuerBuilder) WithAudience(audience []string) *SessionTokenIssuerBuilder
WithAudience sets the JWT audience claim
func (*SessionTokenIssuerBuilder) WithClaimsConverter ¶
func (b *SessionTokenIssuerBuilder) WithClaimsConverter(fn ConvertAccessTokenClaimsFunc) *SessionTokenIssuerBuilder
WithClaimsConverter sets the claims to Authenticatable converter
func (*SessionTokenIssuerBuilder) WithExtraClaims ¶
func (b *SessionTokenIssuerBuilder) WithExtraClaims(fn SetExtraClaimsFunc) *SessionTokenIssuerBuilder
WithExtraClaims sets the extra claims callback
func (*SessionTokenIssuerBuilder) WithGetSession ¶
func (b *SessionTokenIssuerBuilder) WithGetSession(fn GetSessionFunc) *SessionTokenIssuerBuilder
WithGetSession sets the get session callback
func (*SessionTokenIssuerBuilder) WithHMACSecret ¶
func (b *SessionTokenIssuerBuilder) WithHMACSecret(secret []byte, method SigningMethod) *SessionTokenIssuerBuilder
WithHMACSecret configures HMAC signing with the given secret
func (*SessionTokenIssuerBuilder) WithIssuer ¶
func (b *SessionTokenIssuerBuilder) WithIssuer(issuer string) *SessionTokenIssuerBuilder
WithIssuer sets the JWT issuer claim
func (*SessionTokenIssuerBuilder) WithKeyProvider ¶
func (b *SessionTokenIssuerBuilder) WithKeyProvider(kp KeyProvider) *SessionTokenIssuerBuilder
WithKeyProvider sets a custom key provider
func (*SessionTokenIssuerBuilder) WithListSessions ¶
func (b *SessionTokenIssuerBuilder) WithListSessions(fn ListSessionsFunc) *SessionTokenIssuerBuilder
WithListSessions sets the list sessions callback
func (*SessionTokenIssuerBuilder) WithRSAKeys ¶
func (b *SessionTokenIssuerBuilder) WithRSAKeys(privateKey *rsa.PrivateKey, publicKey *rsa.PublicKey, method SigningMethod) *SessionTokenIssuerBuilder
WithRSAKeys configures RSA signing with the given keys
func (*SessionTokenIssuerBuilder) WithRefreshTokenTTL ¶
func (b *SessionTokenIssuerBuilder) WithRefreshTokenTTL(ttl time.Duration) *SessionTokenIssuerBuilder
WithRefreshTokenTTL sets the refresh token time-to-live
func (*SessionTokenIssuerBuilder) WithRegisteredClaims ¶
func (b *SessionTokenIssuerBuilder) WithRegisteredClaims(fn SetRegisteredClaimsFunc) *SessionTokenIssuerBuilder
WithRegisteredClaims sets the registered claims callback
func (*SessionTokenIssuerBuilder) WithSessionIDGenerator ¶
func (b *SessionTokenIssuerBuilder) WithSessionIDGenerator(fn GenerateSessionIDFunc) *SessionTokenIssuerBuilder
WithSessionIDGenerator sets a custom session ID generator
func (*SessionTokenIssuerBuilder) WithSessionMetadataExtractor ¶
func (b *SessionTokenIssuerBuilder) WithSessionMetadataExtractor(fn ExtractSessionMetadataFunc) *SessionTokenIssuerBuilder
WithSessionMetadataExtractor sets a custom session metadata extractor
func (*SessionTokenIssuerBuilder) WithSessionStore ¶
func (b *SessionTokenIssuerBuilder) WithSessionStore( store StoreSessionFunc, validate ValidateSessionFunc, revoke RevokeSessionFunc, revokeAll RevokeAllSessionsFunc, ) *SessionTokenIssuerBuilder
WithSessionStore sets the session storage callbacks
type SetExtraClaimsFunc ¶
type SetExtraClaimsFunc func(ctx context.Context, authenticatable Authenticatable) map[string]any
SetExtraClaimsFunc returns extra claims to include in the access token
type SetRegisteredClaimsFunc ¶
type SetRegisteredClaimsFunc func(ctx context.Context, authenticatable Authenticatable) jwt.RegisteredClaims
SetRegisteredClaimsFunc returns custom registered claims for the access token
type SigningMethod ¶
type SigningMethod string
SigningMethod represents supported JWT signing algorithms
const ( // HMAC signing methods (symmetric) HS256 SigningMethod = "HS256" HS384 SigningMethod = "HS384" HS512 SigningMethod = "HS512" // RSA signing methods (asymmetric) RS256 SigningMethod = "RS256" RS384 SigningMethod = "RS384" RS512 SigningMethod = "RS512" // ECDSA signing methods (asymmetric) ES256 SigningMethod = "ES256" ES384 SigningMethod = "ES384" ES512 SigningMethod = "ES512" )
type StoreRefreshTokenFunc ¶
type StoreRefreshTokenFunc func(ctx context.Context, authenticatable Authenticatable, token *Token, oldToken *string) error
StoreRefreshTokenFunc stores a refresh token oldToken is the previous refresh token being rotated (nil for initial login)
type StoreSessionFunc ¶
type StoreSessionFunc func(ctx context.Context, auth Authenticatable, session *SessionInfo, token *Token, oldToken *string) error
StoreSessionFunc stores a session and its refresh token oldToken is the previous refresh token being rotated (nil for initial login)
type Strategy ¶
type Strategy interface {
Name() string
Authenticate(ctx context.Context, params AuthParams) (Authenticatable, error)
}
Strategy defines the authentication strategy interface
type Token ¶
type Token struct {
Value string
Type TokenType
ExpiresIn time.Duration
IssuedAt time.Time
SessionID string // For multi-session support
}
Token represents an authentication token (access or refresh)
type TokenClaims ¶
type TokenClaims struct {
jwt.RegisteredClaims
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
TokenType TokenType `json:"typ,omitempty"` // "access" or "refresh"
SessionID string `json:"sid,omitempty"` // Session identifier for multi-session support
ExtraClaims map[string]any `json:"ext,omitempty"`
}
TokenClaims represents the JWT claims for access tokens
func (*TokenClaims) GetExtraClaim ¶
func (tc *TokenClaims) GetExtraClaim(key string) (any, bool)
GetExtraClaim returns a value from extra claims
func (*TokenClaims) GetExtraClaimBool ¶
func (tc *TokenClaims) GetExtraClaimBool(key string) (bool, bool)
GetExtraClaimBool returns a bool value from extra claims
func (*TokenClaims) GetExtraClaimString ¶
func (tc *TokenClaims) GetExtraClaimString(key string) (string, bool)
GetExtraClaimString returns a string value from extra claims
func (*TokenClaims) IsAccessToken ¶
func (tc *TokenClaims) IsAccessToken() bool
IsAccessToken returns true if this is an access token
func (*TokenClaims) IsRefreshToken ¶
func (tc *TokenClaims) IsRefreshToken() bool
IsRefreshToken returns true if this is a refresh token
type TokenError ¶
TokenError indicates problems related to tokens (missing/invalid/expired).
func (*TokenError) Error ¶
func (e *TokenError) Error() string
func (*TokenError) Unwrap ¶
func (e *TokenError) Unwrap() error
type TokenIssuer ¶
type TokenIssuer interface {
// CreateAccessToken generates a new access token for the authenticated entity
CreateAccessToken(ctx context.Context, authenticatable Authenticatable) (*Token, error)
// CreateRefreshToken generates a new refresh token
// oldToken is the previous refresh token being rotated (nil for initial login)
CreateRefreshToken(ctx context.Context, authenticatable Authenticatable, oldToken *string) (*Token, error)
// DecodeAccessToken parses and validates an access token, returning its claims
DecodeAccessToken(ctx context.Context, token string) (*TokenClaims, error)
// ConvertAccessTokenClaims converts token claims back to an Authenticatable entity
ConvertAccessTokenClaims(ctx context.Context, claims *TokenClaims) (Authenticatable, error)
// ValidateRefreshToken validates a refresh token and returns the associated entity
ValidateRefreshToken(ctx context.Context, token string) (Authenticatable, error)
// RevokeRefreshToken invalidates a refresh token
RevokeRefreshToken(ctx context.Context, token string) error
}
TokenIssuer defines the contract for token creation and validation
type TokenRevoker ¶
type TokenRevoker interface {
// IsRevoked checks if a token has been revoked
IsRevoked(ctx context.Context, token string) bool
// Revoke marks a token as revoked
Revoke(ctx context.Context, token string) error
}
TokenRevoker defines the contract for checking token revocation
type ValidatePasswordFunc ¶
ValidatePasswordFunc validates a plain password against a hashed password
type ValidateRefreshTokenFunc ¶
type ValidateRefreshTokenFunc func(ctx context.Context, token string) (Authenticatable, error)
ValidateRefreshTokenFunc validates a refresh token and returns the associated user
type ValidateSessionFunc ¶
type ValidateSessionFunc func(ctx context.Context, token string) (Authenticatable, *SessionInfo, error)
ValidateSessionFunc validates a refresh token and returns the user and session
type ValidationError ¶
type ValidationError struct {
Msg string
Fields map[string]string // field name -> error message
Err error
}
ValidationError indicates validation failure on input parameters.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
func (*ValidationError) GetFieldError ¶
func (e *ValidationError) GetFieldError(field string) (string, bool)
GetFieldError returns the error message for a specific field
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error