Documentation
¶
Overview ¶
Package iam composes the authentication features of Arkoren into one facade: password login and optional registration, email verification, password reset, two-factor authentication, API and device tokens, sign-in with external providers, connections, permissions and roles, and account deletion, as JSON routes on core's auth.Guard.
The module is dependency-free (core, foundation and the standard library) and split into packages that never import each other; only this root package imports them:
account the users table (email), signed email verification links, the user provider password login, confirm, change, forgot and reset; register when enabled; signed reset links twofactor TOTP and recovery codes apitoken personal and device tokens, the bearer authenticator, scopes and their grant ceiling federation links external identities to users, create on first login when enabled permission roles and permissions assigned to users (core gate definitions), last-holder protection
It never imports ark/oauth: a module boundary is a dependency boundary. The Provider and NativeProvider interfaces are satisfied structurally by *oauthauth.Client.
Wiring ¶
scheme := totp.New("Acme") // the name authenticator apps show for this account
identity, err := iam.New(db, store, func(identity *iam.Builder) {
identity.Queue(dispatcher) // the module's emails are queue jobs
identity.Password(hasher, func(passwords *password.Builder) {
passwords.Registration(true) // off by default
passwords.Reset(signer, mailer, "https://app.example.com/reset-password")
})
identity.Directory(func(accounts *account.Builder) {
accounts.Verification(signer, mailer, "https://app.example.com/verify-email")
})
identity.TwoFactor(scheme, cipher)
identity.Tokens()
identity.Permissions(func(policy *permission.Builder) {
policy.Roles(Viewer, Editor, Admin).KeepOne(Admin)
})
identity.Provider(google)
identity.Provider(github, func(login *iam.ProviderBuilder) {
login.SignUp(true) // off by default, per provider
})
identity.Account(func(view *iam.AccountBuilder) {
view.Permissions(true).TwoFactor(true).Login(true)
})
})
if err != nil {
return err
}
if err := migrator.Add(identity.Migrations()...); err != nil { // every feature, enabled or not
return err
}
if err := identity.RegisterJobs(consumer); err != nil { // in the process that sends the emails
return err
}
web := routes.With(identity.Middleware()) // session, guard and token authenticators
web.Group("/auth", identity.Register)
api := routes.With(identity.Middleware(), auth.Require())
api.Get("/posts", listPosts)
Every feature is off until its method is called, and calling it enables the feature; to follow a configuration flag, wrap the call in an if. A setting that depends on a feature that is off is ignored with one warning logged through slog.Default, and missing components or invalid values still fail New with ErrInvalidConfig. The two ways users appear on their own are off by default too: self-service registration (password.Builder.Registration) and creating a user on a first provider login (ProviderBuilder.SignUp). With both off the application adds users itself, with IAM.Directory (account.Directory.Create, account.Directory.CreateVerified) or its own users. The application brings the database, the cache, a hasher for passwords and a cipher for two-factor secrets; the facade does no I/O at construction, the application runs the migrations, and IAM.Ping is the readiness check.
The default client address is the connection host, ignoring forwarding headers. If a reverse proxy sits in front of the application, configure Builder.ClientIP with a resolver that trusts only that infrastructure. The resolvers in arkoren.dev/core/http/clientip return addresses for login records; the throttles independently group IPv6 addresses into /64 buckets.
Email links ¶
The module queues its own jobs on the application's dispatcher and sends through the application's mailer; it starts no goroutine. Password reset (password.Builder.Reset) and email verification (account.Builder.Verification) each take a signer from core's http/link package, a [mail.Mailer] and the address of the application page the link opens. Builder.Queue gives the module its dispatcher: a registration, a resend or a forgot-password request stores one job from inside the request and returns, and IAM.RegisterJobs registers the handlers that write and send the emails on the consumer of the process that runs the worker. The jobs belong to the module: the application declares no job, handler or send function, and a feature enabled in a later release registers its handler through the same call. The jobs run on the queue QueueName and their names carry the Builder.Instance, so instances share a queue and a consumer without crossing. Enabling Reset or Verification without Builder.Queue fails New with ErrInvalidConfig.
The emails are short plain-text messages with a default subject and wording. password.ResetBuilder.Email and account.VerificationBuilder.Email replace one with the application's own, a function of the message and the page link.
ring, err := key.ParseRing[key.Shared](keyText)
signer, err := link.New(ring, func(links *link.Builder) {
links.Origin("https://app.example.com")
})
identity, err := iam.New(db, store, func(identity *iam.Builder) {
identity.Queue(dispatcher)
identity.Password(hasher, func(passwords *password.Builder) {
passwords.Reset(signer, mailer, "https://app.example.com/reset-password", func(reset *password.ResetBuilder) {
reset.Email(resetEmail) // optional; the default wording otherwise
})
})
})
// in the process that runs the worker:
err = identity.RegisterJobs(consumer)
A link is a signed value bound to the state its action changes, so there are no token tables: a reset link is bound to the user's password hash and stops working once the password changes, a verification link to the user's email and whether it is verified. Both expire. The signed value reaches the front end in the URL fragment; the page reads location.hash and posts it as the token of POST /password/reset or POST /email/verify.
Forgot-password stores its job with the identifier exactly as typed, whether or not the user exists, and answers 202; a dispatch error is a 500. The worker looks the user up. A failing send is retried by the queue, so one request may send more than once, and an email the mailer rejects as malformed fails the job permanently.
IAM.RegisterJobs cannot see a queue restriction on the consumer: one built with queue.ConsumerBuilder.Queues must list QueueName, or stored jobs wait unconsumed. Deploy the workers that register the jobs before enabling a new email feature on the servers that store them.
Routes ¶
IAM.Register registers these, and each has an IAM.XHandler method for custom paths. Bodies and responses are JSON.
Login POST /register (with Registration) · POST /login · POST /login/challenge · GET /login/pending · POST /logout
Step-up POST /confirm
Email POST /email/verify · POST /email/verify/resend
Password POST /password/forgot · POST /password/reset · PUT /password
Two-factor POST /two-factor/setup · POST /two-factor · DELETE /two-factor · POST /two-factor/recovery-codes
Tokens GET /tokens · POST /tokens (personal) · DELETE /tokens/{id} · POST /device-tokens · DELETE /device-tokens/current (device)
Sessions GET /sessions · DELETE /sessions/{id} · DELETE /sessions
Providers GET /<name> · GET|POST /<name>/callback · GET /<name>/nonce · POST /<name>/native
Connections GET /connections · POST /connections/{provider} · DELETE /connections/{id}
Permissions GET /me/permissions (SelfService) · GET /users/{subject}/permissions · PUT|DELETE /users/{subject}/permissions/{name} · PUT|DELETE /users/{subject}/roles/{name} (Management)
Account GET /account (Account) · DELETE /account
Behavior ¶
- A login answers 204 when complete, or 202 {"second_factor": {"methods": [...]}} when the user must also answer a second factor; the client then posts {"method": "...", ...} to /login/challenge. Users pick any enrolled method, listed in registration order.
- Problems carry stable types "tag:arkoren.dev,2026-11:ark/access:<package>:<name>": 422 for a wrong secret or invalid input (core's own challenge and confirm routes answer 403 for a wrong code), 401 for no login or pending state, 403 for step-up, 409 for a conflict, 429 with Retry-After when throttled.
- Every credential-changing handler requires a browser session (auth.Identity.Session) and calls auth.Guard.Fresh; an API token can never enroll, change or remove a credential. A user with no step-up method is fresh right after logging in, so a first enrollment needs nothing special.
- Password login counts only failures, per identifier and client address together (10), per identifier across addresses (50) and per client address (100) in 15 minutes, so someone failing from elsewhere cannot lock a user out; an unknown identifier costs a dummy hash. Forgot-password, register and resend are throttled per identifier and per address too.
- Register, when enabled, answers an empty 202 and logs nobody in, whether or not the address was taken; for a taken one it creates nothing. With the built-in users (which need password.Builder.Reset for registration) and Verification it stores the same work on both paths: a verification job for a new address and a reset notice job for the owner of a taken one; with only Reset it stores nothing. A failed dispatch is logged. It runs within the registration throttle.
- Every POST, PUT and PATCH route requires the media type application/json (415 otherwise, even without a body), which stops cross-site HTML forms. It is core's contenttype middleware, applied inside each handler so it also holds on custom paths; DELETE routes are not checked. It is not CSRF protection: mount core's csrf.Middleware next to IAM.Middleware.
- Forgot-password and resend answer an empty 202 once their work is stored, so neither the answer nor its timing says whether the user exists. Mail goes to the address stored with the user, never to the text of the request.
- A password change keeps the caller, ends the user's other logins and revokes all their tokens, personal ones too (only device tokens with Builder.KeepPersonalTokens); enabling two-factor does the same; a reset rotates the user, which ends every session, pending login and API token, and never logs the user in. Of two concurrent submits of one reset link exactly one succeeds.
- A completed reset proves the mailbox. When the email was unverified it is marked verified and every connection, the authenticator, the recovery codes and all tokens are deleted, because whoever registered the address first may have attached them. Until verified, an account cannot connect a provider, enroll two-factor or create tokens (403 email-unverified).
- Enabling two-factor ends the user's other logins. Disabling it and regenerating recovery codes need a recent authenticator or recovery code; a fresh password alone is 403 with methods ["otp"], and a recovery code used within the step-up window also counts as the fresh login.
- A token's scopes are capped by what apitoken.Builder.Grants lets the user hold: at issue (403 scope-not-granted) and again on every request, or within apitoken.Builder.GrantTTL of a change. With Builder.Permissions the cap is the user's permissions from the store, and its catalog the store's permission names, unless a Grants call in Builder.Tokens replaces both.
- With Builder.Permissions the guard loads the user's expanded roles and permissions on every authenticated session request (permission.Store.Load), so core's gate.HasPermission and gate.HasRole work on sessions; a token carries its scopes and never roles. Sessions then pass scope and permission rules, so mount csrf.Middleware on every route a session can reach. The management routes need a fresh browser session holding permission.Builder.Management, and a caller can grant or revoke only what they hold (403 not-grantable); the last holder of a permission.Builder.KeepOne role cannot lose it (409 last-holder).
- A first login with an unknown provider identity creates no user unless ProviderBuilder.SignUp is on for that provider (403 no-account), and then only when the provider proved an email (403 email-unverified).
- Federation never links by email, with one exception: an identity whose email the provider verified takes over the user who holds that email and never verified it, with or without sign-up. In one transaction the password, connections, authenticator, recovery codes and tokens are deleted, the email is marked verified, the user is rotated (ending the registrant's sessions and, after the commit, their login records), the identity is linked, federation.AccountClaimed is published and the owner is logged in. A verified or disabled user is never taken over. Connecting a provider is a POST that leaves a ten-minute, single-use intent in the session. A user cannot remove their last way to log in (409).
- Email verification never blocks login; protect routes with IAM.RequireVerified, which also works with UsersBuilder.Verification.
- Device tokens unused past their idle limit, expired tokens and tokens a version change of the user ended are deleted by IAM.Prune, which you schedule (it is func(context.Context) error); the token list already hides the ended ones.
- A password reset of a user whose email was already verified does not delete their provider connections: only the reset of an unverified account purges (see above). Someone who held the old password could have connected a provider of their own, so review the connections after a reset, for example from a listener of password.WasReset that lists or removes them with IAM.Links, and from one of federation.AccountClaimed.
- Events carry subjects only (see each package) on Builder.Events.
Your own users ¶
Builder.Users replaces the built-in users table (identified by email) with the application's: a provider plus Lookup, Create and Rotate functions. No users table is migrated, and the routes and handlers that need the directory (email verification, account deletion) are absent or panic at composition, and IAM.RequireVerified needs UsersBuilder.Verification. The other packages work unchanged, because they only see subjects. Lookup returns the stored address mail goes to, Create gets whether the provider verified the email and must fail on an existing identifier, and the unverified-account rules above apply only when you give UsersBuilder.Verification; without it the application must enforce the same rules itself. Registration and sign-up with a provider stay off until password.Builder.Registration and ProviderBuilder.SignUp are enabled, and each needs UsersBuilder.Create; New fails without it. The application adds its own users in its own store, and Builder.Directory, which configures the built-in table, cannot be combined with Users.
Transactions and limits ¶
Every package assumes the one database.Database passed to New: writes that span packages join the transaction carried by the context, and account deletion removes every package's rows together. Store subjects as bytewise text in your own tables ([schema.Column.Bytewise]), because database default collations compare case-insensitively.
The facade owns both the session middleware and the guard and keeps them on one lifetime (Builder.SessionLifetime) and on the default session handle, which the provider handlers of ark/oauth require.
Index ¶
- Constants
- Variables
- func AccountOperation(operation *router.OperationBuilder)
- func ChallengeOperation(operation *router.OperationBuilder)
- func ConfirmOperation(operation *router.OperationBuilder)
- func DeleteAccountOperation(operation *router.OperationBuilder)
- func DeleteOtherSessionsOperation(operation *router.OperationBuilder)
- func DeleteSessionOperation(operation *router.OperationBuilder)
- func ListSessionsOperation(operation *router.OperationBuilder)
- func LogoutOperation(operation *router.OperationBuilder)
- func PendingOperation(operation *router.OperationBuilder)
- func ProviderCallbackOperation(operation *router.OperationBuilder)
- func ProviderLoginOperation(operation *router.OperationBuilder)
- func ProviderNativeOperation(operation *router.OperationBuilder)
- func ProviderNonceOperation(operation *router.OperationBuilder)
- type AccountBuilder
- type AccountBuilderFunc
- type AccountLogin
- type AccountView
- type Builder
- func (identity *Builder) Account(configure ...AccountBuilderFunc) *Builder
- func (identity *Builder) Authenticator(authenticators ...auth.Authenticator) *Builder
- func (identity *Builder) ClientIP(clientIP func(*http.Request) string) *Builder
- func (identity *Builder) Directory(configure ...account.BuilderFunc) *Builder
- func (identity *Builder) Events(bus *event.Bus) *Builder
- func (identity *Builder) Guard(configure ...auth.GuardBuilderFunc) *Builder
- func (identity *Builder) Instance(name string) *Builder
- func (identity *Builder) KeepPersonalTokens() *Builder
- func (identity *Builder) OnEmailProven(hook func(ctx context.Context, subject string) error) *Builder
- func (identity *Builder) Password(hasher *hash.Hasher, configure ...password.BuilderFunc) *Builder
- func (identity *Builder) Permissions(configure ...permission.BuilderFunc) *Builder
- func (identity *Builder) Provider(provider Provider, configure ...ProviderBuilderFunc) *Builder
- func (identity *Builder) Queue(dispatcher *queue.Dispatcher) *Builder
- func (identity *Builder) SecondFactor(credentials ...auth.Credential) *Builder
- func (identity *Builder) Session(configure ...session.BuilderFunc) *Builder
- func (identity *Builder) SessionLifetime(lifetime time.Duration) *Builder
- func (identity *Builder) StepUp(credentials ...auth.Credential) *Builder
- func (identity *Builder) Tokens(configure ...apitoken.BuilderFunc) *Builder
- func (identity *Builder) TwoFactor(scheme totp.Scheme, cipher *crypto.Encrypter, ...) *Builder
- func (identity *Builder) Users(provider *auth.UserProvider, configure ...UsersBuilderFunc) *Builder
- type BuilderFunc
- type IAM
- func (identity *IAM) Account(ctx context.Context) (AccountView, error)
- func (identity *IAM) AccountHandler() router.Handler
- func (identity *IAM) ChallengeHandler() router.Handler
- func (identity *IAM) ChangePasswordHandler() router.Handler
- func (identity *IAM) ConfirmHandler() router.Handler
- func (identity *IAM) ConnectHandler() router.Handler
- func (identity *IAM) CreateTokenHandler() router.Handler
- func (identity *IAM) DeleteAccountHandler() router.Handler
- func (identity *IAM) DeleteConnectionHandler() router.Handler
- func (identity *IAM) DeleteDeviceTokenHandler() router.Handler
- func (identity *IAM) DeleteOtherSessionsHandler() router.Handler
- func (identity *IAM) DeleteSessionHandler() router.Handler
- func (identity *IAM) DeleteTokenHandler() router.Handler
- func (identity *IAM) Directory() *account.Directory
- func (identity *IAM) DisableTwoFactorHandler() router.Handler
- func (identity *IAM) EnableTwoFactorHandler() router.Handler
- func (identity *IAM) ExchangeHandler() router.Handler
- func (identity *IAM) Factors() *twofactor.Factors
- func (identity *IAM) ForgotPasswordHandler() router.Handler
- func (identity *IAM) Grant(ctx context.Context, subject string, granted gate.Permission) error
- func (identity *IAM) GrantPermissionHandler() router.Handler
- func (identity *IAM) GrantRole(ctx context.Context, subject string, role gate.Role) error
- func (identity *IAM) GrantRoleHandler() router.Handler
- func (identity *IAM) Guard() *auth.Guard
- func (identity *IAM) HasAnyPermission(ctx context.Context, subject string, permissions ...gate.Permission) (bool, error)
- func (identity *IAM) HasAnyRole(ctx context.Context, subject string, roles ...gate.Role) (bool, error)
- func (identity *IAM) HasPermission(ctx context.Context, subject string, required ...gate.Permission) (bool, error)
- func (identity *IAM) HasRole(ctx context.Context, subject string, required ...gate.Role) (bool, error)
- func (identity *IAM) Issuer() *apitoken.Issuer
- func (identity *IAM) Links() *federation.Links
- func (identity *IAM) ListConnectionsHandler() router.Handler
- func (identity *IAM) ListSessionsHandler() router.Handler
- func (identity *IAM) ListTokensHandler() router.Handler
- func (identity *IAM) LoginHandler() router.Handler
- func (identity *IAM) LogoutHandler() router.Handler
- func (identity *IAM) Middleware() router.Middleware
- func (identity *IAM) Migrations() []migrate.Definition
- func (identity *IAM) MustAccept(methods ...auth.Method)
- func (identity *IAM) PendingHandler() router.Handler
- func (identity *IAM) Permissions() *permission.Store
- func (identity *IAM) Ping(ctx context.Context) error
- func (identity *IAM) Prune(ctx context.Context) error
- func (identity *IAM) RecoveryCodesHandler() router.Handler
- func (identity *IAM) Register(r *router.Router)
- func (identity *IAM) RegisterHandler() router.Handler
- func (identity *IAM) RegisterJobs(consumer *queue.Consumer) error
- func (identity *IAM) RequireVerified() router.Middleware
- func (identity *IAM) ResendVerificationHandler() router.Handler
- func (identity *IAM) ResetPasswordHandler() router.Handler
- func (identity *IAM) Resolve(ctx context.Context, external auth.External) (string, error)
- func (identity *IAM) Revoke(ctx context.Context, subject string, revoked gate.Permission) error
- func (identity *IAM) RevokePermissionHandler() router.Handler
- func (identity *IAM) RevokeRole(ctx context.Context, subject string, role gate.Role) error
- func (identity *IAM) RevokeRoleHandler() router.Handler
- func (identity *IAM) SelfPermissionsHandler() router.Handler
- func (identity *IAM) SetupTwoFactorHandler() router.Handler
- func (identity *IAM) UserPermissionsHandler() router.Handler
- func (identity *IAM) UserProvider() *auth.UserProvider
- func (identity *IAM) Verifier() *password.Verifier
- func (identity *IAM) VerifyEmailHandler() router.Handler
- type NativeProvider
- type Provider
- type ProviderBuilder
- type ProviderBuilderFunc
- type UsersBuilder
- func (users *UsersBuilder) Create(...) *UsersBuilder
- func (users *UsersBuilder) Lookup(...) *UsersBuilder
- func (users *UsersBuilder) Rotate(rotate func(ctx context.Context, subject string) error) *UsersBuilder
- func (users *UsersBuilder) Verification(verified func(ctx context.Context, subject string) (bool, error), ...) *UsersBuilder
- type UsersBuilderFunc
Constants ¶
const QueueName = storage.Queue
QueueName is the name of the queue every job of the module runs on. A consumer that restricts its queues with queue.ConsumerBuilder.Queues must include it, or the emails of password.Builder.Reset and account.Builder.Verification are stored and never sent.
Example:
consumer := queue.NewConsumer(driver, func(consumer *queue.ConsumerBuilder) {
consumer.Queues("emails", iam.QueueName)
})
Variables ¶
var ErrIdentifierTaken = password.ErrIdentifierTaken
ErrIdentifierTaken is what UsersBuilder.Create returns, or wraps, for an identifier that already belongs to a user. Registration then answers 202 like for a new user and notifies the owner. It is password.ErrIdentifierTaken.
Example:
create := func(ctx context.Context, identifier string, verified bool) (string, error) {
if exists(identifier) {
return "", iam.ErrIdentifierTaken
}
return insert(ctx, identifier, verified)
}
var ErrInvalidConfig = errors.New("access: invalid configuration")
ErrInvalidConfig is wrapped by the errors of New for an unusable configuration: a missing dependency (database, store or client address source), a duplicate provider name, an invalid instance or scheme, an enabled feature without its required components (a nil hasher or two-factor cipher, or password.Builder.Reset or account.Builder.Verification without a signer, a mailer, a page address or Builder.Queue), Builder.Directory combined with Builder.Users, or a failing package constructor (tokens with no kind enabled, a scope catalog without a grant function, an invalid or conflicting permission definition). A setting whose dependency is off is not an error: registration without users that can be created or, with the built-in users, without password.Builder.Reset, and sign-up without users that can be created, are ignored with one warning logged through slog.Default naming the setting.
Example:
_, err := iam.New(nil, nil) fmt.Println(errors.Is(err, iam.ErrInvalidConfig)) // true
var ErrNotMigrated = storage.ErrNotMigrated
ErrNotMigrated is returned by IAM.Ping when the tables of an enabled feature do not exist. Add IAM.Migrations to the application's migrator and run them.
Example:
if errors.Is(identity.Ping(ctx), iam.ErrNotMigrated) {
// run the migrator
}
Functions ¶
func AccountOperation ¶ added in v0.6.0
func AccountOperation(operation *router.OperationBuilder)
AccountOperation describes IAM.AccountHandler. It answers 200 with the AccountView of the request, for a session cookie or a token alike; a request without an identity, including a login still waiting for its second factor, is 401.
Example:
web.Get("/account", identity.AccountHandler(), iam.AccountOperation)
func ChallengeOperation ¶ added in v0.6.0
func ChallengeOperation(operation *router.OperationBuilder)
ChallengeOperation describes IAM.ChallengeHandler, which finishes a parked login with one second-factor credential: the body names the method and carries its input, and success is 204 with the re-issued session cookie. A wrong code or a method the user is not enrolled in is 403, an unknown method 422, and used-up attempts or no pending login 401.
Example:
web.Post("/login/challenge", identity.ChallengeHandler(), iam.ChallengeOperation)
func ConfirmOperation ¶ added in v0.6.0
func ConfirmOperation(operation *router.OperationBuilder)
ConfirmOperation describes IAM.ConfirmHandler, which re-proves a logged-in user with a step-up method. It needs a browser session identity (a bearer token never confirms); success is 204 with the re-issued session cookie, and a wrong code, a method the user is not enrolled in or a lockout is 403.
Example:
web.Post("/confirm", identity.ConfirmHandler(), iam.ConfirmOperation)
func DeleteAccountOperation ¶ added in v0.6.0
func DeleteAccountOperation(operation *router.OperationBuilder)
DeleteAccountOperation describes IAM.DeleteAccountHandler. It needs a browser session and a fresh login and answers 204 after removing the user and every package's rows in one transaction; the session ends, so the cookie is cleared.
Example:
web.Delete("/account", identity.DeleteAccountHandler(), iam.DeleteAccountOperation)
func DeleteOtherSessionsOperation ¶ added in v0.6.0
func DeleteOtherSessionsOperation(operation *router.OperationBuilder)
DeleteOtherSessionsOperation describes IAM.DeleteOtherSessionsHandler. It needs a browser session and answers 204 after ending every login of the user except the request's own.
Example:
web.Delete("/sessions", identity.DeleteOtherSessionsHandler(), iam.DeleteOtherSessionsOperation)
func DeleteSessionOperation ¶ added in v0.6.0
func DeleteSessionOperation(operation *router.OperationBuilder)
DeleteSessionOperation describes IAM.DeleteSessionHandler. It needs a browser session and answers 204 after ending the login with that ID; an unknown ID changes nothing.
Example:
web.Delete("/sessions/{id}", identity.DeleteSessionHandler(), iam.DeleteSessionOperation)
func ListSessionsOperation ¶ added in v0.6.0
func ListSessionsOperation(operation *router.OperationBuilder)
ListSessionsOperation describes IAM.ListSessionsHandler. It needs a browser session and answers 200 with the user's logins, the request's own marked current.
Example:
web.Get("/sessions", identity.ListSessionsHandler(), iam.ListSessionsOperation)
func LogoutOperation ¶ added in v0.6.0
func LogoutOperation(operation *router.OperationBuilder)
LogoutOperation describes IAM.LogoutHandler. It ends the logged-in session, its login record and any pending login, regenerates the session ID and answers 204 with the re-issued session cookie. Logging out an anonymous session also succeeds, so no 401 is declared. Like every state-changing route of the module it needs Content-Type application/json (415 otherwise) and belongs behind CSRF protection.
Example:
web.Post("/logout", identity.LogoutHandler(), iam.LogoutOperation)
func PendingOperation ¶ added in v0.6.0
func PendingOperation(operation *router.OperationBuilder)
PendingOperation describes IAM.PendingHandler. The 200 body lists the second-factor methods of the parked login without naming its subject; a request without a pending login, or one locked out of the second factor, is 401. It spends no attempt.
Example:
web.Get("/login/pending", identity.PendingHandler(), iam.PendingOperation)
func ProviderCallbackOperation ¶ added in v0.6.0
func ProviderCallbackOperation(operation *router.OperationBuilder)
ProviderCallbackOperation describes Provider.CallbackHandler at "/<name>/callback", registered for GET and POST. It verifies the provider's answer, begins the login on the guard and redirects (302) to the return target, or to the challenge page when a second factor is required. It carries no operation ID because one registration covers both methods.
Example:
web.Methods([]string{http.MethodGet, http.MethodPost}, "/auth/google/callback",
google.CallbackHandler(guard, resolve), iam.ProviderCallbackOperation)
func ProviderLoginOperation ¶ added in v0.6.0
func ProviderLoginOperation(operation *router.OperationBuilder)
ProviderLoginOperation describes Provider.LoginHandler at "/<name>": it needs no identity, redirects (302) to the provider and remembers the optional local return_to target in a sealed cookie. The query parameter fresh=1 asks the provider to authenticate the user again.
Example:
web.Get("/auth/google", google.LoginHandler(), iam.ProviderLoginOperation)
func ProviderNativeOperation ¶ added in v0.6.0
func ProviderNativeOperation(operation *router.OperationBuilder)
ProviderNativeOperation describes NativeProvider.NativeHandler at "/<name>/native". The body carries the app's ID token, which is verified against the nonce of the session; a complete login is 204 and a parked one 202 with the second-factor methods, both with the session cookie.
Example:
web.Post("/auth/google/native", google.NativeHandler(guard, resolve), iam.ProviderNativeOperation)
func ProviderNonceOperation ¶ added in v0.6.0
func ProviderNonceOperation(operation *router.OperationBuilder)
ProviderNonceOperation describes NativeProvider.NonceHandler at "/<name>/nonce". It needs the session cookie and answers 200 with the single-use nonce the mobile app puts in its ID token request; the answer is not cacheable.
Example:
web.Get("/auth/google/nonce", google.NonceHandler(), iam.ProviderNonceOperation)
Types ¶
type AccountBuilder ¶ added in v0.4.0
type AccountBuilder struct {
// contains filtered or unexported fields
}
AccountBuilder configures the optional members of GET /account in a Builder.Account call. The subject and the email facts of the user are always part of the answer; every other member is off until its method turns it on, so the response shows only what the application chose to publish. Callbacks run directly once, in order, on one fresh draft and methods return the same draft.
Example:
identity.Account(func(view *iam.AccountBuilder) {
view.Permissions(true).TwoFactor(true).Login(true)
})
func (*AccountBuilder) Login ¶ added in v0.4.0
func (view *AccountBuilder) Login(enabled bool) *AccountBuilder
Login turns the "login" member on or off: how the request authenticated, as {"session": bool, "level": "none"|"single"|"multi", "methods": [...]}. session is false for a request that carries a token, and such an identity has no factors, so its level is "none" and its methods empty. methods lists the core factor codes ("pwd", "otp", "hwk", "swk") in the order they were verified; factors a module names itself, such as a recovery code or a federated login, count toward the level but are not listed.
Example:
view.Login(true)
func (*AccountBuilder) Permissions ¶ added in v0.4.0
func (view *AccountBuilder) Permissions(enabled bool) *AccountBuilder
Permissions turns the "roles" and "permissions" members on or off: the roles on the request's identity and the identity's scopes that the permission store defines, as permission.Store.SelfHandler answers them. Both are lists, empty ones as [] and never null. It needs Builder.Permissions: without it New ignores the setting with one warning.
Example:
view.Permissions(true)
func (*AccountBuilder) TwoFactor ¶ added in v0.4.0
func (view *AccountBuilder) TwoFactor(enabled bool) *AccountBuilder
TwoFactor turns the "two_factor" member on or off: whether the user has a confirmed authenticator. It costs one lookup per call. It needs Builder.TwoFactor: without it New ignores the setting with one warning.
Example:
view.TwoFactor(true)
type AccountBuilderFunc ¶ added in v0.4.0
type AccountBuilderFunc = func(*AccountBuilder)
AccountBuilderFunc is the callback form of AccountBuilder.
Example:
var describe iam.AccountBuilderFunc = func(view *iam.AccountBuilder) {
view.Login(true)
}
identity.Account(describe)
type AccountLogin ¶ added in v0.4.0
type AccountLogin struct {
// Session is true for a browser session and false for a token.
Session bool `json:"session"`
// Level is "none", "single" or "multi", from [auth.Identity.Level].
Level string `json:"level"`
// Methods are the core factor codes of the identity, without repeats. It is
// never nil, so it encodes as [] when empty.
Methods []string `json:"methods"`
}
AccountLogin is the "login" member of AccountView.
type AccountView ¶ added in v0.4.0
type AccountView struct {
// Subject is the user's subject.
Subject string `json:"subject"`
// Email is the "email" claim of the user record, left out when absent.
Email string `json:"email,omitzero"`
// EmailVerified is the "email_verified" claim of the user record, left out
// when the record carries none.
EmailVerified *bool `json:"email_verified,omitzero"`
// VerifiedAt is when a built-in user proved the email, left out for
// unverified users and for the application's own users.
VerifiedAt time.Time `json:"verified_at,omitzero"`
// CreatedAt is when a built-in user was created, left out for the
// application's own users.
CreatedAt time.Time `json:"created_at,omitzero"`
// TwoFactor tells whether an authenticator is confirmed, with
// [AccountBuilder.TwoFactor]; nil leaves it out.
TwoFactor *bool `json:"two_factor,omitzero"`
// Login describes how the request authenticated, with
// [AccountBuilder.Login]; nil leaves it out.
Login *AccountLogin `json:"login,omitzero"`
// Roles are the identity's roles with [AccountBuilder.Permissions]. An
// enabled and empty list is non-nil and encodes as []; a disabled one is
// nil and omitted. Keep the two apart: json/v2 encodes a nil slice as [],
// so the omission rests on omitzero.
Roles []string `json:"roles,omitzero"`
// Permissions are the identity's defined permissions with
// [AccountBuilder.Permissions], with the same nil and empty rules as Roles.
Permissions []string `json:"permissions,omitzero"`
}
AccountView is what GET /account answers and IAM.Account returns: facts about the authenticated user that the facade knows. It never holds the application's own user value, because IAM encodes no application data; an application that wants a profile builds its own route from IAM.Account and its own user (see IAM.Account). Members that are nil, zero or empty are omitted from the JSON, so each optional member appears only when it is on.
Example:
view, err := identity.Account(ctx)
if err != nil {
return err
}
fmt.Println(view.Subject, view.Email)
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder configures New before publication. Each feature is off until its method is called: Builder.Password, Builder.TwoFactor, Builder.Tokens, Builder.Permissions, Builder.Provider and Builder.Account enable what they configure, so the call site states what is on. To follow a configuration flag, wrap the call in an if; the callbacks of a method that is never called never run. So are the two ways new users appear on their own: self-service registration (password.Builder.Registration) and sign-up with a provider (ProviderBuilder.SignUp). Until one is enabled the application adds users itself, through IAM.Directory or its own users. Callbacks run directly once, in order, on one fresh draft; methods return the same draft, and retaining it cannot change a published IAM.
Settings that hold hooks and lists add up across calls (Builder.OnEmailProven, Builder.Directory, Builder.Provider, Builder.SecondFactor, Builder.StepUp, Builder.Authenticator, Builder.Guard and Builder.Session); a nil hook never clears an earlier one. Builder.Password, Builder.TwoFactor, Builder.Tokens, Builder.Permissions and Builder.Account replace their earlier call as a whole instead, so the last call is the complete configuration of that feature.
Example:
scheme := totp.New("Acme") // the name authenticator apps show for this account
identity, err := iam.New(db, store, func(identity *iam.Builder) {
identity.Password(hasher)
identity.TwoFactor(scheme, cipher)
identity.Tokens()
identity.Provider(google)
identity.Provider(github, func(login *iam.ProviderBuilder) {
login.SignUp(true)
})
})
func (*Builder) Account ¶ added in v0.4.0
func (identity *Builder) Account(configure ...AccountBuilderFunc) *Builder
Account turns GET /account on: the facts the facade knows about the authenticated user as JSON, the subject and the email facts and, as configure chooses, the roles and permissions, the two-factor state and how the request logged in (see AccountBuilder and AccountView). Without the call no route is mounted and IAM.AccountHandler panics; IAM.Account still answers with the subject and the email facts. Later calls replace the earlier one: only the configure callbacks of the last call count. Settings that depend on a feature that is off (permissions without Builder.Permissions, two-factor without Builder.TwoFactor) are ignored with one warning.
Example:
identity.Account(func(view *iam.AccountBuilder) {
view.Permissions(true)
view.TwoFactor(true)
view.Login(true)
})
func (*Builder) Authenticator ¶
func (identity *Builder) Authenticator(authenticators ...auth.Authenticator) *Builder
Authenticator adds authenticators after the guard's and the token issuer's, for example one that verifies JWTs, to the chain of IAM.Middleware.
Example:
identity.Authenticator(auth.Bearer(verifyJWT))
func (*Builder) ClientIP ¶
ClientIP selects the address used by login records and all facade throttles. By default, IAM uses the connection host and ignores forwarding headers. Calls replace earlier selections; a final nil makes New return ErrInvalidConfig. The function and its captures remain shared after construction. Return an address without its port; throttles apply IPv6 /64 grouping independently. Trust forwarded headers only from explicitly trusted proxies, for example with arkoren.dev/core/http/clientip.
Example:
identity, err := iam.New(db, store, func(identity *iam.Builder) {
identity.ClientIP(clientip.Cloudflare())
identity.Password(hasher)
})
func (*Builder) Directory ¶
func (identity *Builder) Directory(configure ...account.BuilderFunc) *Builder
Directory configures the built-in users table: email verification (account.Builder.Verification) and the lifetime of its links (account.Builder.VerifyTTL). The callbacks run after the facade's own settings (the instance and the events), which they should leave alone. It cannot be combined with Builder.Users, which replaces the built-in table: New then fails with ErrInvalidConfig.
Example:
identity.Directory(func(accounts *account.Builder) {
accounts.Verification(signer, mailer, "https://app.example.com/verify-email").VerifyTTL(time.Hour)
})
func (*Builder) Events ¶
Events publishes the events of every package on bus: account, password, two-factor, token and connection changes, and the core auth.CredentialEnrolled. Events carry subjects only, never tokens, codes or email addresses. A nil bus publishes nothing. The guard publishes auth.SecondFactorLocked on it too, for your own listeners; the facade never depends on events, because a failing listener must not change a decision.
Example:
identity.Events(events)
func (*Builder) Guard ¶
func (identity *Builder) Guard(configure ...auth.GuardBuilderFunc) *Builder
Guard customizes the auth.Guard the facade builds (the step-up window, the attempt limit, the login limit). The callbacks run first and the facade's own settings after them, so the facade wins: the session lifetime (Builder.SessionLifetime), the session handle (always the default one, which the provider handlers of ark/oauth use), the client address source set by Builder.ClientIP and, with Builder.Permissions, the grants loader (auth.GuardBuilder.Grants) replace whatever the callbacks chose. Without Builder.Permissions a callback may set its own Grants. The event bus of Builder.Events is set before the callbacks and not asserted again, because nothing in the facade depends on it: a callback may replace it, for example to send the guard's events elsewhere. The credential registries only append: register second-factor and step-up credentials with Builder.SecondFactor and Builder.StepUp, not here. A credential registered here would be listed to users before the built-in ones, and a method the facade also registers makes New fail with ErrInvalidConfig as a duplicate.
Example:
identity.Guard(func(policy *auth.GuardBuilder) {
policy.FreshFor(5 * time.Minute)
})
func (*Builder) Instance ¶
Instance selects a named instance for every package: tables are prefixed "<instance>_" and migration groups gain ":<instance>", so two facades can share one database. The name is 1 to 20 bytes of [a-z0-9_] starting with a letter; the default is the empty instance.
Example:
identity.Instance("tenant_a")
func (*Builder) KeepPersonalTokens ¶
KeepPersonalTokens limits what a password change and enabling two-factor revoke to the user's device tokens. By default both revoke every token, personal ones included: someone who stole the password can log in and create a personal token, and a user who then changes the password, or protects the account with two-factor, would otherwise leave that token working. Keep personal tokens only when your users rely on long-lived tokens for scripts and integrations and you accept that trade-off; they can still revoke them one by one. It has no effect without Builder.Tokens enabled. A password reset always revokes every token, whatever this says.
Example:
identity.KeepPersonalTokens()
func (*Builder) OnEmailProven ¶
func (identity *Builder) OnEmailProven(hook func(ctx context.Context, subject string) error) *Builder
OnEmailProven adds a function that runs when a completed password reset, or a provider login that verified the email of an unverified user and took the account over, proved the mailbox of a user whose email was not verified. It runs in that transaction and after the built-in purge of connections, authenticator, recovery codes and tokens. Use it to delete what the application or a module registered through Builder.SecondFactor or Builder.StepUp (passkeys, say) may have attached in the meantime; the facade cannot know of them. An error rolls the reset or the login back. It does not run when the email was already verified. Calls add up: the functions run in the order added, all of them even when one fails (the errors are joined), and a nil hook changes nothing.
Example:
identity.OnEmailProven(passkeys.RemoveAll)
func (*Builder) Password ¶
Password turns login, password confirmation and change on, hashing with hasher. A nil hasher makes New fail with ErrInvalidConfig. Registration and forgotten-password recovery are not part of it: enable them with password.Builder.Registration and password.Builder.Reset in configure (the facade then mounts the forgot and reset routes), or add users some other way (see IAM.Directory). Later calls replace the earlier one: the last hasher and configure callbacks are all that count, so compose the settings into one call. configure customizes the password package (the policy, the reset lifetime, registration); the facade has already set the instance, the events and the client address. While a user is in a second-factor lockout (auth.Guard.LockedOut), a correct password of that user is not refunded by the login throttle, so starting pending logins that cannot finish keeps costing throttle budget. The login asks the guard, so it needs no bus and fails closed if the lockout cannot be read.
Example:
identity.Password(hasher, func(passwords *password.Builder) {
passwords.Registration(true).Reset(signer, mailer, "https://app.example.com/reset-password")
})
func (*Builder) Permissions ¶
func (identity *Builder) Permissions(configure ...permission.BuilderFunc) *Builder
Permissions turns the permission store of the permission package on: roles and permissions assigned to users, built on the core gate definitions. configure defines them (permission.Builder.Roles, permission.Builder.Define) and sets permission.Builder.KeepOne, permission.Builder.CacheTTL and the opt-in routes (permission.Builder.SelfService, permission.Builder.Management); the facade sets the instance and the event bus first. Later calls replace the earlier one: only the configure callbacks of the last call count.
With the store enabled the facade wires it in two places:
- the guard calls permission.Store.Load on every authenticated session request (auth.GuardBuilder.Grants), so session identities carry the user's expanded roles and permissions for gate.HasPermission and gate.HasRole; this setting comes after Builder.Guard callbacks, so they cannot replace it;
- with Builder.Tokens, the token ceiling becomes apitoken.Builder.Grants(store.Permissions, store.Catalog()...), set before the Builder.Tokens callbacks, so a token never carries more than its owner holds. A Grants call in those callbacks replaces it, and with it this ceiling. A positive apitoken.Builder.GrantTTL caches the ceiling on top of permission.Builder.CacheTTL, so a revoke can take both lifetimes to reach a token: keep GrantTTL at zero, the default, and cache in the store.
Sessions then carry scopes and pass scope and permission rules, so every route a session cookie can reach needs CSRF protection.
Example:
identity.Permissions(func(policy *permission.Builder) {
policy.Roles(Viewer, Editor, Admin).KeepOne(Admin)
})
func (*Builder) Provider ¶
func (identity *Builder) Provider(provider Provider, configure ...ProviderBuilderFunc) *Builder
Provider adds an external identity provider and its settings. It is mounted under its Provider.Name, and the facade maps its verified identities to users with the one connection store the providers share (`federation.Links`), so the application writes no resolve function. Configure each provider in its own call, with callbacks that run directly once, in order, on one fresh ProviderBuilder; a name used by two calls makes New fail with ErrInvalidConfig. By default a provider only logs in people the application already has: see ProviderBuilder.SignUp. To follow a configuration flag, wrap the call in an if.
Example:
identity.Provider(google)
if cfg.Entra {
identity.Provider(entra, func(login *iam.ProviderBuilder) {
login.SignUp(true)
})
}
func (*Builder) Queue ¶ added in v0.5.0
func (identity *Builder) Queue(dispatcher *queue.Dispatcher) *Builder
Queue sets the dispatcher on which the module stores its background work, the emails of password.Builder.Reset and account.Builder.Verification. The module owns those jobs: it stores them on this dispatcher from the request and sends the emails, through the mailer given to Reset and Verification, in the worker that runs IAM.RegisterJobs. Enabling Reset or Verification without Queue makes New fail with ErrInvalidConfig. A nil dispatcher is the same as no call. The jobs run on the queue QueueName; a consumer restricted with queue.ConsumerBuilder.Queues must list it.
Example:
identity.Queue(dispatcher)
func (*Builder) SecondFactor ¶
func (identity *Builder) SecondFactor(credentials ...auth.Credential) *Builder
SecondFactor registers more second-factor credentials after the built-in ones, for third-party modules such as a passkey package. Methods are listed to users in registration order.
Example:
identity.SecondFactor(passkeys.Credential())
func (*Builder) Session ¶
func (identity *Builder) Session(configure ...session.BuilderFunc) *Builder
Session customizes the session middleware that IAM.Middleware installs (cookie name, domain, renewal). The callbacks run first and the facade's settings after them, so the maximum lifetime (Builder.SessionLifetime) and the default handle, which the guard and the provider handlers of ark/oauth use, replace whatever the callbacks chose.
Example:
identity.Session(func(cookies *session.Builder) {
cookies.Name("app_session")
})
func (*Builder) SessionLifetime ¶
SessionLifetime sets the absolute lifetime of a login once, for the session middleware and the guard together; they must agree or login records would outlive or undercut their sessions. The default is 24 hours.
Example:
identity.SessionLifetime(7 * 24 * time.Hour)
func (*Builder) StepUp ¶
func (identity *Builder) StepUp(credentials ...auth.Credential) *Builder
StepUp registers more step-up credentials after the built-in ones, for third-party modules. Federated logins are not a step-up method by default.
Example:
identity.StepUp(passkeys.Credential())
func (*Builder) Tokens ¶
func (identity *Builder) Tokens(configure ...apitoken.BuilderFunc) *Builder
Tokens turns personal access tokens and device tokens on. configure sets the scope catalog and the grant ceiling (apitoken.Builder.Grants), the kinds (apitoken.Builder.PersonalTokens, apitoken.Builder.DeviceTokens), the prefix and the lifetime cap of the apitoken package. Without a catalog tokens carry no scopes. Later calls replace the earlier one: only the configure callbacks of the last call count.
Example:
identity.Tokens(func(tokens *apitoken.Builder) {
tokens.Grants(apitoken.AnyScope, "posts:read", "posts:write")
})
func (*Builder) TwoFactor ¶
func (identity *Builder) TwoFactor(scheme totp.Scheme, cipher *crypto.Encrypter, configure ...twofactor.BuilderFunc) *Builder
TwoFactor turns the TOTP authenticator and recovery codes on. scheme holds the TOTP parameters and the issuer, the service name authenticator apps show (see totp.New); an invalid scheme, or a nil cipher, makes New fail with ErrInvalidConfig. cipher encrypts the secrets (use a key reserved for them). configure customizes the twofactor package. Later calls replace the earlier one: the last scheme, cipher and configure callbacks are all that count.
Example:
scheme := totp.New("Acme") // the name authenticator apps show for this account
identity.TwoFactor(scheme, cipher)
func (*Builder) Users ¶
func (identity *Builder) Users(provider *auth.UserProvider, configure ...UsersBuilderFunc) *Builder
Users replaces the built-in users table with the application's own; see UsersBuilder. provider serves the application's users to the guard (its UserRecord.Version must change when UsersBuilder.Rotate runs). Without this call the facade uses the built-in directory, which identifies users by email. Later calls replace the earlier one. It cannot be combined with Builder.Directory: New fails with ErrInvalidConfig.
Example:
identity.Users(provider, func(users *iam.UsersBuilder) {
users.Lookup(store.SubjectAndEmail)
users.Rotate(store.BumpVersion)
users.Verification(store.EmailVerified, store.MarkEmailVerified)
users.Create(store.Create)
})
type BuilderFunc ¶
type BuilderFunc = func(*Builder)
BuilderFunc is the callback form of Builder.
Example:
var configure iam.BuilderFunc = func(identity *iam.Builder) {
identity.Password(hasher)
}
identity, err := iam.New(db, store, configure)
type IAM ¶
type IAM struct {
// contains filtered or unexported fields
}
IAM is the composed authentication system: the guard, the enabled packages and the routes. It is safe for concurrent use. Create it with New.
Every package of the module assumes the one database.Database given to New: writes that span packages (registering a user and storing their password, deleting a user and forgetting their rows) join the transaction carried by the context.
Example:
identity, err := iam.New(db, store, func(identity *iam.Builder) {
identity.Password(hasher)
})
if err != nil {
return err
}
web := routes.With(identity.Middleware())
web.Group("/auth", identity.Register)
func New ¶
New composes the facade over db, the application's single database, store, the cache that holds sessions and counters. The default client address is the host of RemoteAddr, without trusting forwarding headers. Behind a reverse proxy r.RemoteAddr is the proxy, so every user shares one counter, and a header read without trusting the proxy that set it lets an attacker pick their own counter. Set Builder.ClientIP to a resolver from arkoren.dev/core/http/clientip when trusted infrastructure forwards requests. IAM does no I/O at construction: the application runs IAM.Migrations with its migrator, and IAM.Ping verifies the tables. Errors wrap ErrInvalidConfig; a setting that depends on a feature that is off is ignored with a warning instead.
Build order is: the user provider (built-in directory or [Users]), the enabled packages, then the guard with their credentials registered. The default registries are second factor: totp then recovery; step up: password then totp. A federated login is not a step-up method.
Example:
identity, err := iam.New(db, store, func(identity *iam.Builder) {
identity.Password(hasher)
})
if err != nil {
return err
}
if err := migrator.Add(identity.Migrations()...); err != nil {
return err
}
func (*IAM) Account ¶ added in v0.4.0
func (identity *IAM) Account(ctx context.Context) (AccountView, error)
Account returns what GET /account answers for the identity in ctx, which IAM.Middleware stores: the subject, the email facts, and the optional members that Builder.Account turned on. A context without an identity, or whose login still waits for its second factor, returns auth.ErrUnauthenticated. It works without Builder.Account, which only adds the route and turns on the optional parts: without it the view holds the subject and the email facts.
With the built-in users the email facts come from the directory: the email, whether it is verified, and the two timestamps. With the application's own users they come from the "email" and "email_verified" claims of auth.UserRecord.Claims, and there are no timestamps. An application that publishes a profile composes it with this view in its own route:
type Me struct {
iam.AccountView
Name string `json:"name"`
}
Example:
web.Get("/me", func(w http.ResponseWriter, r *http.Request) error {
view, err := identity.Account(r.Context())
if err != nil {
return err
}
profile, err := profiles.Find(r.Context(), view.Subject)
if err != nil {
return err
}
return response.JSON(w, http.StatusOK, Me{AccountView: view, Name: profile.Name})
})
func (*IAM) AccountHandler ¶ added in v0.4.0
AccountHandler returns the handler of GET /account: 200 with the AccountView of the request. A request without an identity, including a login that still waits for its second factor, answers 401 (auth.ErrUnauthenticated); a session cookie and a token both work. It panics unless Builder.Account was called.
Example:
web.Get("/account", identity.AccountHandler(), iam.AccountOperation)
func (*IAM) ChallengeHandler ¶
ChallengeHandler returns the handler of POST /login/challenge, which finishes a parked login with one of the user's second-factor methods; see auth.Guard.ChallengeHandler. It panics unless a second-factor method is registered (two-factor enabled, or Builder.SecondFactor).
Example:
web.Post("/login/challenge", identity.ChallengeHandler(), iam.ChallengeOperation)
func (*IAM) ChangePasswordHandler ¶
ChangePasswordHandler returns the handler of PUT /password; see password.Verifier.ChangeHandler. It panics unless Builder.Password is enabled.
Example:
web.Put("/password", identity.ChangePasswordHandler(), password.ChangeOperation)
func (*IAM) ConfirmHandler ¶
ConfirmHandler returns the handler of POST /confirm, which re-proves a logged-in user with a step-up method ("pwd" or "otp" by default) and so makes them fresh; see auth.Guard.ConfirmHandler. It panics unless a step-up method is registered (password or two-factor enabled, or Builder.StepUp).
Example:
web.Post("/confirm", identity.ConfirmHandler(), iam.ConfirmOperation)
func (*IAM) ConnectHandler ¶
ConnectHandler returns the handler of POST /connections/{provider}: it starts connecting the provider to the logged-in user and redirects (303) to the provider's login route, "/<name>" beside the route itself: the prefix is the path of the request before "/connections/", so a handler mounted at "/auth" redirects to "/auth/<name>". A handler registered on a custom path that has no "/connections/" segment redirects to "/<name>". See federation.Links.ConnectHandler. It panics unless Builder.Provider is used.
An unverified email is 403 account.ErrEmailUnverified (see UsersBuilder.Verification with your own users).
Example:
web.Post("/connections/{provider}", identity.ConnectHandler(), federation.ConnectOperation)
func (*IAM) CreateTokenHandler ¶
CreateTokenHandler returns the handler of POST /tokens; see apitoken.Issuer.CreateHandler. It panics unless Builder.Tokens is enabled with apitoken.Builder.PersonalTokens (the default). A scope the user may not hold is 403 apitoken.ErrScopeNotGranted.
An unverified email is 403 account.ErrEmailUnverified (see UsersBuilder.Verification with your own users).
Example:
web.Post("/tokens", identity.CreateTokenHandler(), apitoken.CreateOperation)
func (*IAM) DeleteAccountHandler ¶
DeleteAccountHandler returns the handler of DELETE /account: it deletes the logged-in user and answers 204. It needs a browser session and a fresh login (auth.Guard.Fresh). The user's row and every package's rows (passwords, two-factor, tokens, connections, login records) are removed in one transaction by the forget hooks, and a failure of any leaves the user in place. It panics without the built-in directory: with Builder.Users the application owns user deletion and calls auth.UserProvider.Forget itself.
Example:
web.Delete("/account", identity.DeleteAccountHandler(), iam.DeleteAccountOperation)
func (*IAM) DeleteConnectionHandler ¶
DeleteConnectionHandler returns the handler of DELETE /connections/{id}; see federation.Links.DeleteHandler. It panics unless Builder.Provider is used.
Example:
web.Delete("/connections/{id}", identity.DeleteConnectionHandler(), federation.DeleteOperation)
func (*IAM) DeleteDeviceTokenHandler ¶
DeleteDeviceTokenHandler returns the handler of DELETE /device-tokens/current, which revokes the presented token (a device's logout); see apitoken.Issuer.DeleteCurrentHandler. It panics unless Builder.Tokens is enabled with apitoken.Builder.DeviceTokens (the default).
Example:
api.Delete("/device-tokens/current", identity.DeleteDeviceTokenHandler(), apitoken.DeleteCurrentOperation)
func (*IAM) DeleteOtherSessionsHandler ¶
DeleteOtherSessionsHandler returns the handler of DELETE /sessions, which ends every login of the user except the one that made the request and answers 204. It needs a browser session. It is always available.
Example:
web.Delete("/sessions", identity.DeleteOtherSessionsHandler(), iam.DeleteOtherSessionsOperation)
func (*IAM) DeleteSessionHandler ¶
DeleteSessionHandler returns the handler of DELETE /sessions/{id}: it ends the login with that id (another device, or this one) and answers 204; an unknown id changes nothing. It needs a browser session. It is always available.
Example:
web.Delete("/sessions/{id}", identity.DeleteSessionHandler(), iam.DeleteSessionOperation)
func (*IAM) DeleteTokenHandler ¶
DeleteTokenHandler returns the handler of DELETE /tokens/{id}; see apitoken.Issuer.DeleteHandler. It panics unless Builder.Tokens is enabled.
Example:
web.Delete("/tokens/{id}", identity.DeleteTokenHandler(), apitoken.DeleteOperation)
func (*IAM) Directory ¶
Directory returns the built-in users table, or nil when the application brought its own with Builder.Users. With registration and sign-up both off this is how the application adds users: account.Directory.Create and account.Directory.CreateVerified.
Example:
if directory := identity.Directory(); directory != nil {
_ = directory.Disable(ctx, subject)
}
func (*IAM) DisableTwoFactorHandler ¶
DisableTwoFactorHandler returns the handler of DELETE /two-factor; see twofactor.Factors.DisableHandler. It panics unless Builder.TwoFactor is enabled.
Example:
web.Delete("/two-factor", identity.DisableTwoFactorHandler(), twofactor.DisableOperation)
func (*IAM) EnableTwoFactorHandler ¶
EnableTwoFactorHandler returns the handler of POST /two-factor; see twofactor.Factors.EnableHandler. It panics unless Builder.TwoFactor is enabled.
An unverified email is 403 account.ErrEmailUnverified (see UsersBuilder.Verification with your own users). Enabling ends the user's other logins.
Example:
web.Post("/two-factor", identity.EnableTwoFactorHandler(), twofactor.EnableOperation)
func (*IAM) ExchangeHandler ¶
ExchangeHandler returns the handler of POST /device-tokens, which trades a fresh login for a device token and ends the session; see apitoken.Issuer.ExchangeHandler. It panics unless Builder.Tokens is enabled with apitoken.Builder.DeviceTokens (the default).
An unverified email is 403 account.ErrEmailUnverified (see UsersBuilder.Verification with your own users).
Example:
web.Post("/device-tokens", identity.ExchangeHandler(), apitoken.ExchangeOperation)
func (*IAM) Factors ¶
Factors returns the two-factor store, or nil without Builder.TwoFactor.
Example:
if factors := identity.Factors(); factors != nil {
status, _ := factors.Status(ctx, subject)
_ = status
}
func (*IAM) ForgotPasswordHandler ¶
ForgotPasswordHandler returns the handler of POST /password/forgot; see password.Verifier.ForgotHandler. It panics unless Builder.Password is enabled with password.Builder.Reset. The work is stored as a job for the worker that IAM.RegisterJobs registers, and the answer is an empty 202 whether or not the user exists.
Example:
web.Post("/password/forgot", identity.ForgotPasswordHandler(), password.ForgotOperation)
func (*IAM) Grant ¶
Grant gives subject a permission directly; see permission.Store.Grant. Without Builder.Permissions it returns an error wrapping ErrInvalidConfig.
Example:
err := identity.Grant(ctx, subject, BillingExport)
func (*IAM) GrantPermissionHandler ¶
GrantPermissionHandler returns the handler of PUT /users/{subject}/permissions/{name}; see permission.Store.GrantHandler and permission.Store.GrantRoleHandler for the session, freshness and escalation rules. It panics unless Builder.Permissions is enabled with permission.Builder.Management.
Example:
web.Put("/users/{subject}/permissions/{name}", identity.GrantPermissionHandler(), permission.GrantOperation)
func (*IAM) GrantRole ¶
GrantRole assigns subject a role; see permission.Store.GrantRole. Without Builder.Permissions it returns an error wrapping ErrInvalidConfig.
Example:
err := identity.GrantRole(ctx, subject, Editor)
func (*IAM) GrantRoleHandler ¶
GrantRoleHandler returns the handler of PUT /users/{subject}/roles/{name}; see permission.Store.GrantRoleHandler. It panics unless Builder.Permissions is enabled with permission.Builder.Management.
Example:
web.Put("/users/{subject}/roles/{name}", identity.GrantRoleHandler(), permission.GrantRoleOperation)
func (*IAM) Guard ¶
Guard returns the guard the facade built, for code that logs users in itself (a custom provider, an SSO callback) or protects routes with auth.Guard.RequireFresh.
Example:
api.With(identity.Guard().RequireFresh(5 * time.Minute)).Delete("/billing", cancel)
func (*IAM) HasAnyPermission ¶
func (identity *IAM) HasAnyPermission(ctx context.Context, subject string, permissions ...gate.Permission) (bool, error)
HasAnyPermission reports whether subject holds at least one of permissions; see permission.Store.HasAnyPermission. Without Builder.Permissions it returns an error wrapping ErrInvalidConfig.
Example:
allowed, err := identity.HasAnyPermission(ctx, subject, PostsWrite, PostsModerate)
func (*IAM) HasAnyRole ¶
func (identity *IAM) HasAnyRole(ctx context.Context, subject string, roles ...gate.Role) (bool, error)
HasAnyRole reports whether subject holds at least one of roles; see permission.Store.HasAnyRole. Without Builder.Permissions it returns an error wrapping ErrInvalidConfig.
Example:
staff, err := identity.HasAnyRole(ctx, subject, Editor, Admin)
func (*IAM) HasPermission ¶
func (identity *IAM) HasPermission(ctx context.Context, subject string, required ...gate.Permission) (bool, error)
HasPermission reports whether subject holds every required permission; see permission.Store.HasPermission. It answers for any user; for the request's identity use gate.HasPermission. Without Builder.Permissions it returns an error wrapping ErrInvalidConfig.
Example:
allowed, err := identity.HasPermission(ctx, subject, BillingExport)
func (*IAM) HasRole ¶
func (identity *IAM) HasRole(ctx context.Context, subject string, required ...gate.Role) (bool, error)
HasRole reports whether subject holds every required role, directly or through an including role; see permission.Store.HasRole. Without Builder.Permissions it returns an error wrapping ErrInvalidConfig.
Example:
isEditor, err := identity.HasRole(ctx, subject, Editor)
func (*IAM) Issuer ¶
Issuer returns the token issuer, or nil without Builder.Tokens.
Example:
if issuer := identity.Issuer(); issuer != nil {
_ = issuer.RevokeAll(ctx, subject)
}
func (*IAM) Links ¶
func (identity *IAM) Links() *federation.Links
Links returns the connection store, or nil without Builder.Provider.
Example:
if links := identity.Links(); links != nil {
connections, _ := links.List(ctx, subject)
_ = connections
}
func (*IAM) ListConnectionsHandler ¶
ListConnectionsHandler returns the handler of GET /connections; see federation.Links.ListHandler. It panics unless Builder.Provider is used.
Example:
web.Get("/connections", identity.ListConnectionsHandler(), federation.ListOperation)
func (*IAM) ListSessionsHandler ¶
ListSessionsHandler returns the handler of GET /sessions: 200 with the user's logins (device, address, times; the request's own is marked current) as a JSON array. It needs a browser session. It is always available.
Example:
web.Get("/sessions", identity.ListSessionsHandler(), iam.ListSessionsOperation)
func (*IAM) ListTokensHandler ¶
ListTokensHandler returns the handler of GET /tokens; see apitoken.Issuer.ListHandler. It panics unless Builder.Tokens is enabled.
Example:
web.Get("/tokens", identity.ListTokensHandler(), apitoken.ListOperation)
func (*IAM) LoginHandler ¶
LoginHandler returns the handler of POST /login; see password.Verifier.LoginHandler. It panics unless Builder.Password is enabled.
Example:
web.Post("/login", identity.LoginHandler(), password.LoginOperation)
func (*IAM) LogoutHandler ¶
LogoutHandler returns the handler of POST /logout, which ends the current login; see auth.Guard.LogoutHandler. It is always available.
Example:
web.Post("/logout", identity.LogoutHandler(), iam.LogoutOperation)
func (*IAM) Middleware ¶
func (identity *IAM) Middleware() router.Middleware
Middleware returns the middleware to install on every route that identifies users: the session middleware, then the authenticators in order (the guard's browser session, the token issuer's bearer tokens when enabled, and those added with Builder.Authenticator). Apply it once per router and protect routes with auth.Require.
Example:
web := routes.With(identity.Middleware()) api := routes.With(identity.Middleware(), auth.Require())
func (*IAM) Migrations ¶
func (identity *IAM) Migrations() []migrate.Definition
Migrations returns the migrations of every feature of the module for this instance, in the order their tables depend on each other: users, passwords, two-factor, tokens, connections, permissions. It does not depend on which features are enabled, so enabling a feature later never needs a new migrator call: its table already exists and its readiness check already passes. The only structural choice that removes a group is Builder.Users: with the application's own users, the built-in users group is left out.
Each package keeps its own migration group (see the Migrations method of each package, which returns the same definitions), so they may also be added separately. Groups are append-only: a release that changes a table adds a migration at the end of its group, never rewrites a shipped one. The application adds the definitions to its migrator; the facade never runs DDL. IAM.Ping still checks the tables of the enabled features only.
Example:
if err := migrator.Add(identity.Migrations()...); err != nil {
return err
}
func (*IAM) MustAccept ¶
MustAccept panics at composition unless every method is registered in the guard's second-factor or step-up registry, so a typo in a method name or a module that was never registered fails at startup instead of on the first request.
Example:
identity.MustAccept(auth.MethodPassword, auth.MethodOTP)
func (*IAM) PendingHandler ¶
PendingHandler returns the handler of GET /login/pending, which tells a client with a parked login which methods it can use; see auth.Guard.PendingHandler. It panics unless a second-factor method is registered.
Example:
web.Get("/login/pending", identity.PendingHandler(), iam.PendingOperation)
func (*IAM) Permissions ¶
func (identity *IAM) Permissions() *permission.Store
Permissions returns the permission store, or nil without Builder.Permissions.
Example:
if permissions := identity.Permissions(); permissions != nil {
admins, err := permissions.Holders(ctx, Admin)
}
func (*IAM) Ping ¶
Ping verifies, read-only, that the tables of every enabled feature exist and returns the first failure, which wraps ErrNotMigrated. Use it as a readiness check.
Example:
if err := identity.Ping(ctx); err != nil {
return err
}
func (*IAM) Prune ¶
Prune deletes the tokens that can no longer authenticate: expired tokens, tokens a version change of their user ended, device tokens unused for longer than apitoken.Builder.DeviceIdleTTL and device tokens that were never used and are older than that; see apitoken.Issuer.Prune. Without Builder.Tokens there is nothing to prune and it returns nil, so one scheduled entry works for every composition. It changes no behavior (the bearer check already rejects these tokens), only keeps the table small, and it is safe to run concurrently and repeatedly.
It has the shape func(context.Context) error, so it can be a scheduled entry run daily.
Example:
err := scheduler.Add(schedule.NewEntry("access-prune", identity.Prune, func(entry *schedule.EntryBuilder) {
entry.When(schedule.UTC().Hour(3))
}))
func (*IAM) RecoveryCodesHandler ¶
RecoveryCodesHandler returns the handler of POST /two-factor/recovery-codes; see twofactor.Factors.RecoveryCodesHandler. It panics unless Builder.TwoFactor is enabled.
Example:
web.Post("/two-factor/recovery-codes", identity.RecoveryCodesHandler(), twofactor.RecoveryCodesOperation)
func (*IAM) Register ¶ added in v0.2.0
Register adds the default routes of the enabled features to r. Only the routes of enabled features are registered; "Always" routes need nothing.
Login POST /register (with Registration), POST /login, POST /login/challenge,
GET /login/pending, POST /logout
Step-up POST /confirm
Email POST /email/verify, POST /email/verify/resend
Password POST /password/forgot, POST /password/reset, PUT /password
Two-factor POST /two-factor/setup, POST /two-factor, DELETE /two-factor,
POST /two-factor/recovery-codes
Tokens GET /tokens, DELETE /tokens/{id}, POST /tokens (personal
tokens), POST /device-tokens, DELETE /device-tokens/current
(device tokens)
Sessions GET /sessions, DELETE /sessions/{id}, DELETE /sessions (always)
Providers GET /<name>, GET and POST /<name>/callback, and for
native providers GET /<name>/nonce, POST /<name>/native
Connections GET /connections, POST /connections/{provider},
DELETE /connections/{id}
Permissions GET /me/permissions (with SelfService), GET /users/{subject}/permissions,
PUT and DELETE /users/{subject}/permissions/{name} and
/users/{subject}/roles/{name} (with Management)
Account GET /account (with Account), DELETE /account (built-in users only)
The password routes need Builder.Password; of them, /register also needs password.Builder.Registration (off by default; New refuses it without users that can be created), and /password/forgot and /password/reset need password.Builder.Reset, because without it no user could receive a reset link. Register skips a route whose requirement is missing instead of panicking, so it never panics for a configuration New accepted; the matching XHandler method still panics when asked for directly. The challenge and pending routes need a registered second factor, /confirm a registered step-up method, and the email routes the built-in users and account.Builder.Verification. The token routes need Builder.Tokens: listing and revoking serve both kinds, POST /tokens needs apitoken.Builder.PersonalTokens and the two device routes apitoken.Builder.DeviceTokens (both default to on). The permission routes need Builder.Permissions: /me/permissions also permission.Builder.SelfService and the /users/{subject} routes permission.Builder.Management. GET /account needs Builder.Account. /logout and the session routes are always registered.
Register never installs IAM.Middleware; r must already run it. The middleware identifies the user behind every request, session, token or device, and it belongs on every route of the application that needs to know who is calling, not only on IAM's. Install it once, on the router that carries all of those routes, and derive IAM's routes from that router, so the application's own routes and IAM's share one identification step and installing it twice (or forgetting it here) cannot happen by accident.
The routes live at the paths above, relative to r: grouped under a prefix, as in routes.Group("/auth", identity.Register), they serve /auth/login and /auth/google/callback. Every path, the providers' included, is relative to the mount, and the connect handler redirects to the login route beside it by reading the prefix from the request, so any prefix works. Register each provider's callback URL with the prefix. To serve other paths, register the XHandler methods yourself; for another connect target use federation.Links.ConnectHandler on IAM.Links. The XHandler methods stay public for custom paths, for a single feature, and for per-route middleware. The connect, token, two-factor setup and enable handlers enforce the verified-email rule themselves, so they are gated on every path, including the package handlers of IAM.Links, IAM.Issuer and IAM.Factors used directly. Registering twice, or on a router that already has these patterns, panics like any duplicate route.
Register is a plain func(*router.Router) method, so its method value fits router.Router.Group.
Example:
web := routes.With(identity.Middleware())
web.Group("/auth", identity.Register)
func (*IAM) RegisterHandler ¶
RegisterHandler returns the handler of POST /register; see password.Verifier.RegisterHandler. It always answers 202 and does not log the user in. With the built-in users it stores no job unless account.Builder.Verification is also configured: then a new user gets a verification email and, for a taken address, nothing is created and the owner gets a reset notice (password.Builder.Reset, which registration with the built-in users requires). With Reset only, nothing is stored for a new or a taken address, so both cost the same. The work is the same on both paths, so the answer and its time do not tell them apart; a failing dispatch is logged and the answer stays 202. It panics unless Builder.Password is enabled with password.Builder.Registration.
Example:
web.Post("/register", identity.RegisterHandler(), password.RegisterOperation)
func (*IAM) RegisterJobs ¶ added in v0.5.0
RegisterJobs registers the handlers of the module's background jobs on consumer, so the process that runs the consumer sends the emails of password.Builder.Reset and account.Builder.Verification. The application does not name the jobs and nothing else needs wiring: new jobs of a feature that is enabled register here too. Features that are off register nothing, so a process that builds the same IAM as the one that dispatches registers exactly the jobs it can receive. Job names carry the Builder.Instance, so several instances can share one consumer.
The jobs run on the queue QueueName. RegisterJobs cannot see a queue restriction of the consumer: a consumer built with queue.ConsumerBuilder.Queues must list QueueName, or stored jobs wait unconsumed. It returns the first error of the registrations, for example queue.ErrDuplicateName when the consumer already handles the module's jobs. Run it at composition and let the consumer's own runner consume.
Example:
consumer := queue.NewConsumer(driver)
if err := identity.RegisterJobs(consumer); err != nil {
return err
}
compose.Run(consumer.Run)
func (*IAM) RequireVerified ¶
func (identity *IAM) RequireVerified() router.Middleware
RequireVerified returns middleware that admits only users whose email is verified. An anonymous request returns auth.ErrUnauthenticated; an unverified user account.ErrEmailUnverified (403). Install it after auth middleware.
With the built-in users it is account.RequireVerified: it judges by the "email_verified" claim of the user the guard read from the directory for this request, so a user who just verified passes at once. With Builder.Users it asks UsersBuilder.Verification for the user's current state on every request, so the answer is as fresh as the application's own lookup; an error of that function passes through. It panics at composition only when there is neither the built-in directory nor UsersBuilder.Verification.
Example:
posts := web.With(auth.Require(), identity.RequireVerified())
func (*IAM) ResendVerificationHandler ¶
ResendVerificationHandler returns the handler of POST /email/verify/resend; see account.Directory.ResendHandler. It panics without the built-in directory or without account.Builder.Verification. It is throttled per user and per client address and stores the work as a job for the worker that IAM.RegisterJobs registers.
Example:
web.Post("/email/verify/resend", identity.ResendVerificationHandler(), account.ResendOperation)
func (*IAM) ResetPasswordHandler ¶
ResetPasswordHandler returns the handler of POST /password/reset; see password.Verifier.ResetHandler. It panics unless Builder.Password is enabled with password.Builder.Reset.
Example:
web.Post("/password/reset", identity.ResetPasswordHandler(), password.ResetOperation)
func (*IAM) Resolve ¶
Resolve is the auth.Resolver the facade gives to its providers: it maps a verified external identity to a local subject through the connection store. It is nil-safe to call only with Builder.Provider; without providers it returns federation.ErrNotLinked. Use it to mount a provider by hand. It never signs users up, because sign-up is a setting of each provider given to Builder.Provider: a first login with an unknown identity is federation.ErrNoAccount (the takeover of an unverified user still works). For a hand-mounted provider that signs up, make its resolver with federation.Links.Resolver on IAM.Links, which creates users with the facade's own creation.
Example:
web.Get("/sso/callback", provider.CallbackHandler(identity.Guard(), identity.Resolve))
func (*IAM) Revoke ¶
Revoke takes a directly granted permission away from subject; see permission.Store.Revoke. Without Builder.Permissions it returns an error wrapping ErrInvalidConfig.
Example:
err := identity.Revoke(ctx, subject, BillingExport)
func (*IAM) RevokePermissionHandler ¶
RevokePermissionHandler returns the handler of DELETE /users/{subject}/permissions/{name}; see permission.Store.RevokeHandler. It panics unless Builder.Permissions is enabled with permission.Builder.Management.
Example:
web.Delete("/users/{subject}/permissions/{name}", identity.RevokePermissionHandler(), permission.RevokeOperation)
func (*IAM) RevokeRole ¶
RevokeRole takes a role away from subject; see permission.Store.RevokeRole, which answers permission.ErrLastHolder for the last holder of a KeepOne role. Without Builder.Permissions it returns an error wrapping ErrInvalidConfig.
Example:
err := identity.RevokeRole(ctx, subject, Editor)
func (*IAM) RevokeRoleHandler ¶
RevokeRoleHandler returns the handler of DELETE /users/{subject}/roles/{name}; see permission.Store.RevokeRoleHandler. It panics unless Builder.Permissions is enabled with permission.Builder.Management.
Example:
web.Delete("/users/{subject}/roles/{name}", identity.RevokeRoleHandler(), permission.RevokeRoleOperation)
func (*IAM) SelfPermissionsHandler ¶
SelfPermissionsHandler returns the handler of GET /me/permissions; see permission.Store.SelfHandler. It panics unless Builder.Permissions is enabled.
Example:
web.Get("/me/permissions", identity.SelfPermissionsHandler(), permission.SelfOperation)
func (*IAM) SetupTwoFactorHandler ¶
SetupTwoFactorHandler returns the handler of POST /two-factor/setup; see twofactor.Factors.SetupHandler. It panics unless Builder.TwoFactor is enabled.
An unverified email is 403 account.ErrEmailUnverified: whoever registered an address first must not attach this before its owner proves it (with your own users, see UsersBuilder.Verification).
Example:
web.Post("/two-factor/setup", identity.SetupTwoFactorHandler(), twofactor.SetupOperation)
func (*IAM) UserPermissionsHandler ¶
UserPermissionsHandler returns the handler of GET /users/{subject}/permissions; see permission.Store.UserHandler. It panics unless Builder.Permissions is enabled with permission.Builder.Management.
Example:
web.Get("/users/{subject}/permissions", identity.UserPermissionsHandler(), permission.UserOperation)
func (*IAM) UserProvider ¶
func (identity *IAM) UserProvider() *auth.UserProvider
UserProvider returns the auth.UserProvider every package shares: the built-in directory's, or the one given in [Users].
Example:
record, err := identity.UserProvider().Find(ctx, subject)
func (*IAM) Verifier ¶
Verifier returns the password package's verifier, or nil without Builder.Password.
Example:
if verifier := identity.Verifier(); verifier != nil {
_ = verifier.Set(ctx, subject, "a new long password")
}
func (*IAM) VerifyEmailHandler ¶
VerifyEmailHandler returns the handler of POST /email/verify; see account.Directory.VerifyHandler. It needs a browser session of the account the link belongs to (the user opens the link while logged in), so someone else's click cannot verify an account they do not hold. It panics without the built-in directory or without account.Builder.Verification.
Example:
web.Post("/email/verify", identity.VerifyEmailHandler(), account.VerifyOperation)
type NativeProvider ¶
type NativeProvider interface {
// NonceHandler issues the nonce the app puts in its ID token request.
NonceHandler() router.Handler
// NativeHandler verifies the app's ID token, maps it to a subject with resolve
// and begins the login on guard.
NativeHandler(guard *auth.Guard, resolve auth.Resolver) router.Handler
}
NativeProvider is the extra capability of a Provider that also accepts an ID token from a mobile app's own provider SDK (Google and Apple in ark/oauth). A provider that implements it also gets "/<name>/nonce" and "/<name>/native", below the mount prefix.
Example:
var _ identity.NativeProvider = (*oauthauth.Client)(nil)
type Provider ¶
type Provider interface {
// Name is the provider's name in mounted paths: "/<name>" starts the login
// and "/<name>/callback" finishes it, below the prefix the routes are mounted
// at (a mount at "/auth" serves "/auth/<name>"). Names must be unique.
Name() string
// LoginHandler starts the login by redirecting to the provider.
LoginHandler() router.Handler
// CallbackHandler finishes the login: it verifies the provider's answer,
// maps it to a subject with resolve and begins the login on guard.
CallbackHandler(guard *auth.Guard, resolve auth.Resolver) router.Handler
}
Provider is a browser login with an external identity provider, such as the *oauthauth.Client of arkoren.dev/ark/oauth, which satisfies it structurally: this module never imports ark/oauth.
Example:
identity.Provider(google) // an *oauthauth.Client
type ProviderBuilder ¶
type ProviderBuilder struct {
// contains filtered or unexported fields
}
ProviderBuilder configures one Provider in a Builder.Provider call. Its settings belong to that provider alone: another provider of the same facade can have different ones. Callbacks run directly once, in order, on one fresh draft and methods return the same draft.
Example:
identity.Provider(entra, func(login *iam.ProviderBuilder) {
login.SignUp(true)
})
func (*ProviderBuilder) Create ¶
func (login *ProviderBuilder) Create(create func(ctx context.Context, external auth.External) (string, error)) *ProviderBuilder
Create adds the application's rule for creating the user of an identity that signs up with this provider; it only runs when ProviderBuilder.SignUp is enabled. It runs before the facade's own creation and returns the new user's subject, and its errors pass through to the client. Returning "" and no error hands the identity on, so what it declines still gets the facade's creation (a user made through UsersBuilder.Create, verified when the provider proved the email). Calls add up in the order made until one returns a subject. The facade never links by email, so the function must not return an existing user. See federation.Builder.Create.
Example:
login.Create(func(ctx context.Context, external auth.External) (string, error) {
if !strings.HasSuffix(external.Email, "@acme.example") {
return "", errNotInvited
}
return "", nil
})
func (*ProviderBuilder) KeepClaims ¶ added in v0.4.0
func (login *ProviderBuilder) KeepClaims(names ...string) *ProviderBuilder
KeepClaims names claims of this provider's verified identity that its connection stores, to prefill a profile form from federation.Links.List later (Google sends "name" and "picture", GitHub "name" and "login"). Nothing is kept by default and calls add up. The claims are unverified suggestions of the provider: use them to prefill, never for authorization, identity or to match users. A login overwrites the claims it carries and keeps the rest, so Apple's name, sent only on the first login, stays; a claim the provider stops sending stays too. Only strings, booleans, numbers and lists of strings are kept, up to 8 KiB per connection. An empty name or a protocol claim (iss, sub, aud, exp, iat, nbf, nonce, at_hash, auth_time, scope, azp, acr, amr) makes New fail with ErrInvalidConfig. See federation.ResolverBuilder.KeepClaims for the storage rules; GET /connections shows the kept claims.
Example:
login.KeepClaims("name", "picture")
func (*ProviderBuilder) SignUp ¶
func (login *ProviderBuilder) SignUp(enabled bool) *ProviderBuilder
SignUp lets a first logged-out login with this provider and an identity the application does not know create a user and connect the identity to it; the default is false. With false such a login fails with federation.ErrNoAccount (403, "federation:no-account") and creates nothing, so only people the application already has can sign in with this provider: they log in another way and connect it, or the application adds the user first. Logging in with an identity already connected, a logged-in user connecting the provider, and the takeover of an unverified built-in user by the owner of a provider-verified address never need it. With true, a first login must carry an email the provider proved, or it fails with federation.ErrEmailUnverified (403) and creates nothing. It needs users that can be created, which the built-in users always are; with Builder.Users that has no UsersBuilder.Create, nothing could create the user: New ignores SignUp, with one warning, and the provider logs in only known identities.
Example:
login.SignUp(true)
type ProviderBuilderFunc ¶
type ProviderBuilderFunc = func(*ProviderBuilder)
ProviderBuilderFunc is the callback form of ProviderBuilder.
Example:
var enableSignUp identity.ProviderBuilderFunc = func(login *iam.ProviderBuilder) {
login.SignUp(true)
}
identity.Provider(entra, enableSignUp)
type UsersBuilder ¶ added in v0.7.0
type UsersBuilder struct {
// contains filtered or unexported fields
}
UsersBuilder configures the application's own user store in a Builder.Users call. The facade then migrates no users table, never creates or deletes users itself, and talks to the application's users only through these functions. Callbacks run directly once, in order, on one fresh draft and methods return the same draft.
Example:
identity.Users(provider, func(users *iam.UsersBuilder) {
users.Lookup(store.SubjectAndEmail)
users.Rotate(store.BumpVersion)
users.Verification(store.EmailVerified, store.MarkEmailVerified)
users.Create(store.Create)
})
Email verification is the application's with its own users. The built-in directory refuses unverified users the actions an earlier holder of the address could abuse (connecting a provider, enrolling two-factor, creating tokens) and, when a password reset proves the mailbox, removes what such a holder attached. With your own users the facade does the same through UsersBuilder.Verification, which is required whenever UsersBuilder.Create is set (new users start unverified); without it (users created elsewhere) the facade does neither, and the application must enforce the rule itself.
func (*UsersBuilder) Create ¶ added in v0.7.0
func (users *UsersBuilder) Create(create func(ctx context.Context, identifier string, verified bool) (subject string, err error)) *UsersBuilder
Create sets the function that adds a user and returns the subject. It serves registration (with verified false) and the first login with an external identity (the identifier is then the provider's email, possibly empty, and verified is auth.External.EmailVerified); its errors pass through to the client. Both are off by default: password.Builder.Registration and ProviderBuilder.SignUp must be enabled, and New ignores each, with a warning, when Create is unset.
Create must fail on an existing identifier and never return the existing user: connecting an identity to someone by email is how accounts get taken over. For a taken identifier return an error wrapping ErrIdentifierTaken (the built-in directory's account.ErrEmailTaken is recognized too): registration then answers like a new user and notifies the owner, instead of answering 409. Requires UsersBuilder.Verification.
Example:
users.Create(store.Create)
func (*UsersBuilder) Lookup ¶ added in v0.7.0
func (users *UsersBuilder) Lookup(lookup func(ctx context.Context, identifier string) (subject, address string, err error)) *UsersBuilder
Lookup sets the function that returns the subject of the user with identifier, whatever the application uses to log in (an email, a username), and the address to send mail to, as stored with the user and never the typed identifier. An unknown user must return an error wrapping auth.ErrUserNotFound. It is required with Builder.Password.
Example:
users.Lookup(store.SubjectAndEmail)
func (*UsersBuilder) Rotate ¶ added in v0.7.0
func (users *UsersBuilder) Rotate(rotate func(ctx context.Context, subject string) error) *UsersBuilder
Rotate sets the function that bumps auth.UserRecord.Version, which ends every session, pending login and API token of the user. A password reset calls it inside its transaction. It is required with Builder.Password.
Example:
users.Rotate(store.BumpVersion)
func (*UsersBuilder) Verification ¶ added in v0.7.0
func (users *UsersBuilder) Verification( verified func(ctx context.Context, subject string) (bool, error), proveEmail func(ctx context.Context, subject string) (wasUnverified bool, err error), ) *UsersBuilder
Verification wires email-verification checks and mailbox-proof cleanup.
verified reports whether the user's email is verified. The handlers that connect a provider, enroll two-factor or create tokens then answer 403 account.ErrEmailUnverified to unverified users, and IAM.RequireVerified checks it on each request.
proveEmail runs in the transaction of a completed password reset because the link reached the mailbox. It marks the email verified and reports whether it was unverified before; if so the facade deletes the user's connections, two-factor enrollment, recovery codes and tokens, which may belong to whoever registered the address first. An error rolls the reset back.
Both functions must be non-nil (or both nil to clear). Required whenever UsersBuilder.Create is set.
Example:
users.Verification(store.EmailVerified, store.MarkEmailVerified)
type UsersBuilderFunc ¶ added in v0.7.0
type UsersBuilderFunc = func(*UsersBuilder)
UsersBuilderFunc is the callback form of UsersBuilder.
Example:
var configure iam.UsersBuilderFunc = func(users *iam.UsersBuilder) {
users.Lookup(store.SubjectAndEmail).Rotate(store.BumpVersion)
}
identity.Users(provider, configure)
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package account is the built-in users table of arkoren.dev/ark/iam: a Directory of users identified by email, the auth.UserProvider that serves them to the guard, and email verification with signed links.
|
Package account is the built-in users table of arkoren.dev/ark/iam: a Directory of users identified by email, the auth.UserProvider that serves them to the guard, and email verification with signed links. |
|
Package apitoken issues opaque, hashed, revocable bearer tokens to users: personal access tokens (named, scoped, optionally expiring, shown once) and device tokens for first-party mobile and desktop apps (issued when a login is exchanged, revoked by the device's own logout, and ended after DefaultDeviceIdleTTL of disuse).
|
Package apitoken issues opaque, hashed, revocable bearer tokens to users: personal access tokens (named, scoped, optionally expiring, shown once) and device tokens for first-party mobile and desktop apps (issued when a login is exchanged, revoked by the device's own logout, and ended after DefaultDeviceIdleTTL of disuse). |
|
Package federation connects external identities, such as a Google or GitHub account verified by ark/oauth, to local users.
|
Package federation connects external identities, such as a Google or GitHub account verified by ark/oauth, to local users. |
|
internal
|
|
|
apptest
Package apptest is the HTTP harness of the tests of arkoren.dev/ark/iam: a router with session and auth middleware behind an in-process server and a client that keeps cookies, like a browser.
|
Package apptest is the HTTP harness of the tests of arkoren.dev/ark/iam: a router with session and auth middleware behind an in-process server and a client that keeps cookies, like a browser. |
|
migration
Package migration holds the migration definitions of every table of arkoren.dev/ark/iam, one function per package and group.
|
Package migration holds the migration definitions of every table of arkoren.dev/ark/iam, one function per package and group. |
|
storage
Package storage holds the table conventions shared by the packages of arkoren.dev/ark/iam: instance validation, table and migration-group names, identifiers, secret hashing and the readiness check.
|
Package storage holds the table conventions shared by the packages of arkoren.dev/ark/iam: instance validation, table and migration-group names, identifiers, secret hashing and the readiness check. |
|
throttle
Package throttle counts attempts in the application's cache for the packages of arkoren.dev/ark/iam, so a wrong-secret handler can answer 429 with Retry-After before it does any expensive work.
|
Package throttle counts attempts in the application's cache for the packages of arkoren.dev/ark/iam, so a wrong-secret handler can answer 429 with Retry-After before it does any expensive work. |
|
web
Package web holds the request helpers shared by the handlers of the packages of arkoren.dev/ark/iam.
|
Package web holds the request helpers shared by the handlers of the packages of arkoren.dev/ark/iam. |
|
Package password registers, logs in and recovers users by password.
|
Package password registers, logs in and recovers users by password. |
|
Package permission stores which users hold which roles and permissions, and answers what a user holds.
|
Package permission stores which users hold which roles and permissions, and answers what a user holds. |
|
Package twofactor adds a time-based one-time password (TOTP) authenticator and single-use recovery codes to any user store.
|
Package twofactor adds a time-based one-time password (TOTP) authenticator and single-use recovery codes to any user store. |