auth

package
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 43 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package auth is Gombit's runtime Bearer JWT surface (C3 / M5-2).

Behavior lives here, not in generated apps. framework.New mounts the Huma routes when config.Auth.JWTSecret is set and a database is attached.

Access tokens are short-lived JWTs. Refresh tokens are opaque, stored hashed, and rotated on each successful refresh. The generated SPA keeps both in memory — never localStorage or sessionStorage. Cookie/session + CSRF (--auth cookie) is a first-class alternative (M5-3).

Users can receive stable permission keys directly or through groups. IsSuperuser bypasses every permission check.

Index

Constants

View Source
const (
	// AccessCookieName holds the short-lived access JWT in cookie mode.
	AccessCookieName = "gombit_access"
	// RefreshCookieName holds the rotating refresh token in cookie mode.
	RefreshCookieName = "gombit_refresh"
	// CSRFCookieName holds the signed double-submit CSRF token.
	CSRFCookieName = "gombit_csrf"
	// CSRFHeaderName is the header clients must echo the CSRF cookie value
	// into for state-changing (POST/PUT/PATCH/DELETE) requests.
	CSRFHeaderName = "X-CSRF-Token"
)

Cookie and CSRF header names for cookie-mode session auth (M5-3). See docs/auth-cookie.md for the threat model these pair with.

View Source
const (

	// ExternalStateCookieName holds the flow's encrypted state, between the
	// start of an external sign-in and its callback.
	ExternalStateCookieName = "gombit_external"
	// ExternalCodeCookieName holds a Bearer-mode code's browser binding,
	// between the callback and the exchange.
	ExternalCodeCookieName = "gombit_external_code"
)
View Source
const PermissionManageUsers = "auth.users.manage"

PermissionManageUsers is the permission POST {prefix}/auth/users/{id}/disable and /enable require (a superuser has every permission). Create it with EnsurePermission and grant it to the users or groups that may.

Variables

View Source
var (
	ErrPasswordTooShort = errPasswordTooShort
	ErrPasswordTooLong  = errPasswordTooLong
	ErrPasswordRequired = errPasswordRequired
)

The password policy's reasons (PasswordPolicyError.Err).

View Source
var ErrAccountDisabled = errAccountDisabled

ErrAccountDisabled is the error of an operation of a disabled account (User.Disabled): a login with the right password, a session start, a message, a password change.

View Source
var ErrAlreadyVerified = errAlreadyVerified

ErrAlreadyVerified is returned by SendEmailVerification for a user whose email is verified.

View Source
var ErrEmailChangedMeanwhile = errEmailChangedMeanwhile

ErrEmailChangedMeanwhile is RequestEmailChange's error when another change of the account's email committed while the request ran: the request was for the old one.

View Source
var ErrEmailTaken = errEmailTaken

ErrEmailTaken is the exported form of errEmailTaken. Register and CreateSuperuser return it (wrapped) so callers such as gombit createsuperuser can detect duplicates with errors.Is without a second uniqueness check.

View Source
var ErrEmailUnchanged = errEmailUnchanged

ErrEmailUnchanged is RequestEmailChange's error for a new email that is the account's already.

View Source
var ErrIdentityLinkNotFound = errIdentityLinkNotFound

ErrIdentityLinkNotFound is UnlinkIdentity's link that is not the user's.

View Source
var ErrInvalidAccessToken = errInvalidAccessToken

