Documentation
¶
Overview ¶
Package auth provides authentication primitives (JWT issuance, stateful repositories, HTTP helpers) plus lifecycle extension points for downstream admin workflows.
User lifecycle:
- Users carry a UserStatus field that is persisted via Bun. Statuses cover pending, active, suspended, disabled, and archived flows so every product can opt into the same invariants.
- UserStateMachine centralizes the transition graph, timestamp handling, hooks, and persistence. Embed the shared Users repository and invoke Transition with ActorRef metadata whenever an admin moves an account. Hook failures route through a configurable error handler so production services can translate panics into domain errors.
Activity sinks:
- ActivitySink is a light-weight audit emitter used by Auther and the state machine to describe lifecycle, login, impersonation, and password reset events. Sinks run best-effort (errors are logged) so you can forward to a database or queue without blocking authentication.
Claims decoration:
- ClaimsDecorator is invoked before JWTs are signed. Decorators may enrich extension fields such as resource roles or metadata while protected claims (sub, iss, aud, exp, etc.) remain immutable. Combine WithClaimsDecorator with ActivitySink to keep lifecycle state and issued tokens consistent.
Index ¶
- Constants
- Variables
- func Can(ctx context.Context, resource, permission string) bool
- func CanFromRouter(ctx router.Context, resource, permission string) bool
- func ComparePasswordAndHash(password, hash string) error
- func ContextEnricherAdapter(c context.Context, claims jwtware.AuthClaims) context.Context
- func DefaultPermissionsCacheKeyFromContext(ctx context.Context) (string, bool)
- func GetMigrationsFS() embed.FS
- func GetTemplateUser(ctx router.Context, userKey string) (any, bool)
- func HasUserUUID(session Session) bool
- func HashPassword(password string) (string, error)
- func IsMalformedError(err error) bool
- func IsOutsideThresholdPeriod(t time.Time, pattern string) (bool, error)
- func IsTokenExpiredError(err error) bool
- func IsWithinThresholdPeriod(t time.Time, pattern string) (bool, error)
- func MergeTemplateData(ctx router.Context, data router.ViewContext) router.ViewContext
- func MintScopedToken(tokenService TokenService, identity Identity, resourceRoles map[string]string, ...) (string, time.Time, error)
- func MustValidateResolverConfigured(strict bool, resolver PermissionResolverFunc)
- func NewPasswordResetsRepository(db *bun.DB) repository.Repository[*PasswordReset]
- func PermissionsVersionFromClaims(claims AuthClaims) string
- func PermissionsVersionFromContext(ctx context.Context) string
- func RandomPasswordHash() string
- func RegisterAuthRoutes[T any](app router.Router[T], opts ...AuthControllerOption)
- func RegisterValidationListeners(cfg *jwtware.Config, listeners ...ValidationListener)
- func ResolveLogger(name string, provider LoggerProvider, logger Logger) (LoggerProvider, Logger)
- func SetPermissionsVersionMetadata(claims *JWTClaims, version string)
- func TemplateHelpers() map[string]any
- func TemplateHelpersWithRouter(ctx router.Context, userKey string) map[string]any
- func TemplateHelpersWithUser(user *User) map[string]any
- func TokenIDFromContext(ctx context.Context) (string, bool)
- func ValidateResolverConfigured(strict bool, resolver PermissionResolverFunc) error
- func ValidateStringEquals(str string) validation.RuleFunc
- func WithActorContext(ctx context.Context, actor *ActorContext) context.Context
- func WithClaimsContext(r context.Context, claims AuthClaims) context.Context
- func WithContext(r context.Context, user *User) context.Context
- func WithResolvedPermissionsCache(ctx context.Context) context.Context
- type AccountRegistrerer
- type AccountVerificationHandler
- type AccountVerificationMesage
- type AccountVerificationResponse
- type ActivityEvent
- type ActivityEventType
- type ActivitySink
- type ActivitySinkFunc
- type ActorContext
- type ActorRef
- type AuthClaims
- type AuthController
- func (a *AuthController) LogOut(ctx router.Context) error
- func (a *AuthController) LoginPost(ctx router.Context) error
- func (a *AuthController) LoginShow(ctx router.Context) error
- func (a *AuthController) PasswordResetExecute(ctx router.Context) error
- func (a *AuthController) PasswordResetForm(ctx router.Context) error
- func (a *AuthController) PasswordResetGet(ctx router.Context) error
- func (a *AuthController) PasswordResetPost(ctx router.Context) error
- func (a *AuthController) RegistrationCreate(ctx router.Context) error
- func (a *AuthController) RegistrationShow(ctx router.Context) error
- func (a *AuthController) WithLogger(l Logger) *AuthController
- type AuthControllerOption
- func WithAuthControllerActivitySink(sink ActivitySink) AuthControllerOption
- func WithAuthControllerRedirect(r string) AuthControllerOption
- func WithAuthControllerRoutes(r *AuthControllerRoutes) AuthControllerOption
- func WithAuthControllerUseHashID(v bool) AuthControllerOption
- func WithAuthControllerViews(v *AuthControllerViews) AuthControllerOption
- func WithControllerLogger(logger Logger) AuthControllerOption
- func WithControllerLoggerProvider(provider LoggerProvider) AuthControllerOption
- func WithErrorHandler(errHandler router.ErrorHandler) AuthControllerOption
- func WithFeatureGate(featureGate gate.FeatureGate) AuthControllerOption
- type AuthControllerRoutes
- type AuthControllerViews
- type Authenticator
- type Auther
- func (s *Auther) IdentityFromSession(ctx context.Context, session Session) (Identity, error)
- func (s *Auther) Impersonate(ctx context.Context, identifier string) (string, error)
- func (s *Auther) Login(ctx context.Context, identifier, password string) (string, error)
- func (a *Auther) NewWSAuthMiddleware(config ...router.WSAuthConfig) router.WebSocketMiddleware
- func (s Auther) SessionFromToken(raw string) (Session, error)
- func (s *Auther) TokenService() TokenService
- func (s *Auther) WithActivitySink(sink ActivitySink) *Auther
- func (s *Auther) WithClaimsDecorator(decorator ClaimsDecorator) *Auther
- func (s *Auther) WithLogger(logger Logger) *Auther
- func (s *Auther) WithLoggerProvider(provider LoggerProvider) *Auther
- func (s *Auther) WithResourceRoleProvider(provider ResourceRoleProvider) *Auther
- func (s *Auther) WithTokenSizeGuardrails(warnThresholdBytes, hardLimitBytes int) *Auther
- func (s *Auther) WithTokenValidator(validator TokenValidator) *Auther
- type CachedPermissionsResolver
- func (r *CachedPermissionsResolver) Invalidate(ctx context.Context, key string) error
- func (r *CachedPermissionsResolver) PurgeExpired(ctx context.Context) (int, error)
- func (r *CachedPermissionsResolver) ResolvePermissions(ctx context.Context) ([]string, error)
- func (r *CachedPermissionsResolver) ResolverFunc() PermissionResolverFunc
- func (r *CachedPermissionsResolver) Stats() PermissionResolverStats
- func (r *CachedPermissionsResolver) Store() PermissionCacheStore
- type CachedPermissionsResolverConfig
- type ClaimsDecorator
- type ClaimsDecoratorFunc
- type Config
- type FieldsLogger
- type FinalizePasswordResetHandler
- func (h *FinalizePasswordResetHandler) Execute(ctx context.Context, event FinalizePasswordResetMesasge) error
- func (h *FinalizePasswordResetHandler) WithActivitySink(sink ActivitySink) *FinalizePasswordResetHandler
- func (h *FinalizePasswordResetHandler) WithFeatureGate(featureGate gate.FeatureGate) *FinalizePasswordResetHandler
- func (h *FinalizePasswordResetHandler) WithLogger(logger Logger) *FinalizePasswordResetHandler
- func (h *FinalizePasswordResetHandler) WithLoggerProvider(provider LoggerProvider) *FinalizePasswordResetHandler
- type FinalizePasswordResetMesasge
- type FormattedLogger
- type HTTPAuthenticator
- type HookErrorHandler
- type Identity
- type IdentityProvider
- type InMemoryPermissionCacheStore
- func (s *InMemoryPermissionCacheStore) Delete(_ context.Context, key string) error
- func (s *InMemoryPermissionCacheStore) Get(_ context.Context, key string) ([]string, bool, error)
- func (s *InMemoryPermissionCacheStore) PurgeExpired(_ context.Context) (int, error)
- func (s *InMemoryPermissionCacheStore) Set(_ context.Context, key string, permissions []string, ttl time.Duration) error
- type InMemoryPermissionCacheStoreConfig
- type InitializePasswordResetHandler
- type InitializePasswordResetMessage
- type InitializePasswordResetResponse
- type JWTClaims
- func (c *JWTClaims) CanCreate(resource string) bool
- func (c *JWTClaims) CanDelete(resource string) bool
- func (c *JWTClaims) CanEdit(resource string) bool
- func (c *JWTClaims) CanRead(resource string) bool
- func (c *JWTClaims) ClaimsMetadata() map[string]any
- func (c *JWTClaims) Expires() time.Time
- func (c *JWTClaims) HasRole(role string) bool
- func (c *JWTClaims) IsAtLeast(minRole string) bool
- func (c *JWTClaims) IssuedAt() time.Time
- func (c *JWTClaims) ResourceRoles() map[string]string
- func (c *JWTClaims) Role() string
- func (c *JWTClaims) Subject() string
- func (c *JWTClaims) TokenID() string
- func (c *JWTClaims) UserID() string
- type LegacyLogger
- type Logger
- type LoggerProvider
- type LoginPayload
- type LoginRequest
- type Middleware
- type MultiTokenValidator
- type PasswordAuthenticator
- type PasswordReset
- type PasswordResetRequestPayload
- type PasswordResetStep
- type PasswordResetVerifyPayload
- type PermissionCacheErrorMode
- type PermissionCacheKeyFunc
- type PermissionCacheStore
- type PermissionResolverFunc
- type PermissionResolverStats
- type PurgeablePermissionCacheStore
- type RegisterUserHandler
- type RegisterUserMessage
- type RegistrationCreatePayload
- type RepositoryManager
- type ResourceRoleProvider
- type RoleCapableSession
- type RoleValidator
- type RouteAuthenticator
- func (a RouteAuthenticator) GetCookieDuration() time.Duration
- func (a RouteAuthenticator) GetExtendedCookieDuration() time.Duration
- func (a *RouteAuthenticator) GetRedirect(ctx router.Context, def ...string) string
- func (a *RouteAuthenticator) GetRedirectOrDefault(ctx router.Context) string
- func (a *RouteAuthenticator) Impersonate(c router.Context, identifier string) error
- func (a *RouteAuthenticator) Login(ctx router.Context, payload LoginPayload) error
- func (a *RouteAuthenticator) Logout(ctx router.Context)
- func (a *RouteAuthenticator) MakeClientRouteAuthErrorHandler(optional bool) func(router.Context, error) error
- func (a *RouteAuthenticator) ProtectedRoute(cfg Config, errorHandler func(router.Context, error) error) router.MiddlewareFunc
- func (a *RouteAuthenticator) SetRedirect(ctx router.Context)
- func (a *RouteAuthenticator) WithLogger(l Logger) *RouteAuthenticator
- func (a *RouteAuthenticator) WithLoggerProvider(provider LoggerProvider) *RouteAuthenticator
- func (a *RouteAuthenticator) WithValidationListeners(listeners ...ValidationListener) *RouteAuthenticator
- type ScopedTokenOptions
- type Session
- type SessionObject
- func (s *SessionObject) CanCreate(resource string) bool
- func (s *SessionObject) CanDelete(resource string) bool
- func (s *SessionObject) CanEdit(resource string) bool
- func (s *SessionObject) CanRead(resource string) bool
- func (s *SessionObject) GetAudience() []string
- func (s *SessionObject) GetData() map[string]any
- func (s *SessionObject) GetIssuedAt() *time.Time
- func (s *SessionObject) GetIssuer() string
- func (s *SessionObject) GetUserID() string
- func (s *SessionObject) GetUserUUID() (uuid.UUID, error)
- func (s *SessionObject) HasRole(role string) bool
- func (s *SessionObject) IsAtLeast(minRole UserRole) bool
- func (s SessionObject) String() string
- type StateMachineOption
- func WithStateMachineActivitySink(sink ActivitySink) StateMachineOption
- func WithStateMachineClock(clock func() time.Time) StateMachineOption
- func WithStateMachineHookErrorHandler(handler HookErrorHandler) StateMachineOption
- func WithStateMachineLogger(logger Logger) StateMachineOption
- func WithStateMachineLoggerProvider(provider LoggerProvider) StateMachineOption
- type StatusUpdateOption
- type TokenIDer
- type TokenService
- type TokenServiceAdapter
- type TokenServiceImpl
- func (ts *TokenServiceImpl) Generate(identity Identity, resourceRoles map[string]string) (string, error)
- func (ts *TokenServiceImpl) SignClaims(claims *JWTClaims) (string, error)
- func (ts *TokenServiceImpl) SignClaimsWithType(claims *JWTClaims, tokenType string) (string, error)
- func (ts *TokenServiceImpl) Stats() TokenServiceStats
- func (ts *TokenServiceImpl) Validate(tokenString string) (AuthClaims, error)
- type TokenServiceOption
- type TokenServiceStats
- type TokenValidator
- type TokenValidatorFunc
- type TransitionContext
- type TransitionHook
- type TransitionHookPhase
- type TransitionMetadata
- type TransitionOption
- func WithAfterTransitionHook(h TransitionHook) TransitionOption
- func WithBeforeTransitionHook(h TransitionHook) TransitionOption
- func WithForceTransition() TransitionOption
- func WithSuspensionTime(t time.Time) TransitionOption
- func WithTransitionMetadata(metadata map[string]any) TransitionOption
- func WithTransitionReason(reason string) TransitionOption
- type User
- func (u *User) AddMetadata(key string, val any) *User
- func (u *User) EnsureStatus() *User
- func (u *User) HasStatus(status UserStatus) bool
- func (u *User) IsActive() bool
- func (u *User) IsArchived() bool
- func (u *User) IsDisabled() bool
- func (u *User) IsPending() bool
- func (u *User) IsSuspended() bool
- type UserIdentity
- type UserProvider
- func (u UserProvider) FindIdentityByIdentifier(ctx context.Context, identfier string) (Identity, error)
- func (u UserProvider) VerifyIdentity(ctx context.Context, identifier, password string) (Identity, error)
- func (u *UserProvider) WithLogger(l Logger) *UserProvider
- func (u *UserProvider) WithLoggerProvider(provider LoggerProvider) *UserProvider
- type UserRole
- type UserStateMachine
- type UserStatus
- type UserTracker
- type Users
- type UsersOption
- type ValidationListener
- type WSAuthClaimsAdapter
- func (w *WSAuthClaimsAdapter) CanCreate(resource string) bool
- func (w *WSAuthClaimsAdapter) CanDelete(resource string) bool
- func (w *WSAuthClaimsAdapter) CanEdit(resource string) bool
- func (w *WSAuthClaimsAdapter) CanRead(resource string) bool
- func (w *WSAuthClaimsAdapter) HasRole(role string) bool
- func (w *WSAuthClaimsAdapter) IsAtLeast(minRole string) bool
- func (w *WSAuthClaimsAdapter) Role() string
- func (w *WSAuthClaimsAdapter) Subject() string
- func (w *WSAuthClaimsAdapter) UserID() string
- type WSTokenValidator
Constants ¶
const ( TextCodeInvalidCreds = "INVALID_CREDENTIALS" TextCodeTooManyAttempts = "TOO_MANY_ATTEMPTS" TextCodeSessionNotFound = "SESSION_NOT_FOUND" TextCodeSessionDecodeError = "SESSION_DECODE_ERROR" TextCodeClaimsMappingError = "CLAIMS_MAPPING_ERROR" TextCodeDataParseError = "DATA_PARSE_ERROR" TextCodeEmptyPassword = "EMPTY_PASSWORD_NOT_ALLOWED" TextCodeTokenExpired = "TOKEN_EXPIRED" TextCodeTokenMalformed = "TOKEN_MALFORMED" TextCodeTokenTooLarge = "TOKEN_TOO_LARGE" TextCodeImmutableClaim = "IMMUTABLE_CLAIM_MUTATION" TextCodeAccountSuspended = "ACCOUNT_SUSPENDED" TextCodeAccountDisabled = "ACCOUNT_DISABLED" TextCodeAccountArchived = "ACCOUNT_ARCHIVED" TextCodeAccountPending = "ACCOUNT_PENDING" TextCodeSignupDisabled = "SIGNUP_DISABLED" TextCodePasswordResetDisabled = "PASSWORD_RESET_DISABLED" TextCodePermissionResolverRequired = "PERMISSION_RESOLVER_REQUIRED" )
const ( // ResetUnknownStatus is the unknown status ResetUnknownStatus = "unknown" // ResetRequestedStatus is the requested status ResetRequestedStatus = "requested" // ResetExpiredStatus is the expired status ResetExpiredStatus = "expired" // ResetChangedStatus is the changed status ResetChangedStatus = "changed" )
const ( // DefaultTokenWarnThresholdBytes emits a warning log when a signed JWT reaches // this size. It remains valid unless the hard limit is exceeded. DefaultTokenWarnThresholdBytes = 2048 // DefaultTokenHardLimitBytes rejects tokens larger than this size to reduce // oversized cookie risk in downstream applications. DefaultTokenHardLimitBytes = 4096 )
const ( // TokenTypeSession labels regular auth/session JWTs. TokenTypeSession = "session" // TokenTypeScoped labels short-lived scoped JWTs minted by MintScopedToken. TokenTypeScoped = "scoped" // TokenTypeCustom labels direct TokenService.SignClaims calls. TokenTypeCustom = "custom" )
const ( // PermissionsVersionMetadataKey is the preferred claim metadata key used to // carry permission-set version/etag values across requests. PermissionsVersionMetadataKey = "permissions_version" )
Variables ¶
var CoolDownPeriod = "24h"
CoolDownPeriod is the period in which we enforce a cool down
var ErrIdentityNotFound = errors.New("identity not found", errors.CategoryNotFound). WithCode(errors.CodeNotFound)
ErrIdentityNotFound is returned when an identity cannot be found.
var ErrImmutableClaimMutation = errors.New("claims decorator attempted to mutate immutable claim", errors.CategoryValidation). WithTextCode(TextCodeImmutableClaim). WithCode(errors.CodeBadRequest)
ErrImmutableClaimMutation is returned when a decorator tampers with protected claims.
var ErrInvalidTransition = goerrors.New("invalid user state transition", goerrors.CategoryValidation). WithTextCode(textCodeInvalidTransition). WithCode(goerrors.CodeBadRequest)
ErrInvalidTransition is returned when a requested status change is not allowed.
var ErrMismatchedHashAndPassword = errors.New("the credentials provided are invalid", errors.CategoryAuth). WithTextCode(TextCodeInvalidCreds). WithCode(errors.CodeUnauthorized)
ErrMismatchedHashAndPassword is returned on a failure to check a password hash. The message is generic to avoid leaking information.
var ErrNoEmptyString = errors.New("password can't be an empty string", errors.CategoryValidation). WithTextCode(TextCodeEmptyPassword). WithCode(errors.CodeBadRequest)
ErrNoEmptyString is returned when an empty string is provided for a value that must not be empty, like a password.
var ErrPasswordResetDisabled = errors.New("password reset is currently disabled", errors.CategoryAuthz). WithTextCode(TextCodePasswordResetDisabled). WithCode(errors.CodeForbidden)
ErrPasswordResetDisabled is returned when password reset flows are disabled.
var ErrPermissionResolverRequired = errors.New("permission resolver is required in strict mode", errors.CategoryValidation). WithTextCode(TextCodePermissionResolverRequired). WithCode(errors.CodeBadRequest)
ErrPermissionResolverRequired is returned when strict resolver mode is enabled without a resolver.
var ErrSignupDisabled = errors.New("signups are currently disabled", errors.CategoryAuthz). WithTextCode(TextCodeSignupDisabled). WithCode(errors.CodeForbidden)
ErrSignupDisabled is returned when registrations are turned off by feature gates.
var ErrTerminalState = goerrors.New("user state is terminal", goerrors.CategoryConflict). WithTextCode(textCodeTerminalState). WithCode(goerrors.CodeConflict)
ErrTerminalState is returned when attempting to move away from a terminal status (e.g., archived).
var ErrTokenExpired = errors.New("token is expired", errors.CategoryAuth). WithTextCode(TextCodeTokenExpired). WithCode(errors.CodeUnauthorized)
ErrTokenExpired is returned when a JWT token has expired.
var ErrTokenMalformed = errors.New("token is malformed", errors.CategoryAuth). WithTextCode(TextCodeTokenMalformed). WithCode(errors.CodeBadRequest)
ErrTokenMalformed is returned when a JWT token is malformed.
var ErrTokenTooLarge = errors.New("token exceeds maximum allowed size", errors.CategoryValidation). WithTextCode(TextCodeTokenTooLarge). WithCode(errors.CodeBadRequest)
ErrTokenTooLarge is returned when a signed JWT exceeds configured guardrails.
var ErrTooManyLoginAttempts = errors.New("too many login attempts, please try again later", errors.CategoryRateLimit). WithTextCode(TextCodeTooManyAttempts). WithCode(errors.CodeTooManyRequests)
ErrTooManyLoginAttempts indicates the user has tried to log in too many times.
var ErrUnableToDecodeSession = errors.New("unable to decode session", errors.CategoryAuth). WithTextCode(TextCodeSessionDecodeError). WithCode(errors.CodeUnauthorized)
ErrUnableToDecodeSession is returned when a session token (e.g., JWT) cannot be decoded or parsed.
var ErrUnableToFindSession = errors.New("unable to find session", errors.CategoryAuth). WithTextCode(TextCodeSessionNotFound). WithCode(errors.CodeUnauthorized)
ErrUnableToFindSession is returned when a session (e.g., a cookie) is missing from a request.
var ErrUnableToMapClaims = errors.New("unable to map claims from token", errors.CategoryAuth). WithTextCode(TextCodeClaimsMappingError). WithCode(errors.CodeUnauthorized)
ErrUnableToMapClaims is returned when claims cannot be extracted from a parsed token.
var ErrUnableToParseData = errors.New("unable to parse authentication data", errors.CategoryBadInput). WithTextCode(TextCodeDataParseError). WithCode(errors.CodeBadRequest)
ErrUnableToParseData is returned on a generic data parsing error within the auth context.
var ErrUserArchived = errors.New("user account is archived", errors.CategoryAuth). WithTextCode(TextCodeAccountArchived). WithCode(errors.CodeForbidden)
ErrUserArchived is returned when an account is archived.
var ErrUserDisabled = errors.New("user account is disabled", errors.CategoryAuth). WithTextCode(TextCodeAccountDisabled). WithCode(errors.CodeForbidden)
ErrUserDisabled is returned when an account is disabled.
var ErrUserPending = errors.New("user account is pending activation", errors.CategoryAuth). WithTextCode(TextCodeAccountPending). WithCode(errors.CodeForbidden)
ErrUserPending is returned when an account is pending activation.
var ErrUserSuspended = errors.New("user account is suspended", errors.CategoryAuth). WithTextCode(TextCodeAccountSuspended). WithCode(errors.CodeForbidden)
ErrUserSuspended is returned when an account is suspended.
var MaxLoginAttempts = 5
MaxLoginAttempts is the maximun number of attempts a user gets in a period
var ResetUserPasswordSQL = `` /* 148-byte string literal not displayed */
var TemplateUserKey = "current_user"
Functions ¶
func Can ¶ added in v0.7.0
Can is a convenience function to check permissions directly from the standard context Use CanFromRouter for router-based contexts.
func CanFromRouter ¶ added in v0.7.0
CanFromRouter is a convenience function to check permissions directly from the router context
func ComparePasswordAndHash ¶
ComparePasswordAndHash will validate the given cleartext password matches the hashed password
func ContextEnricherAdapter ¶ added in v0.23.0
ContextEnricherAdapter adapts jwtware.AuthClaims to auth.AuthClaims and stores claims + actor context in the standard context for downstream guard usage.
func DefaultPermissionsCacheKeyFromContext ¶ added in v0.32.0
DefaultPermissionsCacheKeyFromContext builds a stable resolver key from identity/tenant context plus permission-affecting discriminators (version, token, scopes, impersonation, session). It bypasses caching when no discriminator is available.
func GetMigrationsFS ¶
GetMigrationsFS returns the migration files for this package
func GetTemplateUser ¶ added in v0.10.0
GetTemplateUser is a convenience function to extract user data from router context for template usage. It returns the user object and a boolean indicating if it was found.
Usage:
if user, ok := auth.GetTemplateUser(ctx, auth.TemplateUserKey); ok {
// Use user in template data
data["user"] = user
}
func HasUserUUID ¶ added in v0.24.0
HasUserUUID reports whether Session.GetUserUUID will succeed.
func HashPassword ¶
HashPassword will generate a password hash
func IsMalformedError ¶
func IsOutsideThresholdPeriod ¶
IsOutsideThresholdPeriod is the negation of IsWithinThresholdPeriod
func IsTokenExpiredError ¶
func IsWithinThresholdPeriod ¶
IsWithinThresholdPeriod checks if the given time is within the threshold
func MergeTemplateData ¶ added in v0.16.0
func MergeTemplateData(ctx router.Context, data router.ViewContext) router.ViewContext
MergeTemplateData ensures every render includes the latest template helpers (current user, CSRF helpers, etc.) merged with the provided view context. It evaluates helper closures that return strings or template.HTML so request- scoped helpers are always materialized before hitting the renderer.
func MintScopedToken ¶ added in v0.29.0
func MintScopedToken(tokenService TokenService, identity Identity, resourceRoles map[string]string, opts ScopedTokenOptions) (string, time.Time, error)
MintScopedToken mints a short-lived JWT with optional scopes and TTL override. It uses TokenService defaults for issuer, audience, and TTL when available.
func MustValidateResolverConfigured ¶ added in v0.34.0
func MustValidateResolverConfigured(strict bool, resolver PermissionResolverFunc)
MustValidateResolverConfigured is a panic wrapper around ValidateResolverConfigured.
func NewPasswordResetsRepository ¶
func NewPasswordResetsRepository(db *bun.DB) repository.Repository[*PasswordReset]
func PermissionsVersionFromClaims ¶ added in v0.32.0
func PermissionsVersionFromClaims(claims AuthClaims) string
PermissionsVersionFromClaims extracts the permissions version from claims metadata.
func PermissionsVersionFromContext ¶ added in v0.32.0
PermissionsVersionFromContext extracts the permissions version from actor/claims metadata.
func RandomPasswordHash ¶
func RandomPasswordHash() string
RandomPasswordHash is a temporary password
func RegisterAuthRoutes ¶
func RegisterAuthRoutes[T any](app router.Router[T], opts ...AuthControllerOption)
func RegisterValidationListeners ¶ added in v0.23.0
func RegisterValidationListeners(cfg *jwtware.Config, listeners ...ValidationListener)
RegisterValidationListeners appends listeners to a jwtware.Config in a safe, reusable way.
func ResolveLogger ¶ added in v0.31.0
func ResolveLogger(name string, provider LoggerProvider, logger Logger) (LoggerProvider, Logger)
ResolveLogger resolves provider and logger with precedence provider > logger > nop.
func SetPermissionsVersionMetadata ¶ added in v0.32.0
SetPermissionsVersionMetadata stores a compact permission-version marker in claims metadata.
func TemplateHelpers ¶ added in v0.10.0
TemplateHelpers returns a map of helper functions and data that can be used with go-template's WithGlobalData option for authentication-related template functionality.
Usage:
renderer, err := template.NewRenderer(
template.WithBaseDir("./templates"),
template.WithGlobalData(auth.TemplateHelpers()),
)
In templates, you can then use:
{% if current_user %}
{% if current_user|has_role:"admin" %}
{% if current_user|can_create:"posts" %}
{{ csrf_field }}
{{ csrf_token }}
func TemplateHelpersWithRouter ¶ added in v0.10.0
TemplateHelpersWithRouter returns template helpers with user data extracted from router context. This is useful for automatically injecting the current user from JWT middleware context. It also includes CSRF token helpers when a CSRF token is available in the context.
Usage:
// In your route handler globalData := auth.TemplateHelpersWithRouter(ctx, auth.TemplateUserKey) // Merge with request-specific data and render template
Or with a reusable render helper:
func renderTemplate(ctx router.Context, name string, data map[string]any) (string, error) {
globalData := auth.TemplateHelpersWithRouter(ctx, auth.TemplateUserKey)
// Create renderer with current context or use a cached one
return renderer.RenderTemplate(name, data)
}
func TemplateHelpersWithUser ¶ added in v0.10.0
TemplateHelpersWithUser returns template helpers with a specific user set as current_user. This is useful when you want to inject the current user directly into the global context.
Usage:
currentUser := getCurrentUser(ctx)
renderer, err := template.NewRenderer(
template.WithBaseDir("./templates"),
template.WithGlobalData(auth.TemplateHelpersWithUser(currentUser)),
)
func TokenIDFromContext ¶ added in v0.29.0
TokenIDFromContext extracts the token ID (jti) from the standard context.
func ValidateResolverConfigured ¶ added in v0.34.0
func ValidateResolverConfigured(strict bool, resolver PermissionResolverFunc) error
ValidateResolverConfigured enforces resolver presence when strict mode is enabled.
func ValidateStringEquals ¶
func ValidateStringEquals(str string) validation.RuleFunc
ValidateStringEquals will check that both values match
func WithActorContext ¶ added in v0.15.0
func WithActorContext(ctx context.Context, actor *ActorContext) context.Context
WithActorContext stores the ActorContext in the provided context.
func WithClaimsContext ¶ added in v0.7.0
func WithClaimsContext(r context.Context, claims AuthClaims) context.Context
WithClaimsContext sets the AuthClaims in the given context
func WithContext ¶ added in v0.4.0
WithContext sets the User in the given context
func WithResolvedPermissionsCache ¶ added in v0.34.0
WithResolvedPermissionsCache seeds a request-scoped permission resolver cache in the provided context. The cache deduplicates repeated permission lookups within the same request context.
Types ¶
type AccountRegistrerer ¶
type AccountRegistrerer interface {
RegisterUser(ctx context.Context, email, username, password string) (*User, error)
}
AccountRegistrerer is the interface we need to handle new user registrations
type AccountVerificationHandler ¶
type AccountVerificationHandler struct {
// contains filtered or unexported fields
}
func (*AccountVerificationHandler) Execute ¶
func (h *AccountVerificationHandler) Execute(ctx context.Context, event AccountVerificationMesage) error
type AccountVerificationMesage ¶
type AccountVerificationMesage struct {
Session string `json:"session" example:"350399bc-c095-4bdc-a59c-3352d44848e4" doc:"Reset password session token"`
OnResponse func(a *AccountVerificationResponse)
}
type AccountVerificationResponse ¶
type AccountVerificationResponse struct {
Stage string `json:"stage" example:"Rone" doc:"Customer last name."`
Redirect string `json:"redirect" example:"Rone" doc:"Customer last name."`
Expired bool `json:"expired" example:"true" doc:"Has the request expired?"`
Found bool `json:"found" example:"true" doc:"Has the request been found?"`
Errors []string `json:"errors" example:"['invalid username']" doc:"Error messages."`
}
type ActivityEvent ¶ added in v0.14.0
type ActivityEvent struct {
EventType ActivityEventType
Actor ActorRef
UserID string
FromStatus UserStatus
ToStatus UserStatus
Metadata map[string]any
OccurredAt time.Time
}
ActivityEvent captures audit-friendly information about an action.
type ActivityEventType ¶ added in v0.14.0
type ActivityEventType string
ActivityEventType enumerates supported activity categories.
const ( ActivityEventUserStatusChanged ActivityEventType = "user.status.changed" ActivityEventLoginSuccess ActivityEventType = "auth.login.success" ActivityEventLoginFailure ActivityEventType = "auth.login.failure" ActivityEventSocialLogin ActivityEventType = "auth.social.login" ActivityEventImpersonationSuccess ActivityEventType = "auth.impersonation.success" ActivityEventImpersonationFailure ActivityEventType = "auth.impersonation.failure" ActivityEventPasswordResetSuccess ActivityEventType = "auth.password.reset" )
type ActivitySink ¶ added in v0.14.0
type ActivitySink interface {
Record(ctx context.Context, event ActivityEvent) error
}
ActivitySink consumes activity events for auditing/telemetry purposes.
type ActivitySinkFunc ¶ added in v0.14.0
type ActivitySinkFunc func(ctx context.Context, event ActivityEvent) error
ActivitySinkFunc adapts a function to the ActivitySink interface.
func (ActivitySinkFunc) Record ¶ added in v0.14.0
func (f ActivitySinkFunc) Record(ctx context.Context, event ActivityEvent) error
Record implements ActivitySink.
type ActorContext ¶ added in v0.15.0
type ActorContext struct {
ActorID string
Subject string
Role string
ResourceRoles map[string]string
TenantID string
OrganizationID string
Metadata map[string]any
ImpersonatorID string
IsImpersonated bool
}
ActorContext captures normalized actor metadata for downstream policy/guard layers.
func ActorContextFromClaims ¶ added in v0.15.0
func ActorContextFromClaims(claims AuthClaims) *ActorContext
ActorContextFromClaims normalizes actor metadata from AuthClaims into an ActorContext structure.
func ActorFromContext ¶ added in v0.15.0
func ActorFromContext(ctx context.Context) (*ActorContext, bool)
ActorFromContext extracts the ActorContext from the standard context.
func ActorFromRouterContext ¶ added in v0.15.0
func ActorFromRouterContext(ctx router.Context) (*ActorContext, bool)
ActorFromRouterContext extracts the ActorContext from a router context by reading the underlying standard context.
type AuthClaims ¶ added in v0.7.0
type AuthClaims interface {
Subject() string
UserID() string
Role() string
CanRead(resource string) bool
CanEdit(resource string) bool
CanCreate(resource string) bool
CanDelete(resource string) bool
HasRole(role string) bool
IsAtLeast(minRole string) bool
Expires() time.Time
IssuedAt() time.Time
}
AuthClaims represents structured JWT claims with enhanced permission checking
func GetClaims ¶ added in v0.7.0
func GetClaims(ctx context.Context) (AuthClaims, bool)
GetClaims extracts the AuthClaims from the standard context
func GetRouterClaims ¶ added in v0.7.0
func GetRouterClaims(ctx router.Context, key string) (AuthClaims, bool)
GetRouterClaims extracts the AuthClaims from the router context
func WSAuthClaimsFromContext ¶ added in v0.9.0
func WSAuthClaimsFromContext(ctx context.Context) (AuthClaims, bool)
WSAuthClaimsFromContext is a convenience function to retrieve auth claims from WebSocket context. It returns the underlying go-auth AuthClaims for easier access to go-auth specific functionality.
type AuthController ¶
type AuthController struct {
Debug bool
Logger Logger
LoggerProvider LoggerProvider
Repo RepositoryManager
Routes *AuthControllerRoutes
Views *AuthControllerViews
Auther HTTPAuthenticator
ErrorHandler router.ErrorHandler
RegisterRedirect string
UseHashID bool
// contains filtered or unexported fields
}
func NewAuthController ¶
func NewAuthController(opts ...AuthControllerOption) *AuthController
func (*AuthController) PasswordResetExecute ¶
func (a *AuthController) PasswordResetExecute(ctx router.Context) error
func (*AuthController) PasswordResetForm ¶
func (a *AuthController) PasswordResetForm(ctx router.Context) error
func (*AuthController) PasswordResetGet ¶
func (a *AuthController) PasswordResetGet(ctx router.Context) error
func (*AuthController) PasswordResetPost ¶
func (a *AuthController) PasswordResetPost(ctx router.Context) error
func (*AuthController) RegistrationCreate ¶
func (a *AuthController) RegistrationCreate(ctx router.Context) error
func (*AuthController) RegistrationShow ¶
func (a *AuthController) RegistrationShow(ctx router.Context) error
func (*AuthController) WithLogger ¶ added in v0.4.0
func (a *AuthController) WithLogger(l Logger) *AuthController
type AuthControllerOption ¶
type AuthControllerOption func(*AuthController) *AuthController
func WithAuthControllerActivitySink ¶ added in v0.14.0
func WithAuthControllerActivitySink(sink ActivitySink) AuthControllerOption
func WithAuthControllerRedirect ¶ added in v0.3.0
func WithAuthControllerRedirect(r string) AuthControllerOption
func WithAuthControllerRoutes ¶ added in v0.3.0
func WithAuthControllerRoutes(r *AuthControllerRoutes) AuthControllerOption
func WithAuthControllerUseHashID ¶ added in v0.3.0
func WithAuthControllerUseHashID(v bool) AuthControllerOption
func WithAuthControllerViews ¶ added in v0.3.0
func WithAuthControllerViews(v *AuthControllerViews) AuthControllerOption
func WithControllerLogger ¶ added in v0.1.1
func WithControllerLogger(logger Logger) AuthControllerOption
func WithControllerLoggerProvider ¶ added in v0.31.0
func WithControllerLoggerProvider(provider LoggerProvider) AuthControllerOption
func WithErrorHandler ¶ added in v0.3.0
func WithErrorHandler(errHandler router.ErrorHandler) AuthControllerOption
func WithFeatureGate ¶ added in v0.26.0
func WithFeatureGate(featureGate gate.FeatureGate) AuthControllerOption
type AuthControllerRoutes ¶
type AuthControllerViews ¶
type Authenticator ¶
type Authenticator interface {
Login(ctx context.Context, identifier, password string) (string, error)
Impersonate(ctx context.Context, identifier string) (string, error)
SessionFromToken(token string) (Session, error)
IdentityFromSession(ctx context.Context, session Session) (Identity, error)
TokenService() TokenService
}
Authenticator holds methods to deal with authentication
type Auther ¶
type Auther struct {
// contains filtered or unexported fields
}
func NewAuthenticator ¶
func NewAuthenticator(provider IdentityProvider, opts Config) *Auther
NewAuthenticator returns a new Authenticator
func (*Auther) IdentityFromSession ¶
func (*Auther) Impersonate ¶
func (*Auther) NewWSAuthMiddleware ¶ added in v0.9.0
func (a *Auther) NewWSAuthMiddleware(config ...router.WSAuthConfig) router.WebSocketMiddleware
NewWSAuthMiddleware creates a fully configured WebSocket authentication middleware using the go-auth TokenService. This is a convenience function for go-auth users.
func (*Auther) TokenService ¶ added in v0.11.0
func (s *Auther) TokenService() TokenService
TokenService returns the TokenService instance used by this Authenticator
func (*Auther) WithActivitySink ¶ added in v0.14.0
func (s *Auther) WithActivitySink(sink ActivitySink) *Auther
WithActivitySink configures an ActivitySink for emitting auth events.
func (*Auther) WithClaimsDecorator ¶ added in v0.14.0
func (s *Auther) WithClaimsDecorator(decorator ClaimsDecorator) *Auther
WithClaimsDecorator configures a ClaimsDecorator for enriching JWTs.
func (*Auther) WithLogger ¶ added in v0.1.1
func (*Auther) WithLoggerProvider ¶ added in v0.31.0
func (s *Auther) WithLoggerProvider(provider LoggerProvider) *Auther
WithLoggerProvider overrides the logger provider used by the authenticator.
func (*Auther) WithResourceRoleProvider ¶ added in v0.7.0
func (s *Auther) WithResourceRoleProvider(provider ResourceRoleProvider) *Auther
WithResourceRoleProvider sets a custom ResourceRoleProvider for the Auther. This enables resource-level permissions in JWT tokens.
func (*Auther) WithTokenSizeGuardrails ¶ added in v0.34.0
WithTokenSizeGuardrails configures signed JWT size warning/rejection thresholds.
func (*Auther) WithTokenValidator ¶ added in v0.24.0
func (s *Auther) WithTokenValidator(validator TokenValidator) *Auther
WithTokenValidator sets a custom token validator for externally issued tokens.
type CachedPermissionsResolver ¶ added in v0.32.0
type CachedPermissionsResolver struct {
// contains filtered or unexported fields
}
CachedPermissionsResolver wraps a permission resolver with key-based TTL caching and singleflight deduplication to prevent query amplification under load.
func NewCachedPermissionsResolver ¶ added in v0.32.0
func NewCachedPermissionsResolver(cfg CachedPermissionsResolverConfig) *CachedPermissionsResolver
NewCachedPermissionsResolver builds a CachedPermissionsResolver. When cfg.TTL <= 0, cross-request storage is disabled but singleflight deduplication still applies.
func (*CachedPermissionsResolver) Invalidate ¶ added in v0.32.0
func (r *CachedPermissionsResolver) Invalidate(ctx context.Context, key string) error
Invalidate removes a single cache key.
func (*CachedPermissionsResolver) PurgeExpired ¶ added in v0.32.0
func (r *CachedPermissionsResolver) PurgeExpired(ctx context.Context) (int, error)
PurgeExpired deletes stale cache entries when the configured store supports it.
func (*CachedPermissionsResolver) ResolvePermissions ¶ added in v0.32.0
func (r *CachedPermissionsResolver) ResolvePermissions(ctx context.Context) ([]string, error)
ResolvePermissions resolves permissions with cache + singleflight safeguards.
func (*CachedPermissionsResolver) ResolverFunc ¶ added in v0.32.0
func (r *CachedPermissionsResolver) ResolverFunc() PermissionResolverFunc
ResolverFunc returns the wrapped resolver function.
func (*CachedPermissionsResolver) Stats ¶ added in v0.32.0
func (r *CachedPermissionsResolver) Stats() PermissionResolverStats
Stats returns a copy of the internal counters.
func (*CachedPermissionsResolver) Store ¶ added in v0.33.0
func (r *CachedPermissionsResolver) Store() PermissionCacheStore
Store returns the configured cache store implementation.
type CachedPermissionsResolverConfig ¶ added in v0.32.0
type CachedPermissionsResolverConfig struct {
Resolver PermissionResolverFunc
KeyFunc PermissionCacheKeyFunc
Store PermissionCacheStore
TTL time.Duration
CacheErrorMode PermissionCacheErrorMode
Logger Logger
}
CachedPermissionsResolverConfig configures the cross-request resolver cache.
type ClaimsDecorator ¶ added in v0.14.0
type ClaimsDecorator interface {
Decorate(ctx context.Context, identity Identity, claims *JWTClaims) error
}
ClaimsDecorator can mutate allowed JWT claim extensions before a token is signed. Implementations may only touch extension fields (e.g. Resources, Metadata) and must leave registered/identity claims untouched so core auth semantics stay stable.
type ClaimsDecoratorFunc ¶ added in v0.14.0
ClaimsDecoratorFunc adapts a function into a ClaimsDecorator.
type Config ¶
type Config interface {
GetSigningKey() string
GetSigningMethod() string
GetContextKey() string
GetTokenExpiration() int
GetExtendedTokenDuration() int
GetTokenLookup() string
GetAuthScheme() string
GetIssuer() string
GetAudience() []string
GetRejectedRouteKey() string
GetRejectedRouteDefault() string
}
Config holds auth options
type FieldsLogger ¶ added in v0.31.0
type FieldsLogger = glog.FieldsLogger
type FinalizePasswordResetHandler ¶
type FinalizePasswordResetHandler struct {
// contains filtered or unexported fields
}
func NewFinalizePasswordResetHandler ¶ added in v0.14.0
func NewFinalizePasswordResetHandler(repo RepositoryManager) *FinalizePasswordResetHandler
NewFinalizePasswordResetHandler creates a handler with sane defaults.
func (*FinalizePasswordResetHandler) Execute ¶
func (h *FinalizePasswordResetHandler) Execute(ctx context.Context, event FinalizePasswordResetMesasge) error
func (*FinalizePasswordResetHandler) WithActivitySink ¶ added in v0.14.0
func (h *FinalizePasswordResetHandler) WithActivitySink(sink ActivitySink) *FinalizePasswordResetHandler
WithActivitySink sets the sink used to emit password reset events.
func (*FinalizePasswordResetHandler) WithFeatureGate ¶ added in v0.26.0
func (h *FinalizePasswordResetHandler) WithFeatureGate(featureGate gate.FeatureGate) *FinalizePasswordResetHandler
WithFeatureGate sets the feature gate used to authorize reset completion.
func (*FinalizePasswordResetHandler) WithLogger ¶ added in v0.14.0
func (h *FinalizePasswordResetHandler) WithLogger(logger Logger) *FinalizePasswordResetHandler
WithLogger overrides the logger used by the handler.
func (*FinalizePasswordResetHandler) WithLoggerProvider ¶ added in v0.31.0
func (h *FinalizePasswordResetHandler) WithLoggerProvider(provider LoggerProvider) *FinalizePasswordResetHandler
WithLoggerProvider overrides the logger provider used by the handler.
type FormattedLogger ¶ added in v0.31.0
type FormattedLogger = compat.FormattedLogger
func ToFormattedLogger ¶ added in v0.31.0
func ToFormattedLogger(logger Logger) FormattedLogger
ToFormattedLogger adapts a glog.Logger into a format-style logger.
type HTTPAuthenticator ¶
type HTTPAuthenticator interface {
Middleware
Login(c router.Context, payload LoginPayload) error
Logout(c router.Context)
SetRedirect(c router.Context)
GetRedirect(c router.Context, def ...string) string
GetRedirectOrDefault(c router.Context) string
MakeClientRouteAuthErrorHandler(optionalAuth bool) func(c router.Context, err error) error
}
type HookErrorHandler ¶ added in v0.15.0
type HookErrorHandler func(ctx context.Context, phase TransitionHookPhase, err error, tc TransitionContext) error
HookErrorHandler handles errors surfaced by transition hooks.
type Identity ¶
Identity holds the attributes of an identity
func NewIdentityFromUser ¶ added in v0.24.0
NewIdentityFromUser returns an Identity adapter for the provided user.
type IdentityProvider ¶
type IdentityProvider interface {
VerifyIdentity(ctx context.Context, identifier, password string) (Identity, error)
FindIdentityByIdentifier(ctx context.Context, identifier string) (Identity, error)
}
IdentityProvider ensure we have a store to retrieve auth identity
type InMemoryPermissionCacheStore ¶ added in v0.33.0
type InMemoryPermissionCacheStore struct {
// contains filtered or unexported fields
}
InMemoryPermissionCacheStore is the default PermissionCacheStore implementation.
func NewInMemoryPermissionCacheStore ¶ added in v0.33.0
func NewInMemoryPermissionCacheStore(cfg InMemoryPermissionCacheStoreConfig) *InMemoryPermissionCacheStore
NewInMemoryPermissionCacheStore builds an in-memory permission cache store.
func (*InMemoryPermissionCacheStore) Delete ¶ added in v0.33.0
func (s *InMemoryPermissionCacheStore) Delete(_ context.Context, key string) error
Delete removes a key from the store.
func (*InMemoryPermissionCacheStore) Get ¶ added in v0.33.0
Get returns cached permissions when the key exists and has not expired.
func (*InMemoryPermissionCacheStore) PurgeExpired ¶ added in v0.33.0
func (s *InMemoryPermissionCacheStore) PurgeExpired(_ context.Context) (int, error)
PurgeExpired removes all expired entries and returns the number of keys removed.
type InMemoryPermissionCacheStoreConfig ¶ added in v0.33.0
type InMemoryPermissionCacheStoreConfig struct {
// PurgeInterval throttles opportunistic cleanup on writes.
// Zero applies a sensible default.
PurgeInterval time.Duration
// Now can be provided in tests to control time.
Now func() time.Time
}
InMemoryPermissionCacheStoreConfig configures the default in-memory permission cache store.
type InitializePasswordResetHandler ¶
type InitializePasswordResetHandler struct {
// contains filtered or unexported fields
}
func NewInitializePasswordResetHandler ¶ added in v0.26.0
func NewInitializePasswordResetHandler(repo RepositoryManager) *InitializePasswordResetHandler
func (*InitializePasswordResetHandler) Execute ¶
func (h *InitializePasswordResetHandler) Execute(ctx context.Context, event InitializePasswordResetMessage) error
func (*InitializePasswordResetHandler) WithFeatureGate ¶ added in v0.26.0
func (h *InitializePasswordResetHandler) WithFeatureGate(featureGate gate.FeatureGate) *InitializePasswordResetHandler
type InitializePasswordResetMessage ¶
type InitializePasswordResetMessage struct {
Stage string `json:"stage" example:"Rone" doc:"Customer last name."`
Session string `json:"session" example:"350399bc-c095-4bdc-a59c-3352d44848e4" doc:"Reset password session token"`
Email string `json:"email" example:"[email protected]" doc:"Customer email."`
OnResponse func(resp *InitializePasswordResetResponse)
}
func (InitializePasswordResetMessage) Type ¶
func (p InitializePasswordResetMessage) Type() string
type InitializePasswordResetResponse ¶
type InitializePasswordResetResponse struct {
Reset *PasswordReset
Stage string
Success bool
}
type JWTClaims ¶ added in v0.7.0
type JWTClaims struct {
jwt.RegisteredClaims
UID string `json:"uid,omitempty"`
UserRole string `json:"role,omitempty"`
Resources map[string]string `json:"res,omitempty"` // resource -> role mapping
Metadata map[string]any `json:"metadata,omitempty"` // extension payload
Scopes []string `json:"scopes,omitempty"` // optional scopes (e.g., debug tokens)
}
JWTClaims is the concrete implementation of AuthClaims
func (*JWTClaims) CanCreate ¶ added in v0.7.0
CanCreate checks if the user can create a specific resource
func (*JWTClaims) CanDelete ¶ added in v0.7.0
CanDelete checks if the user can delete a specific resource
func (*JWTClaims) ClaimsMetadata ¶ added in v0.15.0
ClaimsMetadata exposes metadata extensions for optional context enrichment.
func (*JWTClaims) HasRole ¶ added in v0.7.0
HasRole checks if the user has a specific role (either global or for any resource)
func (*JWTClaims) IsAtLeast ¶ added in v0.7.0
IsAtLeast checks if the user's role is at least the minimum required role
func (*JWTClaims) ResourceRoles ¶ added in v0.15.0
ResourceRoles exposes resource-specific roles for optional context enrichment.
type LegacyLogger ¶ added in v0.31.0
type LegacyLogger interface {
Debug(format string, args ...any)
Info(format string, args ...any)
Warn(format string, args ...any)
Error(format string, args ...any)
}
LegacyLogger matches the historical go-auth logging contract.
type Logger ¶
func EnsureLogger ¶ added in v0.31.0
EnsureLogger guarantees a non-nil logger.
func FromFormattedLogger ¶ added in v0.31.0
func FromFormattedLogger(logger FormattedLogger) Logger
FromFormattedLogger adapts a format-style logger into a glog.Logger.
func FromLegacyLogger ¶ added in v0.31.0
func FromLegacyLogger(logger LegacyLogger) Logger
FromLegacyLogger adapts the historical go-auth logger into a glog.Logger.
type LoggerProvider ¶ added in v0.31.0
type LoggerProvider = glog.LoggerProvider
type LoginPayload ¶
type LoginRequest ¶
type LoginRequest struct {
Identifier string `form:"identifier" json:"identifier"`
Password string `form:"password" json:"password"`
RememberMe bool `form:"remember_me" json:"remember_me"`
}
LoginRequest payload
func (LoginRequest) GetExtendedSession ¶
func (r LoginRequest) GetExtendedSession() bool
GetExtendedSession will return the password
func (LoginRequest) GetIdentifier ¶
func (r LoginRequest) GetIdentifier() string
GetIdentifier returns the identifier
func (LoginRequest) GetPassword ¶
func (r LoginRequest) GetPassword() string
GetPassword will return the password
func (LoginRequest) Validate ¶
func (r LoginRequest) Validate() *errors.Error
Validate will run validation rules
type Middleware ¶
type MultiTokenValidator ¶ added in v0.24.0
type MultiTokenValidator struct {
// contains filtered or unexported fields
}
MultiTokenValidator tries validators in order until one succeeds. It treats ErrTokenMalformed as "try next" and returns the last malformed error if all validators fail.
func NewMultiTokenValidator ¶ added in v0.24.0
func NewMultiTokenValidator(validators ...TokenValidator) *MultiTokenValidator
NewMultiTokenValidator filters nil validators and returns a composite validator.
func (*MultiTokenValidator) Validate ¶ added in v0.24.0
func (m *MultiTokenValidator) Validate(tokenString string) (AuthClaims, error)
Validate satisfies the TokenValidator interface.
type PasswordAuthenticator ¶
type PasswordAuthenticator interface {
HashPassword(password string) (string, error)
ComparePasswordAndHash(password, hash string) error
}
PasswordAuthenticator authenticates passwords
type PasswordReset ¶
type PasswordReset struct {
bun.BaseModel `bun:"table:password_reset,alias:pwdr"`
ID uuid.UUID `bun:"id,pk,nullzero,type:uuid" json:"id,omitempty"`
UserID *uuid.UUID `bun:"user_id,notnull" json:"user_id,omitempty"`
User *User `bun:"rel:has-one,join:user_id=id" json:"user,omitempty"`
Status string `bun:"status,notnull" json:"status,omitempty"`
Email string `bun:"email,notnull" json:"email,omitempty"`
DeletedAt *time.Time `bun:"deleted_at,soft_delete,nullzero" json:"deleted_at,omitempty"`
ResetedAt *time.Time `bun:"reseted_at,nullzero" json:"reseted_at,omitempty"`
CreatedAt *time.Time `bun:"created_at,nullzero,default:current_timestamp" json:"created_at,omitempty"`
UpdatedAt *time.Time `bun:"updated_at,nullzero,default:current_timestamp" json:"updated_at,omitempty"`
}
PasswordReset is the user model
func MarkPasswordAsReseted ¶
func MarkPasswordAsReseted(id uuid.UUID) *PasswordReset
MarkPasswordAsReseted will create a new instance
type PasswordResetRequestPayload ¶
type PasswordResetRequestPayload struct {
Email string `form:"email" json:"email"`
Stage string `form:"stage" json:"stage"`
}
PasswordResetRequestPayload holds values for password reset
func (PasswordResetRequestPayload) Validate ¶
func (r PasswordResetRequestPayload) Validate() *errors.Error
Validate will validate the payload
type PasswordResetStep ¶
type PasswordResetStep = string
PasswordResetStep step on password reset
const ( // ResetUnknown is the unknown status ResetUnknown PasswordResetStep = "unknown" // ResetInit is the initial step ResetInit PasswordResetStep = "show-reset" //AccountVerification notifiction sent AccountVerification PasswordResetStep = "email-sent" // ChangingPassword user will change password ChangingPassword PasswordResetStep = "change-password" // ChangeFinalized processing change ChangeFinalized PasswordResetStep = "password-changed" )
type PasswordResetVerifyPayload ¶
type PasswordResetVerifyPayload struct {
Stage string `form:"stage" json:"stage"`
Password string `form:"password" json:"password"`
ConfirmPassword string `form:"confirm_password" json:"confirm_password"`
}
PasswordResetVerifyPayload holds values for password reset
func (PasswordResetVerifyPayload) Validate ¶
func (r PasswordResetVerifyPayload) Validate() *errors.Error
Validate will validate the payload
type PermissionCacheErrorMode ¶ added in v0.33.0
type PermissionCacheErrorMode string
PermissionCacheErrorMode defines resolver behavior when cache store operations fail.
const ( // PermissionCacheErrorModeFailOpen bypasses cache errors and continues resolving. PermissionCacheErrorModeFailOpen PermissionCacheErrorMode = "fail_open" // PermissionCacheErrorModeFailClosed returns cache operation errors immediately. PermissionCacheErrorModeFailClosed PermissionCacheErrorMode = "fail_closed" )
type PermissionCacheKeyFunc ¶ added in v0.32.0
PermissionCacheKeyFunc computes a stable cache key for a permission resolution request. Return ok=false to bypass cross-request caching.
type PermissionCacheStore ¶ added in v0.33.0
type PermissionCacheStore interface {
Get(ctx context.Context, key string) (permissions []string, ok bool, err error)
Set(ctx context.Context, key string, permissions []string, ttl time.Duration) error
Delete(ctx context.Context, key string) error
}
PermissionCacheStore is the storage contract used by CachedPermissionsResolver. The interface is intentionally narrow to align with generic cache backends.
type PermissionResolverFunc ¶ added in v0.32.0
PermissionResolverFunc resolves effective permission keys from a request context.
type PermissionResolverStats ¶ added in v0.32.0
type PermissionResolverStats struct {
Calls uint64
ResolverRuns uint64
CacheHits uint64
CacheMisses uint64
NoCacheCalls uint64
Errors uint64
StoreGetErrors uint64
StoreSetErrors uint64
StoreDeleteErrors uint64
PurgeRuns uint64
PurgedEntries uint64
}
PermissionResolverStats exposes lightweight runtime counters for observability.
type PurgeablePermissionCacheStore ¶ added in v0.33.0
type PurgeablePermissionCacheStore interface {
PurgeExpired(ctx context.Context) (purged int, err error)
}
PurgeablePermissionCacheStore optionally supports active cleanup of expired keys. Implementations backed by Redis can ignore this capability.
type RegisterUserHandler ¶
type RegisterUserHandler struct {
// contains filtered or unexported fields
}
Test handlers
func NewRegisterUserHandler ¶ added in v0.26.0
func NewRegisterUserHandler(repo RepositoryManager) *RegisterUserHandler
func (*RegisterUserHandler) Execute ¶
func (h *RegisterUserHandler) Execute(ctx context.Context, event RegisterUserMessage) error
func (*RegisterUserHandler) WithFeatureGate ¶ added in v0.26.0
func (h *RegisterUserHandler) WithFeatureGate(featureGate gate.FeatureGate) *RegisterUserHandler
type RegisterUserMessage ¶
type RegisterUserMessage struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Username string `json:"username"`
Email string `json:"email"`
Phone string `json:"phone"`
Role string `json:"role"`
Password string `json:"password"`
UseHashid bool
}
func (RegisterUserMessage) Type ¶
func (e RegisterUserMessage) Type() string
type RegistrationCreatePayload ¶
type RegistrationCreatePayload struct {
FirstName string `form:"first_name" json:"first_name"`
LastName string `form:"last_name" json:"last_name"`
Email string `form:"email" json:"email"`
Phone string `form:"phone_number" json:"phone_number"`
Password string `form:"password" json:"password"`
ConfirmPassword string `form:"confirm_password" json:"confirm_password"`
}
RegistrationCreatePayload is the form paylaod
func (RegistrationCreatePayload) Validate ¶
func (r RegistrationCreatePayload) Validate() *errors.Error
Validate will validate the payload
type RepositoryManager ¶
type RepositoryManager interface {
repository.Validator
repository.TransactionManager
Users() Users
PasswordResets() repository.Repository[*PasswordReset]
}
RepositoryManager exposes all repositories
func NewRepositoryManager ¶
func NewRepositoryManager(db *bun.DB) RepositoryManager
type ResourceRoleProvider ¶ added in v0.7.0
type ResourceRoleProvider interface {
FindResourceRoles(ctx context.Context, identity Identity) (map[string]string, error)
}
ResourceRoleProvider is an optional interface for fetching resource-specific roles. If provided to an Auther, it will be used to embed fine-grained permissions into the JWT, upgrading it to a structured claims format.
type RoleCapableSession ¶ added in v0.7.0
type RoleCapableSession interface {
Session // Embed the existing Session interface
// CanRead checks if the role can read a specific resource
CanRead(resource string) bool
// CanEdit checks if the role can edit a specific resource
CanEdit(resource string) bool
// CanCreate checks if the role can create a specific resource
CanCreate(resource string) bool
// CanDelete checks if the role can delete a specific resource
CanDelete(resource string) bool
// HasRole checks if the user has a specific role
HasRole(role string) bool
// IsAtLeast checks if the user's role is at least the minimum required role
IsAtLeast(minRole UserRole) bool
}
RoleCapableSession extends Session with role-based access control capabilities
type RoleValidator ¶ added in v0.7.0
type RoleValidator interface {
// CanRead checks if the role can read a specific resource
CanRead(resource string) bool
// CanEdit checks if the role can edit a specific resource
CanEdit(resource string) bool
// CanCreate checks if the role can create a specific resource
CanCreate(resource string) bool
// CanDelete checks if the role can delete a specific resource
CanDelete(resource string) bool
// HasRole checks if the user has a specific role
HasRole(role string) bool
// IsAtLeast checks if the user's role is at least the minimum required role
IsAtLeast(minRole UserRole) bool
}
RoleValidator defines the interface for role-based access control validation
type RouteAuthenticator ¶
type RouteAuthenticator struct {
AuthErrorHandler func(c router.Context, err error) error // TODO: make functions
ErrorHandler func(c router.Context, err error) error // TODO: make functions
// contains filtered or unexported fields
}
func NewHTTPAuthenticator ¶
func NewHTTPAuthenticator(auther Authenticator, cfg Config) (*RouteAuthenticator, error)
func (RouteAuthenticator) GetCookieDuration ¶
func (a RouteAuthenticator) GetCookieDuration() time.Duration
func (RouteAuthenticator) GetExtendedCookieDuration ¶
func (a RouteAuthenticator) GetExtendedCookieDuration() time.Duration
func (*RouteAuthenticator) GetRedirect ¶
func (a *RouteAuthenticator) GetRedirect(ctx router.Context, def ...string) string
func (*RouteAuthenticator) GetRedirectOrDefault ¶
func (a *RouteAuthenticator) GetRedirectOrDefault(ctx router.Context) string
func (*RouteAuthenticator) Impersonate ¶
func (a *RouteAuthenticator) Impersonate(c router.Context, identifier string) error
func (*RouteAuthenticator) Login ¶
func (a *RouteAuthenticator) Login(ctx router.Context, payload LoginPayload) error
func (*RouteAuthenticator) Logout ¶
func (a *RouteAuthenticator) Logout(ctx router.Context)
func (*RouteAuthenticator) MakeClientRouteAuthErrorHandler ¶
func (*RouteAuthenticator) ProtectedRoute ¶
func (a *RouteAuthenticator) ProtectedRoute(cfg Config, errorHandler func(router.Context, error) error) router.MiddlewareFunc
func (*RouteAuthenticator) SetRedirect ¶
func (a *RouteAuthenticator) SetRedirect(ctx router.Context)
func (*RouteAuthenticator) WithLogger ¶ added in v0.4.0
func (a *RouteAuthenticator) WithLogger(l Logger) *RouteAuthenticator
func (*RouteAuthenticator) WithLoggerProvider ¶ added in v0.31.0
func (a *RouteAuthenticator) WithLoggerProvider(provider LoggerProvider) *RouteAuthenticator
WithLoggerProvider overrides the logger provider used by the HTTP authenticator.
func (*RouteAuthenticator) WithValidationListeners ¶ added in v0.15.0
func (a *RouteAuthenticator) WithValidationListeners(listeners ...ValidationListener) *RouteAuthenticator
WithValidationListeners registers callbacks invoked immediately after token validation.
type ScopedTokenOptions ¶ added in v0.29.0
type ScopedTokenOptions struct {
// TTL overrides the default token expiration. Zero uses TokenService defaults.
TTL time.Duration
// Issuer overrides the default issuer if provided.
Issuer string
// Audience overrides the default audience if provided.
Audience []string
// IssuedAt overrides the issuance time. Zero uses time.Now().
IssuedAt time.Time
// Scopes sets the optional scopes claim on the minted token.
Scopes []string
}
ScopedTokenOptions controls how MintScopedToken issues short-lived tokens.
type Session ¶
type Session interface {
GetUserID() string
GetUserUUID() (uuid.UUID, error)
GetAudience() []string
GetIssuer() string
GetIssuedAt() *time.Time
GetData() map[string]any
}
Session holds attributes that are part of an auth session
type SessionObject ¶
type SessionObject struct {
UserID string `json:"user_id,omitempty"`
Audience []string `json:"audience,omitempty"`
Issuer string `json:"issuer,omitempty"`
IssuedAt *time.Time `json:"issued_at,omitempty"`
ExpirationDate *time.Time `json:"expiration_date,omitempty"`
Data map[string]any `json:"data,omitempty"`
}
func GetRouterSession ¶
func GetRouterSession(c router.Context, key string) (*SessionObject, error)
func (*SessionObject) CanCreate ¶ added in v0.7.0
func (s *SessionObject) CanCreate(resource string) bool
CanCreate checks if the role can create a specific resource
func (*SessionObject) CanDelete ¶ added in v0.7.0
func (s *SessionObject) CanDelete(resource string) bool
CanDelete checks if the role can delete a specific resource
func (*SessionObject) CanEdit ¶ added in v0.7.0
func (s *SessionObject) CanEdit(resource string) bool
CanEdit checks if the role can edit a specific resource
func (*SessionObject) CanRead ¶ added in v0.7.0
func (s *SessionObject) CanRead(resource string) bool
CanRead checks if the role can read a specific resource
func (*SessionObject) GetAudience ¶
func (s *SessionObject) GetAudience() []string
func (*SessionObject) GetData ¶
func (s *SessionObject) GetData() map[string]any
func (*SessionObject) GetIssuedAt ¶
func (s *SessionObject) GetIssuedAt() *time.Time
func (*SessionObject) GetIssuer ¶
func (s *SessionObject) GetIssuer() string
func (*SessionObject) GetUserID ¶
func (s *SessionObject) GetUserID() string
func (*SessionObject) GetUserUUID ¶
func (s *SessionObject) GetUserUUID() (uuid.UUID, error)
func (*SessionObject) HasRole ¶ added in v0.7.0
func (s *SessionObject) HasRole(role string) bool
HasRole checks if the user has a specific role
func (*SessionObject) IsAtLeast ¶ added in v0.7.0
func (s *SessionObject) IsAtLeast(minRole UserRole) bool
IsAtLeast checks if the user's role is at least the minimum required role
func (SessionObject) String ¶
func (s SessionObject) String() string
TODO: enable only in development!
type StateMachineOption ¶ added in v0.14.0
type StateMachineOption func(*userStateMachine)
StateMachineOption customizes state machine construction.
func WithStateMachineActivitySink ¶ added in v0.14.0
func WithStateMachineActivitySink(sink ActivitySink) StateMachineOption
WithStateMachineActivitySink sets the ActivitySink used to publish lifecycle events.
func WithStateMachineClock ¶ added in v0.14.0
func WithStateMachineClock(clock func() time.Time) StateMachineOption
WithStateMachineClock injects a custom clock (useful for tests).
func WithStateMachineHookErrorHandler ¶ added in v0.15.0
func WithStateMachineHookErrorHandler(handler HookErrorHandler) StateMachineOption
WithStateMachineHookErrorHandler overrides how hook failures are propagated. Provide a handler to convert hook errors into domain-specific responses, otherwise the default handler panics with guidance for developers.
func WithStateMachineLogger ¶ added in v0.14.0
func WithStateMachineLogger(logger Logger) StateMachineOption
WithStateMachineLogger overrides the logger used for sink failures.
func WithStateMachineLoggerProvider ¶ added in v0.31.0
func WithStateMachineLoggerProvider(provider LoggerProvider) StateMachineOption
WithStateMachineLoggerProvider overrides the logger provider used by the state machine.
type StatusUpdateOption ¶ added in v0.14.0
type StatusUpdateOption func(*User)
StatusUpdateOption allows callers to mutate the user record before persisting status changes.
func WithSuspendedAt ¶ added in v0.14.0
func WithSuspendedAt(at *time.Time) StatusUpdateOption
WithSuspendedAt sets the SuspendedAt timestamp during a status transition.
type TokenIDer ¶ added in v0.29.0
type TokenIDer interface {
TokenID() string
}
TokenIDer is an optional interface for claims that expose a token ID (jti).
type TokenService ¶ added in v0.7.0
type TokenService interface {
// Generate creates a new JWT token for the given identity with resource-specific roles
Generate(identity Identity, resourceRoles map[string]string) (string, error)
// SignClaims signs the provided claims without mutating registered fields, enabling
// callers to apply decorators before the token is finalized.
SignClaims(claims *JWTClaims) (string, error)
// Validate parses and validates a token string, returning structured claims
Validate(tokenString string) (AuthClaims, error)
}
TokenService provides transport-agnostic JWT operations
func NewTokenService ¶ added in v0.7.0
func NewTokenService(signingKey []byte, tokenExpiration int, issuer string, audience jwt.ClaimStrings, logger Logger, opts ...TokenServiceOption) TokenService
NewTokenService creates a new TokenService instance.
type TokenServiceAdapter ¶ added in v0.7.0
type TokenServiceAdapter struct {
// contains filtered or unexported fields
}
TokenServiceAdapter adapts TokenValidator to jwtware.TokenValidator interface
func NewTokenServiceAdapter ¶ added in v0.11.0
func NewTokenServiceAdapter(tokenValidator TokenValidator) *TokenServiceAdapter
NewTokenServiceAdapter creates a new TokenServiceAdapter
func (*TokenServiceAdapter) Validate ¶ added in v0.7.0
func (tsa *TokenServiceAdapter) Validate(tokenString string) (jwtware.AuthClaims, error)
Validate implements the jwtware.TokenValidator interface
type TokenServiceImpl ¶ added in v0.7.0
type TokenServiceImpl struct {
// contains filtered or unexported fields
}
TokenServiceImpl implements the TokenService interface
func (*TokenServiceImpl) Generate ¶ added in v0.7.0
func (ts *TokenServiceImpl) Generate(identity Identity, resourceRoles map[string]string) (string, error)
Generate creates a JWT token with resource specific roles
func (*TokenServiceImpl) SignClaims ¶ added in v0.14.0
func (ts *TokenServiceImpl) SignClaims(claims *JWTClaims) (string, error)
SignClaims signs arbitrary JWT claims using the configured signing key.
func (*TokenServiceImpl) SignClaimsWithType ¶ added in v0.34.0
func (ts *TokenServiceImpl) SignClaimsWithType(claims *JWTClaims, tokenType string) (string, error)
SignClaimsWithType signs claims and annotates guardrail logs/errors with the provided token type.
func (*TokenServiceImpl) Stats ¶ added in v0.34.0
func (ts *TokenServiceImpl) Stats() TokenServiceStats
Stats returns runtime counters for token signing guardrails.
func (*TokenServiceImpl) Validate ¶ added in v0.7.0
func (ts *TokenServiceImpl) Validate(tokenString string) (AuthClaims, error)
Validate parses and validates a token string, returning structured claims
type TokenServiceOption ¶ added in v0.34.0
type TokenServiceOption func(*TokenServiceImpl)
TokenServiceOption customizes TokenService behavior without changing the TokenService interface.
func WithClaimsMetadataStripKeys ¶ added in v0.34.0
func WithClaimsMetadataStripKeys(keys ...string) TokenServiceOption
WithClaimsMetadataStripKeys overrides the metadata keys that are removed by default minimization. Matching is case-insensitive and normalizes "-" to "_".
func WithTokenSizeGuardrails ¶ added in v0.34.0
func WithTokenSizeGuardrails(warnThresholdBytes, hardLimitBytes int) TokenServiceOption
WithTokenSizeGuardrails overrides warning and hard-limit thresholds for signed JWT size. Values <= 0 disable the respective threshold.
type TokenServiceStats ¶ added in v0.34.0
TokenServiceStats exposes runtime counters for token signing operations.
type TokenValidator ¶ added in v0.24.0
type TokenValidator interface {
Validate(tokenString string) (AuthClaims, error)
}
TokenValidator validates tokens and extracts claims without tying callers to a specific signing implementation.
type TokenValidatorFunc ¶ added in v0.24.0
type TokenValidatorFunc func(tokenString string) (AuthClaims, error)
TokenValidatorFunc adapts a function into a TokenValidator.
func (TokenValidatorFunc) Validate ¶ added in v0.24.0
func (f TokenValidatorFunc) Validate(tokenString string) (AuthClaims, error)
Validate satisfies the TokenValidator interface.
type TransitionContext ¶ added in v0.14.0
type TransitionContext struct {
Actor ActorRef
User *User
From UserStatus
To UserStatus
Meta TransitionMetadata
}
TransitionContext is passed into hooks for additional processing.
type TransitionHook ¶ added in v0.14.0
type TransitionHook func(ctx context.Context, tc TransitionContext) error
TransitionHook is executed before or after a transition.
type TransitionHookPhase ¶ added in v0.15.0
type TransitionHookPhase string
TransitionHookPhase identifies whether a hook ran before or after persistence.
const ( HookPhaseBefore TransitionHookPhase = "before_transition" HookPhaseAfter TransitionHookPhase = "after_transition" )
type TransitionMetadata ¶ added in v0.14.0
TransitionMetadata captures extra context for a transition.
type TransitionOption ¶ added in v0.14.0
type TransitionOption func(*transitionOptions)
TransitionOption customizes state machine behavior.
func WithAfterTransitionHook ¶ added in v0.14.0
func WithAfterTransitionHook(h TransitionHook) TransitionOption
WithAfterTransitionHook adds a hook executed after the status update succeeds.
func WithBeforeTransitionHook ¶ added in v0.14.0
func WithBeforeTransitionHook(h TransitionHook) TransitionOption
WithBeforeTransitionHook adds a hook executed before the status update.
func WithForceTransition ¶ added in v0.14.0
func WithForceTransition() TransitionOption
WithForceTransition bypasses validation rules (use sparingly).
func WithSuspensionTime ¶ added in v0.14.0
func WithSuspensionTime(t time.Time) TransitionOption
WithSuspensionTime overrides the timestamp recorded when entering the suspended state.
func WithTransitionMetadata ¶ added in v0.14.0
func WithTransitionMetadata(metadata map[string]any) TransitionOption
WithTransitionMetadata merges metadata into the transition context.
func WithTransitionReason ¶ added in v0.14.0
func WithTransitionReason(reason string) TransitionOption
WithTransitionReason sets the human-readable reason for the transition.
type User ¶
type User struct {
bun.BaseModel `bun:"table:users,alias:usr"`
ID uuid.UUID `bun:"id,pk,nullzero,type:uuid" json:"id,omitempty"`
Role UserRole `bun:"user_role,notnull" json:"user_role,omitempty"`
Status UserStatus `bun:"status,notnull,default:'active'" json:"status,omitempty"`
FirstName string `bun:"first_name,notnull" json:"first_name,omitempty"`
LastName string `bun:"last_name,notnull" json:"last_name,omitempty"`
Username string `bun:"username,notnull,unique" json:"username,omitempty"`
ProfilePicture string `bun:"profile_picture" json:"profile_picture,omitempty"`
Email string `bun:"email,notnull,unique" json:"email,omitempty"`
ExternalID string `bun:"external_id" json:"external_id,omitempty"`
ExternalIDProvider string `bun:"external_id_provider" json:"external_id_provider,omitempty"`
Phone string `bun:"phone_number" json:"phone_number,omitempty"`
PasswordHash string `bun:"password_hash" json:"password_hash,omitempty"`
EmailValidated bool `bun:"is_email_verified" json:"is_email_verified,omitempty"`
LoginAttempts int `bun:"login_attempts" json:"login_attempts,omitempty"`
LoginAttemptAt *time.Time `bun:"login_attempt_at" json:"login_attempt_at,omitempty"`
LoggedInAt *time.Time `bun:"loggedin_at" json:"loggedin_at,omitempty"`
SuspendedAt *time.Time `bun:"suspended_at,nullzero" json:"suspended_at,omitempty"`
Metadata map[string]any `bun:"metadata" json:"metadata,omitempty"`
ResetedAt *time.Time `bun:"reseted_at,nullzero" json:"reseted_at,omitempty"`
CreatedAt *time.Time `bun:"created_at,nullzero,default:current_timestamp" json:"created_at,omitempty"`
UpdatedAt *time.Time `bun:"updated_at,nullzero,default:current_timestamp" json:"updated_at,omitempty"`
DeletedAt *time.Time `bun:"deleted_at,soft_delete,nullzero" json:"deleted_at,omitempty"`
}
User is the user model
func FromContext ¶ added in v0.4.0
FromContext finds the user from the context.
func (*User) AddMetadata ¶
AddMetadata will append information to a metadata attribute TODO: make a trigger to merge metadata in database! https://stackoverflow.com/a/42954907/125083
func (*User) EnsureStatus ¶ added in v0.14.0
EnsureStatus sets a default status when empty to keep DB constraints satisfied.
func (*User) HasStatus ¶ added in v0.14.0
func (u *User) HasStatus(status UserStatus) bool
HasStatus reports whether the user is currently in the provided status.
func (*User) IsArchived ¶ added in v0.14.0
IsArchived returns true when the user is archived.
func (*User) IsDisabled ¶ added in v0.14.0
IsDisabled returns true when the user is disabled.
func (*User) IsPending ¶ added in v0.14.0
IsPending returns true when the user is pending activation.
func (*User) IsSuspended ¶ added in v0.14.0
IsSuspended returns true when the user is suspended.
type UserIdentity ¶ added in v0.24.0
type UserIdentity struct {
// contains filtered or unexported fields
}
UserIdentity adapts a User into the Identity interface for token generation.
func (UserIdentity) Email ¶ added in v0.24.0
func (u UserIdentity) Email() string
Email returns the user's email address.
func (UserIdentity) ID ¶ added in v0.24.0
func (u UserIdentity) ID() string
ID returns the user's ID as a string.
func (UserIdentity) Role ¶ added in v0.24.0
func (u UserIdentity) Role() string
Role returns the user's role as a string.
func (UserIdentity) Status ¶ added in v0.24.0
func (u UserIdentity) Status() UserStatus
Status returns the user's lifecycle status.
func (UserIdentity) Username ¶ added in v0.24.0
func (u UserIdentity) Username() string
Username returns the user's username.
type UserProvider ¶
UserProvider handles users
func NewUserProvider ¶
func NewUserProvider(store UserTracker) *UserProvider
NewUserProvider will create a new UserProvider
func (UserProvider) FindIdentityByIdentifier ¶
func (UserProvider) VerifyIdentity ¶
func (u UserProvider) VerifyIdentity(ctx context.Context, identifier, password string) (Identity, error)
VerifyIdentity will find the user, compare to the password, and return identity
func (*UserProvider) WithLogger ¶ added in v0.4.0
func (u *UserProvider) WithLogger(l Logger) *UserProvider
func (*UserProvider) WithLoggerProvider ¶ added in v0.31.0
func (u *UserProvider) WithLoggerProvider(provider LoggerProvider) *UserProvider
WithLoggerProvider overrides the logger provider used by the user provider.
type UserRole ¶
type UserRole string
UserRole is the user's role
const ( // RoleGuest is an guest role (ie. view) RoleGuest UserRole = "guest" // RoleMember us a member (i.e. view, edit) RoleMember UserRole = "member" // RoleAdmin is an admin role (i.e. view, edit, create) RoleAdmin UserRole = "admin" // RoleOwner is an admin role (i.e. view, edit, create, delete) RoleOwner UserRole = "owner" )
func GetAllRoles ¶ added in v0.7.0
func GetAllRoles() []UserRole
GetAllRoles returns all predefined roles in hierarchical order
type UserStateMachine ¶ added in v0.14.0
type UserStateMachine interface {
Transition(ctx context.Context, actor ActorRef, user *User, target UserStatus, opts ...TransitionOption) (*User, error)
CurrentStatus(user *User) UserStatus
}
UserStateMachine defines lifecycle operations for users.
func NewUserStateMachine ¶ added in v0.14.0
func NewUserStateMachine(users Users, opts ...StateMachineOption) UserStateMachine
NewUserStateMachine returns the default implementation backed by the provided repository.
type UserStatus ¶ added in v0.14.0
type UserStatus string
UserStatus represents lifecycle states for a user account
const ( // UserStatusPending indicates the account exists but is not yet active UserStatusPending UserStatus = "pending" // UserStatusActive represents a fully active account UserStatusActive UserStatus = "active" // UserStatusSuspended indicates temporary suspension UserStatusSuspended UserStatus = "suspended" // UserStatusDisabled indicates manual disablement with no path back to active except admin intervention UserStatusDisabled UserStatus = "disabled" // UserStatusArchived signals the record should be treated as deleted/read-only UserStatusArchived UserStatus = "archived" )
type UserTracker ¶
type UserTracker interface {
GetByIdentifier(ctx context.Context, identifier string) (*User, error)
TrackAttemptedLogin(ctx context.Context, user *User) error
TrackSucccessfulLogin(ctx context.Context, user *User) error
}
UserTracker is a store we can use to retrieve users
type Users ¶
type Users interface {
repository.Repository[*User]
TrackAttemptedLogin(ctx context.Context, user *User) error
TrackAttemptedLoginTx(ctx context.Context, tx bun.IDB, user *User) error
TrackSucccessfulLogin(ctx context.Context, user *User) error
TrackSucccessfulLoginTx(ctx context.Context, tx bun.IDB, user *User) error
Register(ctx context.Context, user *User) (*User, error)
RegisterTx(ctx context.Context, tx bun.IDB, user *User) (*User, error)
GetOrRegisterTx(ctx context.Context, tx bun.IDB, record *User) (*User, error)
GetOrCreate(ctx context.Context, record *User) (*User, error)
GetOrCreateTx(ctx context.Context, tx bun.IDB, record *User) (*User, error)
Create(ctx context.Context, record *User, criteria ...repository.InsertCriteria) (*User, error)
CreateTx(ctx context.Context, tx bun.IDB, record *User, criteria ...repository.InsertCriteria) (*User, error)
Upsert(ctx context.Context, record *User, criteria ...repository.UpdateCriteria) (*User, error)
UpsertTx(ctx context.Context, tx bun.IDB, record *User, criteria ...repository.UpdateCriteria) (*User, error)
UpdateStatus(ctx context.Context, id uuid.UUID, status UserStatus, opts ...StatusUpdateOption) (*User, error)
UpdateStatusTx(ctx context.Context, tx bun.IDB, id uuid.UUID, status UserStatus, opts ...StatusUpdateOption) (*User, error)
Suspend(ctx context.Context, actor ActorRef, user *User, opts ...TransitionOption) (*User, error)
Reinstate(ctx context.Context, actor ActorRef, user *User, opts ...TransitionOption) (*User, error)
ResetPassword(ctx context.Context, id uuid.UUID, passwordHash string) error
ResetPasswordTx(ctx context.Context, tx bun.IDB, id uuid.UUID, passwordHash string) error
}
func NewUsersRepository ¶
func NewUsersRepository(db *bun.DB, opts ...UsersOption) Users
type UsersOption ¶ added in v0.14.0
type UsersOption func(*users)
func WithUsersStateMachine ¶ added in v0.14.0
func WithUsersStateMachine(sm UserStateMachine) UsersOption
func WithUsersStateMachineOptions ¶ added in v0.14.0
func WithUsersStateMachineOptions(options ...StateMachineOption) UsersOption
type ValidationListener ¶ added in v0.23.0
type ValidationListener = jwtware.ValidationListener
ValidationListener aliases the jwtware listener so consumers can use auth helpers directly.
type WSAuthClaimsAdapter ¶ added in v0.9.0
type WSAuthClaimsAdapter struct {
// contains filtered or unexported fields
}
WSAuthClaimsAdapter adapts go-auth AuthClaims to go-router's WSAuthClaims interface
func (*WSAuthClaimsAdapter) CanCreate ¶ added in v0.9.0
func (w *WSAuthClaimsAdapter) CanCreate(resource string) bool
CanCreate checks if the user can create a specific resource
func (*WSAuthClaimsAdapter) CanDelete ¶ added in v0.9.0
func (w *WSAuthClaimsAdapter) CanDelete(resource string) bool
CanDelete checks if the user can delete a specific resource
func (*WSAuthClaimsAdapter) CanEdit ¶ added in v0.9.0
func (w *WSAuthClaimsAdapter) CanEdit(resource string) bool
CanEdit checks if the user can edit a specific resource
func (*WSAuthClaimsAdapter) CanRead ¶ added in v0.9.0
func (w *WSAuthClaimsAdapter) CanRead(resource string) bool
CanRead checks if the user can read a specific resource
func (*WSAuthClaimsAdapter) HasRole ¶ added in v0.9.0
func (w *WSAuthClaimsAdapter) HasRole(role string) bool
HasRole checks if the user has a specific role
func (*WSAuthClaimsAdapter) IsAtLeast ¶ added in v0.9.0
func (w *WSAuthClaimsAdapter) IsAtLeast(minRole string) bool
IsAtLeast checks if the user's role is at least the minimum required role
func (*WSAuthClaimsAdapter) Role ¶ added in v0.9.0
func (w *WSAuthClaimsAdapter) Role() string
Role returns the user's role
func (*WSAuthClaimsAdapter) Subject ¶ added in v0.9.0
func (w *WSAuthClaimsAdapter) Subject() string
Subject returns the subject claim
func (*WSAuthClaimsAdapter) UserID ¶ added in v0.9.0
func (w *WSAuthClaimsAdapter) UserID() string
UserID returns the user ID
type WSTokenValidator ¶ added in v0.9.0
type WSTokenValidator struct {
// contains filtered or unexported fields
}
WSTokenValidator implements go-router's WSTokenValidator interface using the go-auth TokenValidator for seamless WebSocket authentication
func NewWSTokenValidator ¶ added in v0.9.0
func NewWSTokenValidator(tokenValidator TokenValidator) *WSTokenValidator
NewWSTokenValidator creates a new WebSocket token validator using the provided TokenValidator
func (*WSTokenValidator) Validate ¶ added in v0.9.0
func (w *WSTokenValidator) Validate(tokenString string) (router.WSAuthClaims, error)
Validate validates a token string and returns WebSocket-compatible auth claims
Source Files
¶
- activity.go
- authenticator.go
- bcrypt.go
- bcrypt_cost_default.go
- claims.go
- claims_decorator.go
- claims_guard.go
- command_account_verification_request.go
- command_password_reset_finalize.go
- command_password_reset_initialize.go
- command_register_user.go
- ctx.go
- doc.go
- errors.go
- feature_gate_helpers.go
- files.go
- http.go
- http_controller.go
- identity_adapter.go
- middleware_helpers.go
- models.go
- permissions_cache_store.go
- permissions_cache_store_memory.go
- permissions_resolver.go
- permissions_resolver_request_cache.go
- permissions_resolver_strict.go
- repo_manager.go
- repo_users.go
- roles.go
- session.go
- state_machine.go
- template_helpers.go
- time.go
- token_mint.go
- token_service.go
- token_service_options.go
- token_validator.go
- types.go
- user_provider.go
- uuid_helpers.go
- websocket_adapter.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package activitymap provides helpers to normalize auth activity events into transport-agnostic records for external activity systems.
|
Package activitymap provides helpers to normalize auth activity events into transport-agnostic records for external activity systems. |
|
adapters
|
|
|
featuregate
module
|
|
|
middleware
|
|
|
provider
|
|
|
auth0
Package auth0 provides Auth0 JWT validation and claims mapping for go-auth.
|
Package auth0 provides Auth0 JWT validation and claims mapping for go-auth. |
|
auth0/sync
Package sync provides optional Auth0 user synchronization helpers.
|
Package sync provides optional Auth0 user synchronization helpers. |
|
Package social provides OAuth2 social login primitives for go-auth.
|
Package social provides OAuth2 social login primitives for go-auth. |