ErrInvalidAccessToken is the error ParseAccess returns for an access token that is malformed, expired, or whose session has ended: a 401. Any other error is a server failure loading the user or the session (#460).

View Source
var ErrInvalidCredentials = errInvalidCredentials

ErrInvalidCredentials is the client-side failure of a login: a 401. Authenticate returns it for an unknown email or a wrong password; Login and IssueTokens also for a password changed, or an account deleted, between the password check and the session; Register and CreateSuperuser for an empty email. Authenticate, Login and IssueTokens also return ErrAccountDisabled for a disabled account (a 403), and Authenticate and Login (not IssueTokens, which checks no password) a *ThrottleError (errors.Is ErrTooManyAttempts, a 429) past a login throttle; any other error they return is a server failure (the database's, for one), not a credential problem, and answers a 500 (#460). Register and CreateSuperuser also return ErrEmailTaken (a 409) and CheckNewAccount's refusals, ErrInvalidEmail and a PasswordPolicyError on "password" (a 422), and Register a *ThrottleError (a 429) past its throttle.

View Source
var ErrInvalidEmail = errInvalidEmail

ErrInvalidEmail is the error for an email that is not a bare address of at most 255 characters: RequestEmailChange's for a new email, CheckNewAccount's for an account's, and Register's and CreateSuperuser's for one that is not blank (a blank email is ErrInvalidCredentials there; #461).

View Source
var ErrInvalidMFACode = errInvalidMFACode

ErrInvalidMFACode is a code that is not the authenticator's current one (or was used already), nor an unused recovery code.

View Source
var ErrInvalidToken = errInvalidOneTimeToken

ErrInvalidToken is returned by VerifyEmail and ResetPassword for a token that is unknown, expired, already used, superseded by a newer one, never delivered, or issued for an address the user no longer has. The cases are not told apart.

View Source
var ErrLastSignInMethod = errLastSignInMethod

ErrLastSignInMethod is UnlinkIdentity's refusal to remove the only way an account without a password signs in.

View Source
var ErrMFAAlreadyEnabled = errMFAAlreadyEnabled

ErrMFAAlreadyEnabled is an enrollment of an account with MFA enabled.

View Source
var ErrMFANotEnabled = errMFANotEnabled

ErrMFANotEnabled is an operation on the MFA of an account without it.

View Source
var ErrMFARequired = errMFARequired

ErrMFARequired is a login of an account with MFA enabled that gave no code: the password was right (it is told only then), a code is needed.

View Source
var ErrNoMailer = errors.New("auth: no mailer is configured, so the message cannot be sent")

ErrNoMailer is returned when a message must be sent and no Mailer is configured (WithMailer).

View Source
var ErrNoPendingEnrollment = errNoPendingEnrollment

ErrNoPendingEnrollment is a confirmation with no enrollment begun.

View Source
var ErrPasswordChanged = errPasswordChanged

ErrPasswordChanged is ChangePassword's error when the user's password changed between its check and its write (a reset or another change committed first; the route's 409): retry with the password the user has now.

View Source
var ErrSessionEnded = errSessionEnded

ErrSessionEnded is returned when the session a request runs in ended while the operation waited for the user's lock (a revocation, its expiry): ChangePassword, and the session revocations, then change nothing.

View Source
var ErrSessionNotFound = errSessionNotFound

ErrSessionNotFound is returned by RevokeSession when the id names no active session of the user, including a session that a logout ended while the revocation ran, and by RevokeSession and RevokeAllSessions when the user does not exist (a user that is not there has no sessions).

View Source
var ErrTooManyAttempts = errors.New("auth: too many attempts; try again later")

ErrTooManyAttempts is the error of an attempt a throttle refused; the error is a *ThrottleError, which says how long to wait.

View Source
var ErrUserNotFound = errUserNotFound

ErrUserNotFound is returned for a user id that names no user.

View Source
var ErrWrongCurrentPassword = errWrongCurrentPassword

ErrWrongCurrentPassword is ChangePassword's error for a current password that is not the user's (the route's 422 on current_password).

Functions

func AddUserToGroup

func AddUserToGroup(ctx context.Context, db *gorm.DB, user *User, group *Group) error

AddUserToGroup adds a persisted user to a persisted group.

func CSRFMiddleware

func CSRFMiddleware(cfg config.Config, exemptPaths ...string) gin.HandlerFunc

CSRFMiddleware enforces the double-submit CSRF defense documented in docs/auth-cookie.md for cookie-mode session auth (M5-3). It is a Gin middleware (not scoped to Huma auth routes) because CSRF must cover every state-changing request in the app, including future feature routes, not just the auth surface.

Safe methods (GET/HEAD/OPTIONS) bootstrap a signed CSRF cookie when one is missing. Other methods require a X-CSRF-Token header that matches the gombit_csrf cookie and verifies against cfg.Auth.JWTSecret; otherwise the request is rejected with a D10 403 authorization error.

framework.New wires this into the runtime middleware stack automatically when cfg.Auth.Enabled() and cfg.Auth.EffectiveMode() == AuthModeCookie.

exemptPaths are exact request paths that opt out of CSRF enforcement on unsafe methods — for non-browser endpoints (webhooks, server-to-server callbacks) that cannot participate in the double-submit defense and must authenticate themselves by other means (e.g. HMAC signature verification). Safe methods still bootstrap the cookie on those paths. See framework.WithCSRFExemptPaths and docs/auth-cookie.md.

func CaptureRequestInfo added in v0.9.0

func CaptureRequestInfo() func(ctx huma.Context, next func(huma.Context))

CaptureRequestInfo is a Huma middleware that stores the request's client address (gin's ClientIP, so GOMBIT_HTTP_TRUSTED_PROXIES is respected) and User-Agent for the audit events the operation records, and for the device a session it starts keeps (AUTH-12). Mount puts it on every framework auth route; an application puts it on its own operations that record events (RecordAuditEvent) or start sessions (Service.IssueTokens).

func CheckNewAccount added in v0.9.0

func CheckNewAccount(email, password string) error

CheckNewAccount reports whether email and password meet the account rules Register and CreateSuperuser apply, without touching the database (gombit createsuperuser checks before it opens one); those also refuse a duplicate email and a throttled address. Its verdict matches theirs, but a blank email, which it refuses as ErrInvalidEmail, is ErrInvalidCredentials from them. Two rules, for two reasons (#461):

  • the email, normalized, must be a bare address of at most 255 characters (ErrInvalidEmail): what POST /auth/login accepts, so the account can sign in;
  • the password must meet the policy a user's own password meets on register, change and reset, at least 8 characters and at most 72 bytes (a PasswordPolicyError on "password"). Login itself accepts any non-empty password; this is the policy, not a sign-in requirement.

func GrantPermissionToGroup

func GrantPermissionToGroup(ctx context.Context, db *gorm.DB, group *Group, permission *Permission) error

GrantPermissionToGroup grants a persisted permission to a persisted group.

func GrantPermissionToUser

func GrantPermissionToUser(ctx context.Context, db *gorm.DB, user *User, permission *Permission) error

GrantPermissionToUser grants a persisted permission directly to a user.

func HasPermission

func HasPermission(ctx context.Context, db *gorm.DB, user User, key string) (bool, error)

HasPermission reports whether user has key directly, through a group, or through the Django-style superuser bypass. A disabled account has none.

func HasPermissions

func HasPermissions(ctx context.Context, db *gorm.DB, user User, keys ...string) (map[string]bool, error)

HasPermissions checks several keys while loading the user's associations once. Missing users and unassigned keys are reported as false, and so is every key of a disabled account (User.Disabled), a superuser's too. For a stored user (an ID), the row is reloaded and decides, the superuser flag and the account state included: a snapshot loaded before the account was disabled or demoted grants nothing it no longer has. A user with no ID (never stored) is judged as given.

func Migrate

func Migrate(db *gorm.DB) error

Migrate creates the auth identity, token, group, permission, one-time token and audit tables.

func Models

func Models() []any

Models returns GORM models for Atlas / AutoMigrate.

func RecordAuditEvent added in v0.9.0

func RecordAuditEvent(ctx context.Context, db *gorm.DB, event AuditEvent) error

RecordAuditEvent writes event to auth_audit_events in db, completed from ctx: OccurredAt (now, when zero), the actor (the request's authenticated user, when ActorUserID is nil), and the request id, client IP and user agent (CaptureRequestInfo). It is the trail's entry point for code that has a database and no Service: the group and permission helpers, an application's own sensitive operations. It writes to the table whatever Auditor a Service has; Service.Audit goes through that Auditor.

func RequireVerifiedEmail added in v0.9.0

func RequireVerifiedEmail() func(ctx huma.Context, next func(huma.Context))

RequireVerifiedEmail is a Huma middleware for an application's own operations that only users with a verified email may use. It runs after the authentication gate (Service.RequireBearer or RequireCookieSession), which stores the user it loaded on the request; it answers 403 when that user's email is unverified, and 401 when no gate authenticated the request.

Middlewares: huma.Middlewares{svc.RequireBearer(), auth.RequireVerifiedEmail()}

Types

type AuditAction added in v0.9.0

type AuditAction string

AuditAction names a security-sensitive operation.

const (
	// AuditLoginSucceeded: a user signed in (the target).
	AuditLoginSucceeded AuditAction = "auth.login.succeeded"
	// AuditLoginFailed: a sign-in failed. The target is the account when
	// the email names one (a wrong password), and empty when it names none:
	// the attempted address is not recorded.
	AuditLoginFailed AuditAction = "auth.login.failed"
	// AuditLogout: a session was ended by logout.
	AuditLogout AuditAction = "auth.logout"
	// AuditRegistered: a user registered.
	AuditRegistered AuditAction = "auth.user.registered"
	// AuditSuperuserCreated: a superuser was created (gombit
	// createsuperuser).
	AuditSuperuserCreated AuditAction = "auth.superuser.created"
	// AuditUserDisabled: an account was disabled (its sessions revoked).
	AuditUserDisabled AuditAction = "auth.user.disabled"
	// AuditUserEnabled: a disabled account was enabled again.
	AuditUserEnabled AuditAction = "auth.user.enabled"
	// AuditMFAEnabled: a TOTP authenticator was confirmed (MFA on).
	AuditMFAEnabled AuditAction = "auth.mfa.enabled"
	// AuditMFADisabled: the user turned their MFA off.
	AuditMFADisabled AuditAction = "auth.mfa.disabled"
	// AuditMFAReset: an operator removed a user's MFA.
	AuditMFAReset AuditAction = "auth.mfa.reset"
	// AuditMFAFailed: an MFA operation refused a wrong password or code.
	AuditMFAFailed AuditAction = "auth.mfa.failed"
	// AuditMFARecoveryCodesRegenerated: the recovery codes were replaced.
	AuditMFARecoveryCodesRegenerated AuditAction = "auth.mfa.recovery_codes_regenerated"
	// AuditMFARecoveryCodeUsed: a login (or a disable) used a recovery code.
	AuditMFARecoveryCodeUsed AuditAction = "auth.mfa.recovery_code_used"
	// AuditRefreshReuse: an already-rotated refresh token was presented
	// again, and every session of the user was revoked.
	AuditRefreshReuse AuditAction = "auth.refresh.reuse_detected"
	// AuditRefreshReuseWithinGrace: a rotated refresh token was presented
	// again within config.AuthConfig.RefreshReuseGrace of its rotation: a
	// 401, nothing revoked. Usually two tabs refreshing a round trip apart;
	// also what a thief who rotated a stolen token first leaves when the
	// legitimate client comes back within the grace, the one trace of it.
	// TargetType "session" and TargetID name the successor's session by the
	// id GET /auth/sessions lists it under, which its refreshes keep
	// (AUTH-11); Details "successor" is "live" (it may be
	// either) or "ended" (signed out before the request came).
	AuditRefreshReuseWithinGrace AuditAction = "auth.refresh.reuse_within_grace"
	// AuditSessionRevoked: sessions were revoked (Details "scope": one,
	// others or all).
	AuditSessionRevoked AuditAction = "auth.session.revoked"
	// AuditEmailVerified: a user verified their email (POST
	// /auth/verify-email).
	AuditEmailVerified AuditAction = "auth.email.verified"
	// AuditPasswordResetRequested: a password reset message was sent to the
	// user (POST /auth/password/forgot). A request for an address that is no
	// account records nothing.
	AuditPasswordResetRequested AuditAction = "auth.password.reset_requested"
	// AuditPasswordReset: a user set a new password with a reset token
	// (Details "sessions_revoked").
	AuditPasswordReset AuditAction = "auth.password.reset"
	// AuditPasswordChanged: a signed-in user changed their password with
	// their current one (Details "other_sessions_revoked").
	AuditPasswordChanged AuditAction = "auth.password.changed"
	// AuditPasswordChangeFailed: a password change was refused because the
	// current password given was wrong.
	AuditPasswordChangeFailed AuditAction = "auth.password.change_failed"
	// AuditEmailChangeRequested: a confirmation link was mailed to the new
	// address a signed-in user asked for (the addresses are not recorded).
	AuditEmailChangeRequested AuditAction = "auth.email.change_requested"
	// AuditEmailChangeFailed: an email change was refused because the
	// current password given was wrong.
	AuditEmailChangeFailed AuditAction = "auth.email.change_failed"
	// AuditEmailChanged: the user confirmed the new address; it is now their
	// email, verified.
	AuditEmailChanged AuditAction = "auth.email.changed"
	// AuditIdentityLinked: an external identity was linked to the user
	// (Details "provider").
	AuditIdentityLinked AuditAction = "auth.identity.linked"
	// AuditIdentityLinkFailed: linking an external identity was refused
	// (Details "provider", "reason"; a wrong current password).
	AuditIdentityLinkFailed AuditAction = "auth.identity.link_failed"
	// AuditIdentityUnlinked: the user removed a linked identity (Details
	// "provider").
	AuditIdentityUnlinked AuditAction = "auth.identity.unlinked"
	// AuditGroupMemberAdded: a user was added to a group (Details "group").
	AuditGroupMemberAdded AuditAction = "auth.group.member_added"
	// AuditPermissionGranted: a permission was granted to a user or a group
	// (Details "permission", and "group" for a group).
	AuditPermissionGranted AuditAction = "auth.permission.granted"
	// AuditAdminCreated, AuditAdminUpdated and AuditAdminDeleted: a record
	// was written through the admin data plane (target: the model's slug and
	// the record's primary key).
	AuditAdminCreated AuditAction = "admin.record.created"
	AuditAdminUpdated AuditAction = "admin.record.updated"
	AuditAdminDeleted AuditAction = "admin.record.deleted"
)

type AuditEvent added in v0.9.0

type AuditEvent struct {
	ID uint `gorm:"primaryKey"`
	// OccurredAt is when the operation ran.
	OccurredAt time.Time `gorm:"not null;index"`
	// Action is what was done.
	Action AuditAction `gorm:"size:64;not null;index"`
	// ActorUserID is the user who did it: the request's authenticated user,
	// or the user signing in. Nil for an anonymous request or a command.
	ActorUserID *uint `gorm:"index"`
	// TargetUserID is the account the operation concerns, when it concerns
	// one.
	TargetUserID *uint `gorm:"index"`
	// TargetType and TargetID name any other target: an admin model's slug
	// and a record's primary key, stored whole (neither a slug nor a string
	// key has a length bound).
	TargetType string `gorm:"type:text"`
	TargetID   string `gorm:"type:text"`
	// RequestID, IP and UserAgent correlate it with the request, where there
	// was one: the X-Request-Id the logs carry (at most
	// contract.MaxRequestIDLength, which framework.App enforces where it
	// accepts one), the client address (trusted proxies respected), and the
	// User-Agent, the one value cut (to 255 bytes): free text, not an
	// identifier.
	RequestID string `gorm:"size:128;index"`
	IP        string `gorm:"size:64"`
	UserAgent string `gorm:"size:255"`
	// Details is a JSON object of names and ids: "{}" when empty, and an
	// event whose Details is not a JSON object is refused.
	Details string `gorm:"type:text"`
}

AuditEvent is one entry of the security audit trail.

func ListAuditEvents added in v0.9.0

func ListAuditEvents(ctx context.Context, db *gorm.DB, q AuditQuery) ([]AuditEvent, error)

ListAuditEvents returns the audit events q selects, newest first.

func (AuditEvent) TableName added in v0.9.0

func (AuditEvent) TableName() string

TableName keeps the table in the auth_ namespace.

type AuditQuery added in v0.9.0

type AuditQuery struct {
	ActorUserID  uint
	TargetUserID uint
	Action       AuditAction
	// Limit caps the events returned, newest first: 100 when zero, at most
	// 1000.
	Limit int
}

AuditQuery selects audit events (ListAuditEvents). Zero fields match all.

type Auditor added in v0.9.0

type Auditor interface {
	Record(ctx context.Context, event AuditEvent) error
}

Auditor records audit events. The default writes them to auth_audit_events in the service's database; an application may send them elsewhere as well (a SIEM) with WithAuditor. Record is called on the request, after the operation succeeded or failed, with a context that keeps the request's values but not its cancellation (the operation has happened; a client that hung up must not cancel its record) and carries its own deadline (auditTimeout), which Record must honor: the request waits for it. An error is logged, and does not fail the operation.

func DBAuditor added in v0.9.0

func DBAuditor(db *gorm.DB) Auditor

DBAuditor writes audit events to auth_audit_events in db.

type AuthSession added in v0.8.0

type AuthSession struct {
	ID              string    `` /* 154-byte string literal not displayed */
	LastRefreshedAt time.Time `` /* 157-byte string literal not displayed */
	ExpiresAt       time.Time `json:"expires_at" doc:"When the session ends unless it refreshes first"`
	Current         bool      `json:"current" example:"true" doc:"True for the session that made this request"`
	UserAgent       string    `` /* 233-byte string literal not displayed */
	ClientAddress   string    `` /* 262-byte string literal not displayed */
	Location        string    `` /* 161-byte string literal not displayed */
}

AuthSession is one active sign-in as the sessions API lists it. Huma names a schema after its Go type, in the one namespace every operation of the app shares, and two types with the same name panic at boot: the Auth prefix keeps it clear of an application's own Session type.

type AuthorizationRequest added in v0.9.0

type AuthorizationRequest struct {
	// State is the opaque value the provider must send back unchanged.
	State string
	// Nonce goes in an OIDC authentication request (nonce) and comes back in
	// the ID token.
	Nonce string
	// CodeChallenge is the PKCE challenge (RFC 7636), with
	// CodeChallengeMethod "S256".
	CodeChallenge       string
	CodeChallengeMethod string
}

AuthorizationRequest is what the authorization URL carries.

type Clock

type Clock interface {
	Now() time.Time
}

Clock is the time source used for token expiry. Tests inject a fake.

type ExchangeRequest added in v0.9.0

type ExchangeRequest struct {
	// Code is the authorization code the provider returned.
	Code string
	// CodeVerifier is the PKCE verifier of AuthorizationRequest's challenge.
	CodeVerifier string
	// Nonce is the nonce AuthorizationRequest carried.
	Nonce string
}

ExchangeRequest is what Exchange redeems.

type ExternalIdentity added in v0.9.0

type ExternalIdentity struct {
	// Subject is the provider's stable, unique id for the user (OIDC sub):
	// never an email, which can change hands. Required; at most 255 bytes.
	Subject string
	// Email is the user's address at the provider, if it shares one.
	Email string
	// EmailVerified is whether the provider verified Email. Only a verified
	// email makes an account.
	EmailVerified bool
	// Nonce is the ID token's nonce (OIDC); empty for plain OAuth2.
	Nonce string
}

ExternalIdentity is the user as the provider vouches for them.

type Group

type Group struct {
	ID          uint         `gorm:"primaryKey"`
	Name        string       `gorm:"uniqueIndex;not null;size:100"`
	Permissions []Permission `gorm:"many2many:auth_group_permissions;"`
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

Group collects permissions that can be assigned to users.

func EnsureGroup

func EnsureGroup(ctx context.Context, db *gorm.DB, name string) (Group, error)

EnsureGroup returns the group with name, creating it when needed, with EnsurePermission's guarantee for concurrent first calls (#463).

type Hasher

type Hasher interface {
	Hash(password string) (string, error)
	Compare(hash, password string) error
}

Hasher hashes and compares passwords.

type IDTokenProvider added in v0.9.0

type IDTokenProvider interface {
	IssuesIDTokens() bool
}

IDTokenProvider is implemented by an adapter whose identities come from an OpenID Connect ID token (auth/oidc's). One whose IssuesIDTokens is true declares that each identity carries the token's nonce, and the framework holds it to that: an identity with no nonce, or another flow's, is refused. Without the declaration the framework can only refuse a nonce that is returned and wrong: it cannot tell a plain OAuth2 adapter (no ID token, no nonce) from an OIDC adapter that forgot to check and return it.

type IdentityLink struct {
	ID       uint   `gorm:"primaryKey"`
	UserID   uint   `gorm:"index;not null"`
	Provider string `gorm:"size:32;not null;uniqueIndex:idx_auth_identity_links_provider_subject,priority:1"`
	// SubjectKey is the SHA-256 (hex) of Subject: what identifies the link.
	// The subject is compared byte for byte (an OIDC sub is case-sensitive),
	// and a column compared under a collation that ignores case or trailing
	// spaces (MySQL's default) would let two users' subjects meet.
	SubjectKey string `gorm:"size:64;not null;uniqueIndex:idx_auth_identity_links_provider_subject,priority:2"`
	// Subject is the provider's id for the user, as it sent it.
	Subject string `gorm:"size:255;not null"`
	// Email is the identity's address at the provider when it last signed
	// in, for display: it decides nothing.
	Email string `gorm:"size:255;not null;default:''"`
	// LastUsedAt is the identity's latest sign-in; nil until one.
	LastUsedAt *time.Time
	CreatedAt  time.Time
}

IdentityLink maps an identity at a provider to a local user: who signs in with it. One identity (provider, subject) links one user; a user may link several.

func (IdentityLink) TableName added in v0.9.0

func (IdentityLink) TableName() string

TableName keeps the table in the auth_ namespace.

type IdentityProvider added in v0.9.0

type IdentityProvider interface {
	// Name is the provider's stable name, in the routes' paths and the
	// stored links ("google", "okta"): 1 to 32 lowercase letters, digits,
	// '-' or '_'. Renaming a provider orphans its links.
	Name() string
	// AuthCodeURL is the provider's authorization URL for req.
	AuthCodeURL(req AuthorizationRequest) (string, error)
	// Exchange redeems the authorization code for the user's identity.
	Exchange(ctx context.Context, req ExchangeRequest) (ExternalIdentity, error)
}

IdentityProvider is an external identity provider's adapter. The framework calls AuthCodeURL to send the user to the provider, then Exchange with the code the provider sends back.

The framework owns the request's state, nonce and PKCE pair: the adapter puts them in the authorization URL and the token request as its protocol says, and checks nothing of the state (the framework did, before Exchange). An OIDC adapter must verify the ID token (issuer, audience, signature, expiry) and its nonce against ExchangeRequest.Nonce, return the token's nonce in ExternalIdentity.Nonce, and declare itself an IDTokenProvider: the framework then refuses an identity whose nonce is missing or not the request's. A plain OAuth2 adapter (no ID token) leaves Nonce empty, and relies on the state and PKCE.

type MFAStatus added in v0.9.0

type MFAStatus struct {
	Enabled           bool
	PendingEnrollment bool
	// RecoveryCodesLeft is how many unused recovery codes remain.
	RecoveryCodesLeft int
}

MFAStatus is a user's MFA state.

type Mailer added in v0.9.0

type Mailer interface {
	Send(ctx context.Context, msg Message) error
}

Mailer delivers the messages of the account lifecycle (AUTH-1): the email verification link, and later password reset and email change. It is the one seam to an email provider: the application implements it over its own (SMTP, an API) and passes it with WithMailer (or framework.WithAuthMailer). Tests use authtest.Mailer, which records the messages instead of sending them.

Send is synchronous: it returns nil only once the provider accepted the message (the SMTP server took it, the API answered), because that is when the message's token starts working and the user's earlier ones stop. A Mailer that only enqueues the message would supersede the earlier links before the new one is delivered, and a delivery that then failed could not undo it. Send must also return once ctx is done: the background work that calls it (a password reset) is cancelled at its deadline and on shutdown, and a Send that ignores that keeps its worker for good. Send is called on the request that needs the message. An error is the message not going out: the request reports it where the message is the point (a resend), and logs it where it is a side effect (registration).

func LogMailer added in v0.9.0

func LogMailer(logger *zap.Logger) Mailer

LogMailer is a development Mailer: it logs each message, link and token included, instead of sending it, so a local app's verification flow works with no email provider. framework.New uses it outside production when no Mailer is set. Never use it in production: the log would hold credentials.

type Message added in v0.9.0

type Message struct {
	Kind MessageKind
	// To is the address the message goes to.
	To string
	// Subject and Text are the default subject and plain-text body.
	Subject string
	Text    string
	// Token is the single-use token the message carries, and URL the link
	// with it (config.AuthConfig.EmailVerificationURL or PasswordResetURL;
	// empty when none is configured).
	Token string
	URL   string
	// ExpiresAt is when the token stops working.
	ExpiresAt time.Time
}

Message is one lifecycle email. Subject and Text are a plain default a Mailer may send as they are; Token, URL and ExpiresAt let it render its own. Token is a credential: a Mailer must not log it.

type MessageKind added in v0.9.0

type MessageKind string

MessageKind names a lifecycle message, so a Mailer can pick its own template.

const (
	// MessageVerifyEmail asks the user to confirm they own the address.
	MessageVerifyEmail MessageKind = "verify_email"
	// MessageResetPassword carries a link to set a new password.
	MessageResetPassword MessageKind = "reset_password"
	// MessageChangeEmail, to the new address, carries the link that
	// confirms an email change.
	MessageChangeEmail MessageKind = "change_email"
	// MessageEmailChanged, to the old address, tells its owner the
	// account's email was changed (a security notification, no token).
	MessageEmailChanged MessageKind = "email_changed"
)

type OneTimeToken added in v0.9.0

type OneTimeToken struct {
	ID        uint         `gorm:"primaryKey"`
	UserID    uint         `gorm:"not null;index:idx_auth_one_time_tokens_user_purpose,priority:1"`
	Purpose   TokenPurpose `gorm:"size:32;not null;index:idx_auth_one_time_tokens_user_purpose,priority:2"`
	TokenHash string       `gorm:"uniqueIndex;size:64;not null"`
	Email     string       `gorm:"size:255;not null"`
	FromEmail string       `gorm:"size:255;not null;default:''"`
	ExpiresAt time.Time    `gorm:"index;not null"`
	// SentAt is when the message carrying the token was delivered to the
	// Mailer; nil while it is pending.
	SentAt *time.Time
	// UsedAt is when the token was consumed, or superseded by a newer one
	// for the same purpose; nil while it can still be used.
	UsedAt    *time.Time
	CreatedAt time.Time
}

OneTimeToken is a hashed, expiring, single-use token the account lifecycle mails to a user: email verification (AUTH-1), and the reset and change flows that build on it. The raw token exists only in the message; the row keeps its SHA-256. Email is the address it was mailed to, the one it proves; FromEmail is the user's email when it was issued (the same for every purpose but an email change, whose token goes to the new address). A token works only while the user's email is FromEmail: a check that holds again if the email is written back to it. Only ConfirmEmailChange (which voids the user's other tokens) and the password flows (which void the reset and change links) stop tokens for good; an Email written by another path (an app's own update) is guarded by this check alone.

A token is pending until the message carrying it was delivered to the Mailer (SentAt): a pending token does not work. Delivery activates it and supersedes the user's earlier tokens for the purpose in one transaction, so no failure leaves an undelivered token working, or two delivered ones.

func (OneTimeToken) TableName added in v0.9.0

func (OneTimeToken) TableName() string

TableName keeps the table in the auth_ namespace.

type Option added in v0.9.0

type Option func(*Service)

Option configures a Service (NewService) or the routes Mount registers.

func WithAuditor added in v0.9.0

func WithAuditor(a Auditor) Option

WithAuditor replaces the Service's Auditor.

func WithIdentityProviders added in v0.9.0

func WithIdentityProviders(providers ...IdentityProvider) Option

WithIdentityProviders registers external identity providers: with at least one, the routes mount /auth/external/*. Names must be valid and distinct (NewService fails otherwise).

func WithLogger added in v0.9.0

func WithLogger(l *zap.Logger) Option

WithLogger sets the logger for what the service reports without failing the request (a verification message that could not be sent at registration). Default: none.

func WithMailer added in v0.9.0

func WithMailer(m Mailer) Option

WithMailer sets the Mailer the account lifecycle's messages go through (email verification). Without one, sending a message fails with ErrNoMailer, and registration sends none.

func WithSessionLocator added in v0.10.0

func WithSessionLocator(l SessionLocator) Option

WithSessionLocator sets the SessionLocator that names a session's location when it starts. Without one, sessions have no location.

func WithThrottlePolicy added in v0.9.0

func WithThrottlePolicy(p ThrottlePolicy) Option

WithThrottlePolicy replaces the credential endpoints' limits (DefaultThrottlePolicy).

func WithThrottleStore added in v0.9.0

func WithThrottleStore(c cache.Cache) Option

WithThrottleStore keeps the throttles' counters in c: an app's cache (Redis, to share them between instances). The Service does not close it. Without one, it keeps them in a process-local memory cache of its own, which Close stops.

func WithoutExternalSignup added in v0.9.0

func WithoutExternalSignup() Option

WithoutExternalSignup stops an external sign-in from making accounts: an identity no user linked is refused (signup_disabled), and users link identities from their signed-in accounts only.

type PasswordChange added in v0.9.0

type PasswordChange struct {
	// KeepOtherSessions leaves the user's other sessions signed in. By
	// default every session but the requesting one ends: whoever knew the
	// old password is signed out.
	KeepOtherSessions bool
}

PasswordChange is what ChangePassword does besides setting the password.

type PasswordPolicyError added in v0.9.0

type PasswordPolicyError struct {
	Field string
	Err   error
}

PasswordPolicyError is a new password the policy refuses (ChangePassword, ResetPassword, and Register, CreateSuperuser and CheckNewAccount for a new account's): Err is the reason (ErrPasswordTooShort, ErrPasswordTooLong, ErrPasswordRequired), Field the request field the password came in ("new_password" for a change, "password" for a reset or a new account), so the error is reported where the form put it.

func (PasswordPolicyError) Error added in v0.9.0

func (e PasswordPolicyError) Error() string

func (PasswordPolicyError) Unwrap added in v0.9.0

func (e PasswordPolicyError) Unwrap() error

type Permission

type Permission struct {
	ID          uint   `gorm:"primaryKey"`
	Key         string `gorm:"column:permission_key;uniqueIndex;not null;size:120"` // not "key": reserved in MySQL
	Description string `gorm:"size:255"`
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

Permission is a stable authorization key, such as admin.widgets.view.

func EnsurePermission

func EnsurePermission(ctx context.Context, db *gorm.DB, key, description string) (Permission, error)

EnsurePermission returns the permission for key, creating it when needed. Concurrent first calls for one key (replicas seeding at boot) all get the one row, not a unique violation (#463), outside a transaction and inside one at READ COMMITTED or on MySQL; a lost race does not abort the caller's transaction. Inside a PostgreSQL REPEATABLE READ or SERIALIZABLE transaction the winner's row is not visible, so a lost race returns the unique violation (or a serialization failure) and the caller retries the transaction.

type PublicUser

type PublicUser struct {
	ID            uint   `json:"id" example:"1" doc:"User identifier"`
	Email         string `json:"email" example:"ada@example.com" format:"email" doc:"Normalized email"`
	EmailVerified bool   `json:"email_verified" example:"false" doc:"True once the user has confirmed they own email (POST /auth/verify-email)"`
}

PublicUser is the safe user representation returned by register and /me.

type RecoveryCode added in v0.9.0

type RecoveryCode struct {
	ID       uint   `gorm:"primaryKey"`
	UserID   uint   `gorm:"index;not null"`
	CodeHash string `gorm:"uniqueIndex;size:64;not null"`
	// UsedAt is when the code was used; a used code is refused.
	UsedAt    *time.Time
	CreatedAt time.Time
}

RecoveryCode is one of a user's single-use MFA recovery codes, hashed.

func (RecoveryCode) TableName added in v0.9.0

func (RecoveryCode) TableName() string

TableName is the recovery codes' table.

type RefreshToken

type RefreshToken struct {
	ID         uint       `gorm:"primaryKey"`
	UserID     uint       `gorm:"index;not null"`
	TokenHash  string     `gorm:"uniqueIndex;size:64;not null"`
	ExpiresAt  time.Time  `gorm:"index;not null"`
	RevokedAt  *time.Time `gorm:"index"`
	ReplacedBy *uint
	// SessionID is the session's identifier: random, set by the login and
	// carried to every rotation's successor, and the id the sessions API
	// shows (AUTH-11). Rows written before the column existed, or by a binary
	// from before it, have none; such a row is identified by an HMAC of its
	// row id (Service.sessionIDOf), which its next rotation stores as the
	// successor's SessionID. An index for finding a session's head:
	// ReplacedBy stays the chain's truth.
	SessionID string `gorm:"size:32;index"`
	// UserAgent, ClientAddress and Location describe the device that
	// started the session (AUTH-12): the sign-in request's User-Agent, its
	// client address as config.AuthConfig.SessionClientAddress keeps it
	// (its network by default), and what the application's SessionLocator
	// named. The login sets them and rotation copies them; empty when
	// unknown, and on rows from before the columns existed.
	UserAgent     string `gorm:"size:255"`
	ClientAddress string `gorm:"size:64"`
	Location      string `gorm:"size:128"`
	CreatedAt     time.Time
}

RefreshToken is a hashed, rotating refresh credential. A login writes the first row of a session; each rotation revokes the row and writes its successor (ReplacedBy), with the same SessionID.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is the runtime auth implementation: users, password hashes, access JWTs, and rotating refresh tokens.

func Mount

func Mount(api huma.API, db *gorm.DB, cfg config.Config, opts ...Option) (*Service, error)

Mount registers framework-owned auth Huma routes on api. The route shapes differ by cfg.Auth.EffectiveMode(): AuthModeJWT (default) mounts the Bearer token surface (register/login/refresh/logout/me exchanging JSON tokens); AuthModeCookie mounts the same operation IDs and paths but exchanges HttpOnly session cookies instead, plus GET /auth/csrf. The two modes are mutually exclusive per app — see docs/auth-cookie.md for the cookie/CSRF threat model. Both modes mount email verification (AUTH-1) and password reset (AUTH-2), and, with WithIdentityProviders, the external identity routes under /auth/external (AUTH-10); opts configure the Service the routes use (WithMailer, WithLogger, WithAuditor, WithIdentityProviders).

Mount returns the Service the routes use, built from cfg (so the routes and the Service share one configuration), and the caller owns it: the Service runs background work (password reset messages) that Close drains and cancels, and the caller closes it on shutdown, before what the work uses (the database, the mailer). framework.App does. With auth disabled, Mount mounts nothing and returns a nil Service.

func NewService

func NewService(db *gorm.DB, cfg config.Config, opts ...Option) (*Service, error)

NewService constructs a Service. cfg.Auth.JWTSecret must be set.

func (*Service) Audit added in v0.9.0

func (s *Service) Audit(ctx context.Context, event AuditEvent)

Audit records event through the Service's Auditor, completed from ctx as RecordAuditEvent completes it. A failure is logged, not returned: the operation it records has happened.

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, email, password string) (User, error)

Authenticate verifies email and password. It fails with ErrInvalidCredentials for an unknown email or a wrong password (a 401), ErrAccountDisabled for the right password of a disabled account (a 403), ErrMFARequired for the right password of an account with multi-factor authentication (a 422 on mfa_code: AuthenticateMFA takes the code), and a *ThrottleError (errors.Is ErrTooManyAttempts, a 429) past a login throttle or MFAPerUser; any other error is a server failure (the user lookup's database error, an MFA secret the current key cannot open), which a caller must not answer as wrong credentials (#460).

func (*Service) AuthenticateMFA added in v0.9.0

func (s *Service) AuthenticateMFA(ctx context.Context, email, password, code string) (User, error)

AuthenticateMFA is Authenticate with the second factor of an account with MFA enabled: code is a code from its authenticator or one of its recovery codes. Such an account answers ErrMFARequired for no code (told, like a disabled account, only after the right password) and ErrInvalidMFACode for a wrong one (a failure, throttled by MFAPerUser too). For an account without MFA, code is ignored.

func (*Service) BeginTOTPEnrollment added in v0.9.0

func (s *Service) BeginTOTPEnrollment(ctx context.Context, userID uint, current string) (TOTPEnrollment, error)

BeginTOTPEnrollment starts userID's TOTP enrollment, current being their password: it returns the new secret for their authenticator app, pending until ConfirmTOTPEnrollment gets a code from it (a new enrollment replaces one pending). It returns ErrMFAAlreadyEnabled when MFA is enabled (disable it first), and ErrWrongCurrentPassword (audited).

func (*Service) ChangePassword added in v0.9.0

func (s *Service) ChangePassword(ctx context.Context, userID uint, current, newPassword string, change PasswordChange) (bool, error)

ChangePassword sets userID's password to newPassword once current is the password the user has now.

The requesting session is the one ctx carries: an operation behind the auth gate (Service.RequireBearer, RequireCookieSession) runs with the signed-in user's session in its context, and when that user is userID the session stays signed in. With no such session (a command, another user's request), unless change.KeepOtherSessions, every session of the user ends.

The new password must satisfy the password policy (a PasswordPolicyError, Field "new_password"), and current must be the user's password (ErrWrongCurrentPassword, audited); both are checked before any lock. Then, under the user's row lock, in one transaction: the requesting session must still be signed in (ErrSessionEnded otherwise); the stored hash must still be the one checked (ErrPasswordChanged otherwise); the new hash is written; every outstanding password reset token of the user stops working (a reset link mailed before the change must not undo it), and so does every email change link (asked with the old password); and, unless change.KeepOtherSessions, the user's other sessions end. Any of those errors changes nothing. It returns whether other sessions were revoked; an unknown userID is ErrUserNotFound, and any other error a database failure.

func (*Service) Close added in v0.9.0

func (s *Service) Close(ctx context.Context) error

Close finishes the Service's background work (the password reset messages POST /auth/password/forgot accepted, the email-changed notifications): it stops admitting more, waits for the admitted work until ctx is done, then cancels what is left. framework.App calls it when it stops; an application that mounts the routes itself calls it, on the Service Mount returned, on shutdown. The shutdown runs once: a Close while another runs waits for it (or for its own ctx), and every Close returns its result, so none reports success before the work is done. After Close, the routes answer background requests with 503, and a refresh-token rotation in flight is cancelled (its transaction rolls back) and every later one fails at once with context.Canceled: a shared rotation runs on a context the Service owns (detach). Close also stops the janitor of the throttles' own memory cache, when the Service made one (WithThrottleStore not given).

func (*Service) ConfirmEmailChange added in v0.9.0

func (s *Service) ConfirmEmailChange(ctx context.Context, raw string) (User, error)

ConfirmEmailChange consumes an email change token and makes the address it was mailed to the user's email, verified (the token proves it). It works only while the user's email is the one the change was asked from (FromEmail): while it is another, the token is ErrInvalidToken, like an unknown, expired, used or superseded one. That check alone is reversible (an email written back by another path matches again); the voiding below is what stops links for good, on this path. An address another account took meanwhile is ErrEmailTaken (first come, first served: the unique email decides), and changes nothing. Every other one-time link of the user stops working for good, whatever its purpose (verification, password reset, other email changes), so none comes back if the email changes back. The old address is told, best effort.

func (*Service) ConfirmTOTPEnrollment added in v0.9.0

func (s *Service) ConfirmTOTPEnrollment(ctx context.Context, userID uint, code string) ([]string, error)

ConfirmTOTPEnrollment enables MFA for userID with a code from the authenticator their pending enrollment set up, and returns the account's recovery codes, shown this once (only their hashes are kept). Every other session of the user ends (the one ctx's request carries stays; with none, all end): they were started on the password alone. It returns ErrNoPendingEnrollment, ErrInvalidMFACode (throttled by MFAPerUser), ErrMFAAlreadyEnabled, and ErrSessionEnded when the requesting session ended meanwhile.

func (*Service) CreateSuperuser

func (s *Service) CreateSuperuser(ctx context.Context, email, password string) (User, error)

CreateSuperuser creates a user with IsSuperuser set, for gombit createsuperuser (M4-6). It shares Register's hasher, uniqueness path and rules: an empty email is ErrInvalidCredentials, any other one that is not a bare address ErrInvalidEmail, a password the policy refuses a PasswordPolicyError (CheckNewAccount), a duplicate email errEmailTaken. The operator who creates it vouches for the address, so its email starts verified, and no message is sent.

func (*Service) DisableMFA added in v0.9.0

func (s *Service) DisableMFA(ctx context.Context, userID uint, current, code string) error

DisableMFA turns userID's MFA off, current being their password and code a code from their authenticator or a recovery code (so a stolen session and password alone do not remove the second factor): the factor and the recovery codes are deleted. It returns ErrMFANotEnabled, ErrWrongCurrentPassword (audited) and ErrInvalidMFACode (throttled).

func (*Service) DisableUser added in v0.9.0

func (s *Service) DisableUser(ctx context.Context, userID uint) (User, error)

DisableUser disables userID's account: its sessions are revoked and its one-time links voided, in one transaction under the user's row lock, so a login, a refresh or a link that races it either finished before it or is refused after. Disabling a disabled account changes nothing (its DisabledAt stays). It returns the user, and ErrUserNotFound for an unknown userID. It checks no permission: it is for an app's own code and commands; the HTTP route checks PermissionManageUsers.

func (*Service) EnableUser added in v0.9.0

func (s *Service) EnableUser(ctx context.Context, userID uint) (User, error)

EnableUser makes userID's disabled account active again: the user may sign in. The sessions and links revoked when it was disabled stay revoked. Enabling an active account changes nothing. It returns the user, and ErrUserNotFound for an unknown userID. Like DisableUser, it checks no permission.

func (*Service) IdentityProviders added in v0.9.0

func (s *Service) IdentityProviders() []string

IdentityProviders returns the registered providers' names, in registration order.

func (*Service) IssueTokens

func (s *Service) IssueTokens(ctx context.Context, user User) (TokenPair, error)

IssueTokens returns a new access JWT and a rotating refresh token for user: it starts a session, so it records the login as succeeded (Authenticate records the failures). user is a snapshot, as Authenticate returned it or as loaded from the database: its PasswordHash must still be the user's when the session starts, and the user must still exist, or IssueTokens fails as invalid credentials (ErrInvalidCredentials); the account must not be disabled (ErrAccountDisabled); any other error is a server failure. So Authenticate followed by IssueTokens is as safe as Login: a password reset or a disable that commits between the two leaves the snapshot unable to start a session, and so does multi-factor authentication enabled after Authenticate found none (ErrMFARequired). A snapshot loaded from the database (no Authenticate) is the caller's to have authenticated, second factor included. The session records the device of the request ctx came through (CaptureRequestInfo, which the auth routes put first; an application's own login route adds it): none without one.

func (s *Service) ListIdentityLinks(ctx context.Context, userID uint) ([]IdentityLink, error)

ListIdentityLinks returns the user's linked identities, oldest first.

func (*Service) ListSessions added in v0.8.0

func (s *Service) ListSessions(ctx context.Context, userID uint) ([]AuthSession, error)

ListSessions returns the user's active sessions, most recently refreshed first. When ctx comes from a request the auth middlewares authenticated, the request's own session has Current set, also when it refreshed while the request ran; otherwise none does.

func (*Service) Login added in v0.9.0

func (s *Service) Login(ctx context.Context, email, password string) (User, TokenPair, error)

Login verifies email and password and starts a session, as POST /auth/login does. The session is created under the user's row lock, and only if the password hash it verified is still the user's: a password reset (or any change of the hash) that commits between the check and the session either finds the session and revokes it, or makes this login fail as invalid credentials. The old password never outlives its change.

func (*Service) LoginMFA added in v0.9.0

func (s *Service) LoginMFA(ctx context.Context, email, password, code string) (User, TokenPair, error)

LoginMFA is Login with the second factor of an account with MFA enabled (AuthenticateMFA), as POST /auth/login with mfa_code.

func (*Service) MFAStatusOf added in v0.9.0

func (s *Service) MFAStatusOf(ctx context.Context, userID uint) (MFAStatus, error)

MFAStatusOf is userID's MFA state.

func (*Service) ParseAccess

func (s *Service) ParseAccess(ctx context.Context, token string) (User, error)

ParseAccess validates an access JWT, from the Bearer header or the session cookie, and loads its user. It fails with ErrInvalidAccessToken when the token is invalid or its session has ended (its refresh token row is gone, revoked or expired); any other error is the database's, loading the user or the session, a server failure a gate must not answer as a 401 (#460).

func (*Service) RegenerateRecoveryCodes added in v0.9.0

func (s *Service) RegenerateRecoveryCodes(ctx context.Context, userID uint, current, code string) ([]string, error)

RegenerateRecoveryCodes replaces userID's recovery codes (the old ones stop working) and returns the new ones, current being their password and code a code from their authenticator or a recovery code: new codes are a second factor, so a stolen session and password alone do not mint them. It returns ErrMFANotEnabled, ErrWrongCurrentPassword (audited) and ErrInvalidMFACode (throttled).

func (*Service) Register

func (s *Service) Register(ctx context.Context, email, password string) (User, error)

Register creates a user, with an unverified email, and mails them a verification link when a Mailer is configured (a failure to send is logged, not returned: POST /auth/verify-email/resend asks again). Duplicate emails return errEmailTaken; an empty email ErrInvalidCredentials; any other email that is not a bare address ErrInvalidEmail, and a password the policy refuses a PasswordPolicyError (CheckNewAccount; #461).

func (*Service) RequestEmailChange added in v0.9.0

func (s *Service) RequestEmailChange(ctx context.Context, userID uint, current, newEmail string) error

RequestEmailChange mails a confirmation link to newEmail, the address userID asks to change their email to, once current is their password. The account's email does not change here; ConfirmEmailChange does it, with the link. It returns ErrInvalidEmail for a new address that is not a bare address of at most 255 characters (what the route's schema accepts), ErrEmailUnchanged for the account's own, ErrWrongCurrentPassword (audited), ErrEmailTaken when another account has the address, ErrPasswordChanged when a reset or a password change committed after current was checked (the old password authorizes nothing after it), ErrEmailChangedMeanwhile when another email change did, the resend wait (one message a minute) or the Mailer's error, and ErrUserNotFound for an unknown userID. A newer request supersedes the earlier link: only the latest delivered one works.

func (*Service) RequestPasswordReset added in v0.9.0

func (s *Service) RequestPasswordReset(ctx context.Context, email string) error

RequestPasswordReset mails a password reset token to the account whose email is email. For an address that is no account it does nothing and returns nil. Otherwise it returns what sending returns: an error naming the wait when the previous reset message went out (or is going out) less than a minute ago, or the Mailer's error. The result tells whether email is an account: an endpoint must not show it (POST /auth/password/forgot answers before it is known).

func (*Service) RequireBearer added in v0.9.0

func (s *Service) RequireBearer() func(ctx huma.Context, next func(huma.Context))

RequireBearer is the exported Bearer gate for an application's own operations: it authenticates the Authorization header's access JWT and stores the User on the request context for UserFromContext (and RequireVerifiedEmail).

func (*Service) RequireCookieSession

func (s *Service) RequireCookieSession() func(ctx huma.Context, next func(huma.Context))

RequireCookieSession is the exported cookie-session gate used by runtime packages such as admin. It authenticates the gombit_access cookie and stores the User on the request context for UserFromContext. It does not itself enforce CSRF; CSRFMiddleware (csrf.go) is wired as global Gin middleware ahead of it for state-changing requests.

func (*Service) ResetMFA added in v0.9.0

func (s *Service) ResetMFA(ctx context.Context, userID uint) error

ResetMFA removes userID's MFA (the factor, pending or enabled, and the recovery codes), for a user who lost their authenticator and codes, and revokes every session of the user (the lost device may hold one). It checks no permission, like DisableUser: the HTTP route checks PermissionManageUsers. It returns ErrUserNotFound for an unknown userID; resetting an account without MFA changes nothing.

func (*Service) ResetPassword added in v0.9.0

func (s *Service) ResetPassword(ctx context.Context, raw, password string) (User, error)

ResetPassword consumes a password reset token and sets the user's password to password, hashed as registration hashes it (the Hasher's limits apply). It returns ErrInvalidToken for a token that is unknown, expired, used, superseded, never delivered, or issued for an address the user no longer has. The user's other reset tokens and their email change links (asked with the old password) stop working, and unless AuthConfig.PasswordResetKeepSessions, so do all of the user's sessions and refresh tokens, and the user's linked external identities are removed, in the same transaction.

func (*Service) RevokeAllSessions added in v0.8.0

func (s *Service) RevokeAllSessions(ctx context.Context, userID uint) error

RevokeAllSessions ends every active session of the user. It returns ErrSessionNotFound when the user does not exist. Like RevokeSession, it does not look at the caller's own session; the route checks the request's (revokeAllSessionsAs).

func (*Service) RevokeRefresh

func (s *Service) RevokeRefresh(ctx context.Context, raw string) error

RevokeRefresh ends the session of a refresh token: the token itself, or, when the token has rotated (a refresh in flight as the user signs out, or a client still holding the previous token), the session's current head (#466), found by the session's SessionID however many rotations on, or along replaced_by where that finds none (sessionHead). A token followed along replaced_by maxChainHops (1000) or more rotations behind its head, or a session whose head cannot be found (errChainUnresolved), fails with a 500 rather than succeed having ended nothing; revoking the session (DELETE /auth/sessions/{id}, or ?scope=all) ends it then. A token unknown, past its own expiry, or of a session already ended revokes nothing and succeeds, alike, so logout is idempotent and its answer says nothing about a token; a token past its expiry is no credential, as for refresh (#458). It takes the user's lock (lockUserTx) like rotation does, so a logout and a refresh of the same token run one after the other: whichever comes second sees the other's result, and the session ends either way.

func (*Service) RevokeSession added in v0.8.0

func (s *Service) RevokeSession(ctx context.Context, userID uint, id string) error

RevokeSession ends one of the user's active sessions. It returns ErrSessionNotFound when id names no active session of that user; a session's id does not change when it refreshes, so an id listed before a refresh still ends it. It also returns ErrSessionNotFound when the session's row turns out revoked by the time it is updated, so a success always means this call ended the session (every revocation, logout included, takes the user's lock, so one that ended the session first already left it out of the active sessions). A user that does not exist also yields ErrSessionNotFound. It does not look at the caller's own session, which application code (an admin action revoking another user's session, say) does not have; the route checks the request's (revokeSessionAs).

func (*Service) RotateRefresh

func (s *Service) RotateRefresh(ctx context.Context, raw string) (TokenPair, error)

RotateRefresh validates the current refresh token, revokes it, and issues a new pair. Reuse of an already-rotated token before it expires revokes the user's remaining tokens, unless it comes within the configured RefreshReuseGrace of the rotation while the successor is still live, a lost race that is just invalid (and audited); a token revoked by logout or session revocation, and any expired token, is just invalid. Concurrent callers with the same still-valid token share one rotation so a lost race cannot family-revoke the winner's new session. That rotation runs detached from every caller's cancellation and deadline (s.detach, cancelled only by its own timeout, rotateTimeout, which bounds its transaction, or by Close), and each caller gets its one result: a caller whose client went away cannot fail the others with its cancellation (#462). So RotateRefresh does not return early when ctx is done: every caller, the first included, waits for the shared rotation (its transaction for at most rotateTimeout, then the audit record of a reuse for at most auditTimeout) and gets its result.

func (*Service) SendEmailVerification added in v0.9.0

func (s *Service) SendEmailVerification(ctx context.Context, user User) error

SendEmailVerification issues a new verification token for user's email and mails it. It returns ErrAlreadyVerified for a verified user, an error naming the wait when the previous message went out (or is going out) less than a minute ago, and the Mailer's error (ErrNoMailer when none is configured) when the message could not be sent. The token is pending until the message was delivered, then supersedes the earlier ones (sendOneTimeToken).

func (*Service) UnlinkIdentity added in v0.9.0

func (s *Service) UnlinkIdentity(ctx context.Context, userID, linkID uint) error

UnlinkIdentity removes the user's link linkID: ErrIdentityLinkNotFound unless it is the user's, ErrLastSignInMethod when the account has no password and no other link (it could not sign in again; a password reset gives it one).

func (*Service) VerifyEmail added in v0.9.0

func (s *Service) VerifyEmail(ctx context.Context, raw string) (User, error)

VerifyEmail consumes a verification token and marks the email it was issued for verified. It returns ErrInvalidToken for a token that is unknown, expired, used, superseded, never delivered, or for an address the user no longer has. Concurrent uses of one token: exactly one succeeds.

type SessionLocator added in v0.10.0

type SessionLocator func(ctx context.Context, addr netip.Addr) string

SessionLocator names where a session's sign-in came from, for GET /auth/sessions to show ("Lisbon, PT", say), from the client's full address, whatever config.AuthConfig.SessionClientAddress stores. It runs once per sign-in, in the request, before the session is written: it must be quick (a local GeoIP database, not a network call) and return "" when it does not know. Its answer is stored cut to 128 bytes. The framework ships none: an application that wants locations passes one with WithSessionLocator, and with it the decision to derive them.

type TOTPEnrollment added in v0.9.0

type TOTPEnrollment struct {
	Secret string
	URI    string
}

TOTPEnrollment is what an authenticator app needs: the secret (base32, for typing it in) and the otpauth:// URI (for a QR code).

type TOTPFactor added in v0.9.0

type TOTPFactor struct {
	ID     uint `gorm:"primaryKey"`
	UserID uint `gorm:"uniqueIndex;not null"`
	// Secret is the TOTP key, encrypted (never stored or logged in clear).
	Secret string `gorm:"size:255;not null"`
	// ConfirmedAt is when the enrollment was confirmed; nil while pending.
	ConfirmedAt *time.Time
	// LastStep is the last time step whose code was accepted: no code of
	// it, or of an earlier one, is accepted again.
	LastStep  int64 `gorm:"not null;default:0"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

TOTPFactor is a user's TOTP authenticator: pending (ConfirmedAt nil) from the enrollment until a code from it is confirmed, then enabled.

func (TOTPFactor) TableName added in v0.9.0

func (TOTPFactor) TableName() string

TableName is the factors' table.

type ThrottleError added in v0.9.0

type ThrottleError struct {
	Rule       string
	RetryAfter time.Duration
}

ThrottleError is an attempt refused by Rule, a ThrottlePolicy field's name, until RetryAfter has passed. errors.Is(err, ErrTooManyAttempts).

func (*ThrottleError) Error added in v0.9.0

func (e *ThrottleError) Error() string

func (*ThrottleError) Is added in v0.9.0

func (e *ThrottleError) Is(target error) bool

Is reports ErrTooManyAttempts.

type ThrottleLimit added in v0.9.0

type ThrottleLimit struct {
	Limit  int
	Window time.Duration
}

ThrottleLimit allows Limit attempts in any Window. A zero Limit or Window turns the rule off.

type ThrottlePolicy added in v0.9.0

type ThrottlePolicy struct {
	// LoginPerAccountAddress bounds failed logins for one email from one
	// client address: the guessing of one account's password.
	LoginPerAccountAddress ThrottleLimit
	// LoginPerAddress bounds failed logins from one client address, for any
	// email: credential stuffing. Wide, for many users behind one address.
	LoginPerAddress ThrottleLimit
	// LoginPerAccount bounds failed logins for one email from any address: a
	// guessing spread over many addresses. Anyone can spend it: a handful of
	// addresses failing at their own limit keep it full for as long as they
	// go on, and then every client is refused for the account but the known
	// ones (an address that signed in to it before: KnownClientTTL). A
	// password reset empties it.
	LoginPerAccount ThrottleLimit
	// KnownClientTTL is how long a successful login exempts its client
	// address from LoginPerAccount for that email, renewed by each one.
	// Zero exempts no client.
	KnownClientTTL time.Duration
	// RegisterPerAddress bounds registrations (POST /auth/register) from one
	// client address, every request counted: each one hashes a password and
	// mails a verification message to the address it names.
	RegisterPerAddress ThrottleLimit
	// PasswordResetPerAddress bounds password reset requests (POST
	// /auth/password/forgot) from one client address, whatever the email:
	// mail sent to many addresses. Each address gets one message a minute
	// anyway (the resend wait).
	PasswordResetPerAddress ThrottleLimit
	// TokenPerAddress bounds the invalid one-time tokens (email
	// verification, password reset, email change confirmation) posted from
	// one client address.
	TokenPerAddress ThrottleLimit
	// CurrentPasswordPerUser bounds the wrong current passwords one user
	// gives (password change, email change): the guessing of a password
	// from a stolen session.
	CurrentPasswordPerUser ThrottleLimit
	// MFAPerUser bounds the wrong multi-factor codes one user's account is
	// given (login, enrollment confirmation, disable), from any address. It
	// stays on with AuthConfig.ThrottleDisabled: it is what bounds guessing
	// the code, which a per-address limit in front of the app does not. A
	// replayed code (a login submitted twice) counts as a wrong one.
	MFAPerUser ThrottleLimit
	// VerificationPerUser bounds the verification messages one user is sent,
	// on top of the resend wait (one a minute).
	VerificationPerUser ThrottleLimit
}

ThrottlePolicy holds the credential endpoints' limits. DefaultThrottlePolicy is the framework's; WithThrottlePolicy replaces it.

func DefaultThrottlePolicy added in v0.9.0

func DefaultThrottlePolicy() ThrottlePolicy

DefaultThrottlePolicy returns the framework's limits.

type TokenPair

type TokenPair struct {
	AccessToken  string `json:"access_token" example:"eyJhbGciOiJIUzI1NiJ9..." doc:"Short-lived Bearer access JWT. Hold in memory only."`
	RefreshToken string `json:"refresh_token" example:"aa11..." doc:"Opaque rotating refresh token. Hold in memory only; never web storage."`
	TokenType    string `json:"token_type" example:"Bearer" doc:"Token type; always Bearer"`
	ExpiresIn    int    `json:"expires_in" example:"900" doc:"Access token lifetime in seconds"`
}

TokenPair is the login/refresh success payload (inside D10 data).

type TokenPurpose added in v0.9.0

type TokenPurpose string

TokenPurpose is what a OneTimeToken is for.

const (
	// PurposeVerifyEmail proves the user owns the token's email (AUTH-1).
	PurposeVerifyEmail TokenPurpose = "verify_email"
	// PurposeResetPassword lets the holder set a new password (AUTH-2).
	PurposeResetPassword TokenPurpose = "reset_password"
	// PurposeChangeEmail proves the user owns the new address they asked to
	// change their email to (AUTH-4).
	PurposeChangeEmail TokenPurpose = "change_email"
)
const PurposeExternalLogin TokenPurpose = "external_login"

PurposeExternalLogin is a Bearer-mode external sign-in's exchange code: the callback redirects with it, and POST /auth/external/exchange trades it for the session's tokens (AUTH-10). Never mailed.

type User

type User struct {
	ID           uint   `gorm:"primaryKey"`
	Email        string `gorm:"uniqueIndex;size:255;not null"`
	PasswordHash string `gorm:"not null"`
	IsSuperuser  bool   `gorm:"not null;default:false"`
	// DisabledAt is when the account was disabled (Service.DisableUser);
	// nil while it is active. A disabled user cannot sign in, and no
	// credential issued to it works: its sessions were revoked, its links
	// voided, and every check refuses it.
	DisabledAt *time.Time

	// EmailVerifiedAt is when the user proved they own VerifiedEmail (POST
	// /auth/verify-email); nil while no address is verified. A superuser
	// created by gombit createsuperuser starts verified.
	EmailVerifiedAt *time.Time
	// VerifiedEmail is the address that proof was for. The verification
	// holds only while it is Email: changing Email, by any path (an update
	// through GORM, the admin), makes the user unverified until the new
	// address is proven.
	VerifiedEmail string       `gorm:"size:255;not null;default:''"`
	Groups        []Group      `gorm:"many2many:auth_user_groups;"`
	Permissions   []Permission `gorm:"many2many:auth_user_permissions;"`
	CreatedAt     time.Time
	UpdatedAt     time.Time
	// contains filtered or unexported fields
}

User is the auth identity. IsSuperuser bypasses every permission check; regular users receive permissions directly or through groups.

func UserFromContext

func UserFromContext(ctx context.Context) (User, bool)

UserFromContext returns the authenticated user stored by requireBearer or RequireCookieSession.

func (User) Disabled added in v0.9.0

func (u User) Disabled() bool

Disabled reports whether the account is disabled (DisabledAt).

func (User) EmailVerified added in v0.9.0

func (u User) EmailVerified() bool

EmailVerified reports whether the user has verified their current email: a verification exists, and it is for the address the user has now.

func (User) HasUsablePassword added in v0.9.0

func (u User) HasUsablePassword() bool

HasUsablePassword reports whether the user can sign in with a password: false for an account an external sign-in made, until a password reset sets one.

Directories

Path Synopsis
Package authtest holds test helpers for applications that use the framework's auth: a Mailer that records the account lifecycle's messages instead of sending them, so a test can read the token a flow mailed.
Package authtest holds test helpers for applications that use the framework's auth: a Mailer that records the account lifecycle's messages instead of sending them, so a test can read the token a flow mailed.
Package oidc is an optional auth.IdentityProvider for any OpenID Connect provider (Google, Microsoft Entra ID, Okta, Auth0, Keycloak, ...): the authorization code flow with PKCE, the provider's endpoints and keys from its discovery document, and the ID token verified (signature, issuer, audience, expiry, nonce) before its claims become the auth.ExternalIdentity.
Package oidc is an optional auth.IdentityProvider for any OpenID Connect provider (Google, Microsoft Entra ID, Okta, Auth0, Keycloak, ...): the authorization code flow with PKCE, the provider's endpoints and keys from its discovery document, and the ID token verified (signature, issuer, audience, expiry, nonce) before its claims become the auth.ExternalIdentity.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL