Documentation
¶
Overview ¶
Package session provides cookie-backed sessions for web applications.
Auth is the session: one cookie, one session table and one middleware chain that any registered sign-in method can establish. The password method lives here (PasswordSignIn); the redirect-based methods are their own packages, built on the signin contract: azure (Microsoft Entra ID), google (Google Workspace) and workos (WorkOS SSO). Preauth lets an application bring its own authentication and still use the session handlers.
OIDCAzure and PasswordAuth are the legacy single-method session types, kept for the applications that still run on them; new applications use Auth.
Every session type supports custom session data: an app-defined table whose row is resolved atomically inside the session-insert transaction (or supplied per call), decoded on every authenticated request, reset on session regeneration, and cleaned up with the session via the table's ON DELETE CASCADE. See the "Custom session data" section of the README for the full lifecycle, schema contract, and failure semantics.
Auth, password auth and the legacy OIDC type additionally support custom user data: an app-defined table keyed by the durable user record (SessionUsers, or the library-managed OIDCUsers anchor for the legacy OIDC type), written atomically with user creation or login and read on demand — it survives logout, expiry, and regeneration, and dies with the user. See the "Custom user data" and "OIDC user anchor" sections of the README.
Index ¶
- func SignInAttemptName(username string) string
- type AdvertisedMethod
- type ApplicationTokenHandlers
- type ApplicationTokenRequest
- type Auth
- func (a *Auth[S, U, Tx]) API() *AuthAPI[S, U, Tx]
- func (a *Auth[S, U, Tx]) ApplicationTokens() *ApplicationTokenHandlers
- func (a *Auth[S, U, Tx]) Authenticated() http.HandlerFunc
- func (a *Auth[S, U, Tx]) Device() *DeviceHandlers
- func (a *Auth[S, U, Tx]) Email() *EmailHandlers
- func (a *Auth[S, U, Tx]) EndImpersonation() http.HandlerFunc
- func (a *Auth[S, U, Tx]) EnforceReadOnlyMask(next http.Handler) http.Handler
- func (a *Auth[S, U, Tx]) Invitation() *InvitationHandlers
- func (a *Auth[S, U, Tx]) Logout() http.HandlerFunc
- func (a *Auth[S, U, Tx]) Methods(list *MethodList) http.HandlerFunc
- func (a *Auth[S, U, Tx]) Pending() *PendingHandlers
- func (a *Auth[S, U, Tx]) RegisterExternal(reg *signin.Registration[Tx]) signin.Handlers
- func (a *Auth[SessionData, UserData, Tx]) SetDirectoryAdmission(reader signin.DirectoryReader[Tx], roles signin.UserRoleManager, ...)
- func (a *Auth[SessionData, UserData, Tx]) SetInvitationAccepted(hook InvitationAcceptedHook[Tx])
- func (a *Auth[SessionData, UserData, Tx]) SetSignInPolicy(policy signin.Policy[Tx])
- func (a *Auth[SessionData, UserData, Tx]) SetSignedInHook(hook SignedInHook)
- func (a *Auth[SessionData, UserData, Tx]) SetUserRenamed(hook UserRenamedHook)
- func (a *Auth[S, U, Tx]) SetXSRFToken(next http.Handler) http.Handler
- func (a *Auth[S, U, Tx]) SignUp() *SignUpHandlers
- func (a *Auth[S, U, Tx]) StartSession(next http.Handler) http.Handler
- func (a *Auth[S, U, Tx]) ValidateSession(next http.Handler) http.Handler
- func (a *Auth[S, U, Tx]) ValidateXSRFToken(next http.Handler) http.Handler
- type AuthAPI
- func (p *AuthAPI[S, U, Tx]) ActivateSessionUser(ctx context.Context, userID impulse.UUID) error
- func (p *AuthAPI[S, U, Tx]) ActiveImpersonations(ctx context.Context, q *ImpersonationQuery) ([]*sessioninfo.Impersonation, error)
- func (p *AuthAPI[S, U, Tx]) ApproveDevice(ctx context.Context, userID impulse.UUID, userCode string) error
- func (p *AuthAPI[S, U, Tx]) ChangeSessionUserPassword(ctx context.Context, w http.ResponseWriter, userID impulse.UUID, ...) error
- func (p *AuthAPI[S, U, Tx]) ChangeSessionUserUsername(ctx context.Context, userID impulse.UUID, username string) error
- func (p *AuthAPI[S, U, Tx]) CompletePending(ctx context.Context, w http.ResponseWriter, stepUp ...sessioninfo.AuthEvent) (impulse.UUID, error)
- func (p *AuthAPI[S, U, Tx]) ConfirmPendingWithPassword(ctx context.Context, w http.ResponseWriter, password string) (impulse.UUID, error)
- func (p *AuthAPI[S, U, Tx]) Cookie() *cookie.Client
- func (p *AuthAPI[S, U, Tx]) CreateApplicationToken(ctx context.Context, req *ApplicationTokenRequest) (*IssuedToken, error)
- func (p *AuthAPI[S, U, Tx]) CreateSessionUser(ctx context.Context, req *CreateUserRequest, customData ...*U) (impulse.UUID, error)
- func (p *AuthAPI[S, U, Tx]) CustomData(ctx context.Context) (S, error)
- func (p *AuthAPI[S, U, Tx]) CustomUserData(ctx context.Context, userID impulse.UUID) (U, error)
- func (p *AuthAPI[S, U, Tx]) DeactivateSessionUser(ctx context.Context, userID impulse.UUID) error
- func (p *AuthAPI[S, U, Tx]) DeleteSessionUser(ctx context.Context, userID impulse.UUID) error
- func (p *AuthAPI[S, U, Tx]) DenyDevice(ctx context.Context, userCode string) error
- func (p *AuthAPI[S, U, Tx]) DestroyImpersonatedSession(ctx context.Context, sessionID impulse.UUID) error
- func (p *AuthAPI[S, U, Tx]) DestroyImpersonatedSessions(ctx context.Context, actor string) error
- func (p *AuthAPI[S, U, Tx]) DestroyUserSessions(ctx context.Context, userID impulse.UUID) error
- func (p *AuthAPI[S, U, Tx]) EndImpersonation(ctx context.Context, w http.ResponseWriter) (restored bool, err error)
- func (p *AuthAPI[S, U, Tx]) EnrollEmail(ctx context.Context, email string) error
- func (p *AuthAPI[S, U, Tx]) ForgetTrustedDevice(ctx context.Context, w http.ResponseWriter) error
- func (p *AuthAPI[S, U, Tx]) HashPassword(password string) (string, error)
- func (p *AuthAPI[S, U, Tx]) Identities(ctx context.Context, userID impulse.UUID) ([]*sessionstorage.SessionIdentity, error)
- func (p *AuthAPI[S, U, Tx]) Invitations(ctx context.Context) ([]*sessioninfo.Invitation, error)
- func (p *AuthAPI[S, U, Tx]) Invite(ctx context.Context, req *InvitationRequest) (*sessioninfo.Invitation, error)
- func (p *AuthAPI[S, U, Tx]) Logout(ctx context.Context) error
- func (p *AuthAPI[S, U, Tx]) PendingDevice(ctx context.Context, userCode string) (*sessionstorage.DeviceCode, error)
- func (p *AuthAPI[S, U, Tx]) PendingIdentity(ctx context.Context) (*sessioninfo.PendingIdentity, error)
- func (p *AuthAPI[S, U, Tx]) PrepareInvitation(ctx context.Context, req *InvitationRequest) (PreparedInvitation, error)
- func (p *AuthAPI[S, U, Tx]) RedeemDeviceCode(ctx context.Context, deviceCode string) (*TokenPair, sessionstorage.DeviceCodeStatus, error)
- func (p *AuthAPI[S, U, Tx]) RefreshTokens(ctx context.Context, refreshToken string) (*TokenPair, error)
- func (p *AuthAPI[S, U, Tx]) ResetFactors(ctx context.Context, userID impulse.UUID) error
- func (p *AuthAPI[S, U, Tx]) ResetSessionUserPassword(ctx context.Context, userID impulse.UUID, temporary string) error
- func (p *AuthAPI[S, U, Tx]) RevokeInvitation(ctx context.Context, id impulse.UUID) error
- func (p *AuthAPI[S, U, Tx]) RevokeToken(ctx context.Context, userID, id impulse.UUID) error
- func (p *AuthAPI[S, U, Tx]) RevokeUserTokens(ctx context.Context, userID impulse.UUID) error
- func (p *AuthAPI[S, U, Tx]) SendEmailCode(ctx context.Context) (codeEmail string, expiresAt time.Time, err error)
- func (p *AuthAPI[S, U, Tx]) SetSessionUserEmail(ctx context.Context, userID impulse.UUID, email *string) error
- func (p *AuthAPI[S, U, Tx]) SetSessionUserPassword(ctx context.Context, userID impulse.UUID, password string) error
- func (p *AuthAPI[S, U, Tx]) StartAuthenticatedSession(ctx context.Context, w http.ResponseWriter, userID impulse.UUID, ...) (impulse.UUID, error)
- func (p *AuthAPI[S, U, Tx]) StartDeviceAuthorization(ctx context.Context, req *DeviceAuthorizationRequest) (*DeviceAuthorization, error)
- func (p *AuthAPI[S, U, Tx]) StartImpersonatedSession(ctx context.Context, w http.ResponseWriter, req *ImpersonationRequest, ...) (impulse.UUID, error)
- func (p *AuthAPI[S, U, Tx]) Tokens(ctx context.Context, userID impulse.UUID) ([]*sessionstorage.Token, error)
- func (p *AuthAPI[S, U, Tx]) UnlinkIdentity(ctx context.Context, identityID impulse.UUID) error
- func (p *AuthAPI[S, U, Tx]) UpdateCustomSessionData(ctx context.Context, sessionID impulse.UUID, mutate func(data *S) error) error
- func (p *AuthAPI[S, U, Tx]) UpdateCustomUserData(ctx context.Context, userID impulse.UUID, mutate func(data *U) error) error
- func (p *AuthAPI[S, U, Tx]) User(ctx context.Context, userID impulse.UUID) (*sessionstorage.SessionUser, error)
- func (p *AuthAPI[S, U, Tx]) UserByEmail(ctx context.Context, email string) (*sessionstorage.SessionUser, error)
- func (p *AuthAPI[S, U, Tx]) UserByUsername(ctx context.Context, username string) (*sessionstorage.SessionUser, error)
- func (p *AuthAPI[S, U, Tx]) Users(ctx context.Context) ([]*sessionstorage.SessionUser, error)
- func (p *AuthAPI[S, U, Tx]) ValidateCredentials(ctx context.Context, username, password string) (impulse.UUID, error)
- func (p *AuthAPI[S, U, Tx]) ValidateSession(ctx context.Context) (context.Context, error)
- func (p *AuthAPI[S, U, Tx]) VerifyEmailCode(ctx context.Context, w http.ResponseWriter, code string, rememberDevice bool) (impulse.UUID, error)
- type AuthOption
- func WithDeviceCodeLifetime(lifetime, pollInterval time.Duration) AuthOption
- func WithDeviceCodesTableName(name string) AuthOption
- func WithDeviceVerificationURL(path string) AuthOption
- func WithEmailCodeTimeout(d time.Duration) AuthOption
- func WithFactorCodesTableName(name string) AuthOption
- func WithIdentitiesTableName(name string) AuthOption
- func WithIdentityLinked(hook IdentityLinkedHook) AuthOption
- func WithInvitationCookieName(name string) AuthOption
- func WithMail(sender mail.Sender, settings MailSettings) AuthOption
- func WithMailLinksTableName(name string) AuthOption
- func WithPendingCookieName(name string) AuthOption
- func WithPendingHook(hook PendingHook) AuthOption
- func WithPendingSignInsTableName(name string) AuthOption
- func WithPendingTimeout(d time.Duration) AuthOption
- func WithSignInAttemptsTableName(name string) AuthOption
- func WithTokenLifetimes(access, refresh, applicationMax time.Duration) AuthOption
- func WithTokensTableName(name string) AuthOption
- func WithTrustedDeviceCookieName(name string) AuthOption
- func WithTrustedDevicePeriod(d time.Duration) AuthOption
- func WithTrustedDevicesTableName(name string) AuthOption
- type BaseSessionOption
- func WithImpersonationAudit(hook ImpersonationAuditHook) BaseSessionOption
- func WithImpersonationTimeout(d time.Duration) BaseSessionOption
- func WithLogHandler(l LogHandler) BaseSessionOption
- func WithPrincipalResolver(resolve PrincipalResolver) BaseSessionOption
- func WithSessionTableName(name string) BaseSessionOption
- func WithSessionTimeout(d time.Duration) BaseSessionOption
- func WithUserTableName(name string) BaseSessionOption
- type ChangeSessionUserPasswordRequest
- type CookieOption
- type CreateUserRequest
- type DeviceAuthorization
- type DeviceAuthorizationRequest
- type DeviceHandlers
- type DirectorySeatedHook
- type DisabledRoleSyncConfig
- type EmailHandlers
- type EmailRoutes
- type IdentityLinkedHook
- type ImpersonationAuditHook
- type ImpersonationQuery
- type ImpersonationRequest
- type InvitationAcceptedHook
- type InvitationHandlers
- type InvitationRequest
- type InvitationRoutes
- type InvitationRow
- type IssuedToken
- type LogHandler
- type MachineOutlet
- type MailSettings
- type MethodList
- type NoCustomData
- type PasswordMethod
- type PasswordOption
- type PendingHandlers
- func (h *PendingHandlers) Cancel() http.HandlerFunc
- func (h *PendingHandlers) ConfirmWithPassword() http.HandlerFunc
- func (h *PendingHandlers) EnrollEmail() http.HandlerFunc
- func (h *PendingHandlers) SendCode() http.HandlerFunc
- func (h *PendingHandlers) Status() http.HandlerFunc
- func (h *PendingHandlers) VerifyCode() http.HandlerFunc
- type PendingHook
- type PendingRoutes
- type Preauth
- func (p *Preauth[T]) API() *PreauthAPI[T]
- func (p *Preauth[T]) Authenticated() http.HandlerFunc
- func (p *Preauth[T]) EndImpersonation() http.HandlerFunc
- func (p *Preauth[T]) EnforceReadOnlyMask(next http.Handler) http.Handler
- func (p *Preauth[T]) Logout() http.HandlerFunc
- func (p *Preauth[T]) SetXSRFToken(next http.Handler) http.Handler
- func (p *Preauth[T]) StartSession(next http.Handler) http.Handler
- func (p *Preauth[T]) ValidateSession(next http.Handler) http.Handler
- func (p *Preauth[T]) ValidateXSRFToken(next http.Handler) http.Handler
- type PreauthAPI
- func (p *PreauthAPI[T]) ActiveImpersonations(ctx context.Context, q *ImpersonationQuery) ([]*sessioninfo.Impersonation, error)
- func (p *PreauthAPI[T]) Cookie() *cookie.Client
- func (p *PreauthAPI[T]) CustomData(ctx context.Context) (T, error)
- func (p *PreauthAPI[T]) DestroyAllUserSessions(ctx context.Context, username string) error
- func (p *PreauthAPI[T]) DestroyImpersonatedSession(ctx context.Context, sessionID impulse.UUID) error
- func (p *PreauthAPI[T]) DestroyImpersonatedSessions(ctx context.Context, actor string) error
- func (p *PreauthAPI[T]) EndImpersonation(ctx context.Context, w http.ResponseWriter) (restored bool, err error)
- func (p *PreauthAPI[T]) Login(ctx context.Context, w http.ResponseWriter, username string, customData ...*T) (impulse.UUID, error)
- func (p *PreauthAPI[T]) Logout(ctx context.Context) error
- func (p *PreauthAPI[T]) StartImpersonatedSession(ctx context.Context, w http.ResponseWriter, req *ImpersonationRequest, ...) (impulse.UUID, error)
- func (p *PreauthAPI[T]) StartSession(ctx context.Context, w http.ResponseWriter, r *http.Request) (context.Context, error)
- func (p *PreauthAPI[T]) UpdateCustomSessionData(ctx context.Context, sessionID impulse.UUID, mutate func(data *T) error) error
- func (p *PreauthAPI[T]) ValidateSession(ctx context.Context) (context.Context, error)
- type PreauthHandlers
- type PreauthOption
- type PreparedInvitation
- type PrincipalResolver
- type RoleSyncConfig
- type SignUpHandlers
- type SignUpRoutes
- type SignedIn
- type SignedInHook
- type Tables
- type TokenPair
- type UserRenamedHook
- type UserRoleManager
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func SignInAttemptName ¶ added in v0.3.0
SignInAttemptName returns the name a username's failed sign-ins are counted under: the key of its row in the sign-in attempts table (Tables.SignInAttempts), the username in Unicode NFC and case-folded, as the users table normalizes usernames. A caller that clears a name's count in a transaction of its own (the generated user management) deletes the row of this key; a name with no row has no count.
Types ¶
type AdvertisedMethod ¶
type AdvertisedMethod struct {
// Name is the name the method was registered under on the Auth ("password", or
// the application's name for an external registration).
Name string
// Label is what the page shows for the method.
Label string
// Path is the path the method's Login handler is mounted at, a path in the
// application in canonical form (see SanitizeReturnURL): /api/user/google/login.
Path string
}
AdvertisedMethod is one method of a MethodList.
type ApplicationTokenHandlers ¶
type ApplicationTokenHandlers struct {
// contains filtered or unexported fields
}
ApplicationTokenHandlers are the HTTP handlers of a person's application tokens: the page where they issue, list and revoke tokens for programs of their own.
func (*ApplicationTokenHandlers) Create ¶
func (h *ApplicationTokenHandlers) Create() http.HandlerFunc
Create accepts {"name", "outlet", "expiresIn"} from the signed-in person, expiresIn in seconds and optional, and issues an application token for the outlet as them. It answers {"id", "token", "name", "outlet", "expiresAt"}: token is the secret, shown this once. An outlet that is not registered, a missing name or a lifetime past the Auth's is 400. Route it behind ValidateSession and ValidateXSRFToken.
func (*ApplicationTokenHandlers) List ¶
func (h *ApplicationTokenHandlers) List() http.HandlerFunc
List answers the signed-in person's live tokens, newest first, as [{"id", "kind", "name", "outlet", "clientId", "createdAt", "expiresAt", "lastUsedAt"}]: their application tokens and the tokens of their device grants, never a secret. Route it behind ValidateSession.
func (*ApplicationTokenHandlers) Revoke ¶
func (h *ApplicationTokenHandlers) Revoke() http.HandlerFunc
Revoke accepts {"id"} from the signed-in person and revokes that token of theirs, a device grant's with its family. It answers {}; a token that is not theirs or not live is 404. Route it behind ValidateSession and ValidateXSRFToken.
type ApplicationTokenRequest ¶
type ApplicationTokenRequest struct {
// UserID is the person the token acts as.
UserID impulse.UUID
// Outlet is the registered machine outlet the token is for.
Outlet string
// Name is what the person calls the token, so they recognize it in their listing.
Name string
// ExpiresIn is how long the token lives, at most the Auth's application token
// lifetime; zero takes that lifetime.
ExpiresIn time.Duration
}
ApplicationTokenRequest is what a person asks for when they issue an application token.
type Auth ¶
type Auth[SessionData, UserData, Tx any] struct { // contains filtered or unexported fields }
Auth is one session type that any registered sign-in method can establish. Auth, sessions, cookies, XSRF, custom data, impersonation and the middleware work the same for every method.
Register sign-in methods with PasswordSignIn, azure.SignIn and google.SignIn after NewAuth and before serving the first request (workos.SignIn once WorkOS returns to the public API in v0.13.1). Each returns the method's handlers.
Every session belongs to a user (SessionUsers). A sign-in either establishes a session under a new session ID, becomes a pending identity that waits for a password confirmation or the application's MFA step, or is refused with a sessioninfo.LoginRefusalCode. See the README's "Auth sessions (multiple sign-in methods)" for the routes and the redirect contract.
Tx is the storage's transaction type (pgx.Tx, *spanner.ReadWriteTransaction), taken from the storage NewAuth is given. The sign-in policy and every external method's user resolver receive it, so a hook written for the other backend does not compile.
func NewAuth ¶
func NewAuth[SessionData, UserData, Tx any]( storage sessionstorage.AuthStore[Tx], cookieKey string, options ...AuthOption, ) (*Auth[SessionData, UserData, Tx], error)
NewAuth creates an Auth session for the given storage. The storage's custom session and user data configurations must be built for SessionData and UserData. The OIDC-only storage features (the OIDC user anchor and the custom user data login hook) are refused. Tx is inferred from the storage: an application writes NewAuth[SessionData, UserData](store, cookieKey, options...).
A sign-in is decided by the library's own checks: the user exists and is enabled, the identity is linked or resolved, roles reconcile. An application with rules of its own sets a sign-in policy with SetSignInPolicy. Each external method's first sign-in rule is given to that method's registration. cookieKey: A Base64-encoded string representing at least 32 bytes of cryptographically secure random data.
func (*Auth[S, U, Tx]) ApplicationTokens ¶
func (a *Auth[S, U, Tx]) ApplicationTokens() *ApplicationTokenHandlers
ApplicationTokens returns the application token handlers.
func (*Auth[S, U, Tx]) Authenticated ¶
func (a *Auth[S, U, Tx]) Authenticated() http.HandlerFunc
Authenticated answers {"authenticated", "username", "passwordChangeRequired", "email", "emailVerified", "emailHint", "impersonation"}. A session whose user is missing or disabled is reported as not authenticated. passwordChangeRequired is set while the user must change a password an operator set (see "Users and the forced password change" in the README): the session read is answered under the mark, so the login page can show the change form. email is the user's address when they hold one, with emailVerified saying whether they have proven it; emailHint, present when the user holds no address, is the address a directory asserted at a sign-in, offered as a prefill for the add-address step and trusted for nothing.
func (*Auth[S, U, Tx]) Device ¶
func (a *Auth[S, U, Tx]) Device() *DeviceHandlers
Device returns the device flow's handlers.
func (*Auth[S, U, Tx]) Email ¶
func (a *Auth[S, U, Tx]) Email() *EmailHandlers
Email returns the email address handlers. It panics on an Auth without mail, as a wiring mistake.
func (*Auth[S, U, Tx]) EndImpersonation ¶
func (a *Auth[S, U, Tx]) EndImpersonation() http.HandlerFunc
EndImpersonation ends the current impersonated session.
func (*Auth[S, U, Tx]) EnforceReadOnlyMask ¶
EnforceReadOnlyMask refuses writes from read-only impersonated sessions.
func (*Auth[S, U, Tx]) Invitation ¶
func (a *Auth[S, U, Tx]) Invitation() *InvitationHandlers
Invitation returns the invitation handlers.
func (*Auth[S, U, Tx]) Logout ¶
func (a *Auth[S, U, Tx]) Logout() http.HandlerFunc
Logout destroys the current session.
func (*Auth[S, U, Tx]) Methods ¶
func (a *Auth[S, U, Tx]) Methods(list *MethodList) http.HandlerFunc
Methods answers the login page with the sign-in methods it offers: for each listed method its name, the method behind it, how it starts (a form for the password method, a redirect for an external one), its label and its path, in the list's order, the pending sign-in routes when the list names them, and the password change route when the password method is listed. When the list names the invitation routes and the browser carries a live invitation (the cookie Invitation().Open() set), the invitation block also reports it under "standing": the address it was sent to, its tenant, when it stops being accepted, whether an account created from it takes the address as its username, and the names of the listed external registrations that could admit the address (see Invitation().Open()), so a page that arrives without the mailed link's token, as it does when an external sign-in was refused and sent it back, still shows the invitation and hides the methods that would refuse the person. A browser without the cookie, or whose invitation is no longer live, gets the block without it. The answer is public: route it beside the login routes, behind StartSession and before ValidateSession, and it needs no XSRF token.
{"methods": [{"name": "password", "method": "password", "kind": "password", "label": "Password", "path": "/api/user/password/login"},
{"name": "google", "method": "google", "kind": "redirect", "label": "Google", "path": "/api/user/google/login"}],
"pending": {"status": "/api/user/pending", "confirm": "/api/user/pending/confirm", "cancel": "/api/user/pending/cancel"},
"changePassword": "/api/user/password",
"invitation": {"open": "/api/user/invitation", "accept": "/api/user/invitation/accept", "signUp": "/api/user/invitation/sign-up",
"standing": {"email": "pat@lakeside.edu", "tenant": "", "expiresAt": "2026-10-31T20:00:00Z", "usernameIsEmail": false, "methods": ["google"]}}}
Methods is called where the routes are wired, after every method is registered, and panics on a wiring mistake, the way a registration does: an empty list, a method that is not registered on this Auth, a name listed twice, a method without a label or with a path that is not a canonical path in the application, a pending block with some of its paths, the password method without the password change route, or that route without the password method.
func (*Auth[S, U, Tx]) Pending ¶
func (a *Auth[S, U, Tx]) Pending() *PendingHandlers
Pending returns the pending-identity handlers.
func (*Auth[S, U, Tx]) RegisterExternal ¶
func (a *Auth[S, U, Tx]) RegisterExternal(reg *signin.Registration[Tx]) signin.Handlers
RegisterExternal registers a redirect-based sign-in method under its registration's name and returns its handlers. It implements signin.Core: the method packages (azure, google; workos under internal until v0.13.1) reach it through signin.Register, so an application never calls it directly. It panics on a registration rule, as refuseRegistration documents, when the registration has neither a standard account rule nor a custom one, when it names a standard rule that does not exist, and when a registration that synchronizes roles would stand beside another method, as refuseBeside documents.
func (*Auth[SessionData, UserData, Tx]) SetDirectoryAdmission ¶
func (a *Auth[SessionData, UserData, Tx]) SetDirectoryAdmission(reader signin.DirectoryReader[Tx], roles signin.UserRoleManager, hook DirectorySeatedHook[Tx])
SetDirectoryAdmission sets what a tenanted application gives a first sign-in through a directory by a person no user was created for: reader, which reads every tenant's declaration of the directory the identity came through (signin.DirectoryReader); roles, the role store the person's memberships are read from (signin.UserRoleManager, the access library's user manager the tenant policy reads too); and hook, which seats the person with the default seats the declarations name. With them the standard account rules ask the tenants first: a directory some tenant declares belongs to that tenant, and its declaration decides before the registration's own rule. A person who already holds a membership under the sign-in name in a declaring tenant, or as the application's staff, is that tenant's person and is admitted; a default seat admits a stranger with it; and a declaration naming none refuses a stranger by invitation only (invitation_only, unless the sign-in carries an invitation), with no account created. A directory no tenant declares falls to the registration's rule as without them. Set the three after NewAuth and before serving the first request; a nil reader, roles or hook, a second call, or a call once the Auth is in use is a wiring mistake and panics, as SetSignInPolicy does.
func (*Auth[SessionData, UserData, Tx]) SetInvitationAccepted ¶
func (a *Auth[SessionData, UserData, Tx]) SetInvitationAccepted(hook InvitationAcceptedHook[Tx])
SetInvitationAccepted sets the application's invitation acceptor, the hook that grants what an invitation names when it is accepted. An Auth that sends invitations (AuthAPI.Invite) needs one, or an acceptance grants nothing. Set it after NewAuth and before serving the first request; a nil hook, a second hook, or a hook set once the Auth is in use is a wiring mistake and panics, as SetSignInPolicy does.
func (*Auth[SessionData, UserData, Tx]) SetSignInPolicy ¶
SetSignInPolicy sets the application's sign-in rule: asked once a sign-in's user is known and before any session exists, for every sign-in method and for a session the application starts for a user it authenticated itself (AuthAPI.StartAuthenticatedSession), with signin.Allow, signin.Deny or signin.RequireMFA. Without a policy the library's own checks decide. Set it after NewAuth and before serving the first request; a nil policy, a second policy, or a policy set once the Auth is in use is a wiring mistake and panics, as a misregistered sign-in method does.
func (*Auth[SessionData, UserData, Tx]) SetSignedInHook ¶
func (a *Auth[SessionData, UserData, Tx]) SetSignedInHook(hook SignedInHook)
SetSignedInHook sets the application's after-sign-in hook, called once for every session a sign-in establishes, whatever the method, after the transaction that inserted it has committed, with the user and the sign-in's events; never for a refusal or a sign-in held for confirmation or MFA. An error from the hook is logged and the session stands. Set it after NewAuth and before serving the first request; a nil hook, a second hook, or a hook set once the Auth is in use is a wiring mistake and panics, as SetSignInPolicy does.
func (*Auth[SessionData, UserData, Tx]) SetUserRenamed ¶
func (a *Auth[SessionData, UserData, Tx]) SetUserRenamed(hook UserRenamedHook)
SetUserRenamed sets the hook a rename the library performs is reported to. An application whose password method declares UsernameIsEmail and that keys memberships by username needs one. Set it after NewAuth and before serving the first request; a nil hook, a second hook, or a hook set once the Auth is in use panics.
func (*Auth[S, U, Tx]) SetXSRFToken ¶
SetXSRFToken sets the XSRF token.
func (*Auth[S, U, Tx]) SignUp ¶
func (a *Auth[S, U, Tx]) SignUp() *SignUpHandlers
SignUp returns the sign-up handlers. It panics on an Auth without mail, as a wiring mistake; whether sign-up is offered is the password method's (OpenSignUp), checked as each request arrives.
func (*Auth[S, U, Tx]) StartSession ¶
StartSession restores or initializes the session. It also makes the browser's pending identity, if any, available to the Pending handlers and the AuthAPI pending methods, and the invitation and the trusted device the browser carries to the sign-in.
func (*Auth[S, U, Tx]) ValidateSession ¶
ValidateSession validates the session and loads its user by UserId. A session with no user, or whose user is missing or disabled, is refused with 401. The user is available through sessioninfo.UserFromCtx. A foreign actor's role-principal impersonation has no user and carries only its username. A user who must change a password an operator set is refused with 403 and {"message", "code": "password_change_required"} until the change: route the password change, the session read and the logout outside this middleware, since they validate on their own and are what the user reaches meanwhile. An impersonated session is not held to the mark.
type AuthAPI ¶
type AuthAPI[SessionData, UserData, Tx any] struct { // contains filtered or unexported fields }
AuthAPI provides programmatic access to an Auth session.
func (*AuthAPI[S, U, Tx]) ActivateSessionUser ¶
ActivateSessionUser enables a user.
func (*AuthAPI[S, U, Tx]) ActiveImpersonations ¶
func (p *AuthAPI[S, U, Tx]) ActiveImpersonations(ctx context.Context, q *ImpersonationQuery) ([]*sessioninfo.Impersonation, error)
ActiveImpersonations lists active impersonations matching q.
func (*AuthAPI[S, U, Tx]) ApproveDevice ¶
func (p *AuthAPI[S, U, Tx]) ApproveDevice(ctx context.Context, userID impulse.UUID, userCode string) error
ApproveDevice records that userID approved the device authorization the person's code names; the client's next poll receives the pair as that person. A code that names no pending authorization is NotFound, so one decision stands.
func (*AuthAPI[S, U, Tx]) ChangeSessionUserPassword ¶
func (p *AuthAPI[S, U, Tx]) ChangeSessionUserPassword(ctx context.Context, w http.ResponseWriter, userID impulse.UUID, req *ChangeSessionUserPasswordRequest) error
ChangeSessionUserPassword changes a user's password to one the user chose and regenerates its session.
The old password must match and the new one must differ from it (BadRequest otherwise). The password change mark is cleared, every session of the user is destroyed, by UserId, and the caller continues in a new session (ReasonRegeneration) that records a password event.
func (*AuthAPI[S, U, Tx]) ChangeSessionUserUsername ¶
func (p *AuthAPI[S, U, Tx]) ChangeSessionUserUsername(ctx context.Context, userID impulse.UUID, username string) error
ChangeSessionUserUsername changes a user's username, and atomically the username on its live sessions.
func (*AuthAPI[S, U, Tx]) CompletePending ¶
func (p *AuthAPI[S, U, Tx]) CompletePending(ctx context.Context, w http.ResponseWriter, stepUp ...sessioninfo.AuthEvent) (impulse.UUID, error)
CompletePending finishes a pending identity after the application's MFA step. It records the step-up events, links the identity if needed, starts the session, and regenerates the session ID.
The pending identity must wait for MFA (Conflict otherwise). It is consumed first, so it completes once: a second completion finds it expired. The user is resolved again and must be the one the identity waited on, and the sign-in policy is asked again with the sign-in's events and stepUp on the request: a RequireMFA those events satisfy proceeds, a Deny refuses the completion (no session; the pending identity is consumed), and a RequireMFA for a factor the person did not give holds the sign-in again. The session records the sign-in's events followed by stepUp. If the sign-in must wait again (the resolver now asks for a confirmation, or the policy for another factor), the error is a *signin.PendingSignInError and the pending identity is replaced.
func (*AuthAPI[S, U, Tx]) ConfirmPendingWithPassword ¶
func (p *AuthAPI[S, U, Tx]) ConfirmPendingWithPassword(ctx context.Context, w http.ResponseWriter, password string) (impulse.UUID, error)
ConfirmPendingWithPassword checks the password of the pending identity's user, links the identity, calls the IdentityLinked hook, and starts the session.
The pending identity must wait for a password confirmation (Conflict otherwise). A wrong password is Unauthorized and leaves the pending identity in place; the right one consumes it. The check is limited as a login's is, under the user's name: a wrong password counts, and a name whose attempts reached the limit is refused with RefusedTooManyAttempts and the wait before the password is hashed. The session records the sign-in's event and a link-confirmation event. If the sign-in policy requires MFA after the link, no session starts. The error is then a *signin.PendingSignInError with reason PendingMFA, and a new pending identity waits for MFA (see CompletePending).
func (*AuthAPI[S, U, Tx]) CreateApplicationToken ¶
func (p *AuthAPI[S, U, Tx]) CreateApplicationToken(ctx context.Context, req *ApplicationTokenRequest) (*IssuedToken, error)
CreateApplicationToken issues an application token for req: the secret is returned this once, and the store keeps its hash. The outlet must be registered (RegisterMachineOutlet), the name set and at most 200 characters, the lifetime at most the Auth's application token lifetime, and the user there and enabled; otherwise the request is refused with 400, or 404 for an unknown user.
func (*AuthAPI[S, U, Tx]) CreateSessionUser ¶
func (p *AuthAPI[S, U, Tx]) CreateSessionUser(ctx context.Context, req *CreateUserRequest, customData ...*U) (impulse.UUID, error)
CreateSessionUser creates a user. A nil req.Password creates a password-less user. req.PasswordChangeRequired marks the password as one an operator set, which the user changes before anything else is served; a user without a password has nothing to change, so the mark without a password is a BadRequest. req.Email, when given, is written unverified and reserves the address; one another user holds is a Conflict.
func (*AuthAPI[S, U, Tx]) CustomData ¶
CustomData returns the current session's custom data.
func (*AuthAPI[S, U, Tx]) CustomUserData ¶
CustomUserData returns a user's custom user data.
func (*AuthAPI[S, U, Tx]) DeactivateSessionUser ¶
DeactivateSessionUser disables a user and destroys its sessions. The caller must guard against self-deactivation.
func (*AuthAPI[S, U, Tx]) DeleteSessionUser ¶
DeleteSessionUser deletes a user with its identity links and sessions. The sessions are destroyed first, by UserId, so a failed delete leaves no live session behind. The caller must guard against self-deletion.
func (*AuthAPI[S, U, Tx]) DenyDevice ¶
DenyDevice records that the person denied the device authorization their code names; the client's next poll is told so. A code that names no pending authorization is NotFound.
func (*AuthAPI[S, U, Tx]) DestroyImpersonatedSession ¶
func (p *AuthAPI[S, U, Tx]) DestroyImpersonatedSession(ctx context.Context, sessionID impulse.UUID) error
DestroyImpersonatedSession expires one impersonated session.
func (*AuthAPI[S, U, Tx]) DestroyImpersonatedSessions ¶
DestroyImpersonatedSessions expires every impersonated session started by actor.
func (*AuthAPI[S, U, Tx]) DestroyUserSessions ¶
DestroyUserSessions expires every session of a user.
func (*AuthAPI[S, U, Tx]) EndImpersonation ¶
func (p *AuthAPI[S, U, Tx]) EndImpersonation(ctx context.Context, w http.ResponseWriter) (restored bool, err error)
EndImpersonation ends the current impersonated session, restoring the actor's session when possible.
func (*AuthAPI[S, U, Tx]) EnrollEmail ¶
EnrollEmail mails the code to email for a pending identity whose user holds no address; the address is written on the user, verified, when the code is entered. A user who holds an address is refused (Conflict). An address another account holds is told so by mail, and the call returns as if sent. See SendEmailCode.
func (*AuthAPI[S, U, Tx]) ForgetTrustedDevice ¶
ForgetTrustedDevice forgets the browser of the current request as a trusted device of the session's user: their device is revoked and their entry taken out of the cookie, so their next sign-in from it asks for the factor; the other people the browser was remembered for keep theirs. It reads the session StartSession validated, and a browser that is no trusted device of the user is left as it is.
func (*AuthAPI[S, U, Tx]) HashPassword ¶ added in v0.3.0
HashPassword hashes a password with the password method's hasher and answers the hash as the users table's PasswordHash column holds it. It is for a caller that writes the column in a transaction of its own (the generated user management, which sets a temporary password beside its other writes); the session library's own writers (ResetSessionUserPassword, CreateSessionUser) hash for themselves. An empty password is refused: no password is an absent hash, never the hash of nothing.
func (*AuthAPI[S, U, Tx]) Identities ¶
func (p *AuthAPI[S, U, Tx]) Identities(ctx context.Context, userID impulse.UUID) ([]*sessionstorage.SessionIdentity, error)
Identities lists a user's linked external identities.
func (*AuthAPI[S, U, Tx]) Invitations ¶
func (p *AuthAPI[S, U, Tx]) Invitations(ctx context.Context) ([]*sessioninfo.Invitation, error)
Invitations lists the invitations that stand: sent, not accepted, not revoked and not expired, oldest first.
func (*AuthAPI[S, U, Tx]) Invite ¶
func (p *AuthAPI[S, U, Tx]) Invite(ctx context.Context, req *InvitationRequest) (*sessioninfo.Invitation, error)
Invite sends an invitation to req.Email: a link to the login page that stands for MailSettings.InvitationTimeout, which whoever follows it accepts by signing in or signing up. The request is the same whether an account holds the address or not; only the invitee's path differs, and the caller does not learn which. An address that no sign-in method the login page offers could admit (an address outside the Google Workspaces a registration names, say, with no password method offered) is refused with a message naming its domain, and nothing is stored or mailed, so the sender learns now what the invitee would learn at the sign-in. The invitation is returned as stored; a message that could not be sent is an error and the invitation is withdrawn. It needs mail (WithMail).
func (*AuthAPI[S, U, Tx]) PendingDevice ¶
func (p *AuthAPI[S, U, Tx]) PendingDevice(ctx context.Context, userCode string) (*sessionstorage.DeviceCode, error)
PendingDevice returns the device authorization the person's code names while it waits for their decision, its hash left out, so the approval page can say which client asks for which outlet. A code that names no pending authorization is NotFound.
func (*AuthAPI[S, U, Tx]) PendingIdentity ¶
func (p *AuthAPI[S, U, Tx]) PendingIdentity(ctx context.Context) (*sessioninfo.PendingIdentity, error)
PendingIdentity returns the pending identity of the current request, or a NotFound error. An expired one is a sessioninfo.RefusedPendingExpired refusal. It reads the pending identity StartSession found, so the route must run behind StartSession.
func (*AuthAPI[S, U, Tx]) PrepareInvitation ¶ added in v0.3.0
func (p *AuthAPI[S, U, Tx]) PrepareInvitation(ctx context.Context, req *InvitationRequest) (PreparedInvitation, error)
PrepareInvitation checks and makes an invitation to req.Email without storing or mailing it: the checks Invite makes (the Auth sends mail, the address is one, and a sign-in method the login page offers could admit it), the token and its hash, and the time the link stands for (MailSettings.InvitationTimeout). The caller stores the row (PreparedInvitation.Row) in a transaction of its own and, once that has committed, mails the link (PreparedInvitation.Send). Invite is the two in the Auth's own storage.
func (*AuthAPI[S, U, Tx]) RedeemDeviceCode ¶
func (p *AuthAPI[S, U, Tx]) RedeemDeviceCode(ctx context.Context, deviceCode string) (*TokenPair, sessionstorage.DeviceCodeStatus, error)
RedeemDeviceCode is the client's poll of its device authorization: the pair once the person approved it, with status DeviceApproved, and once only; otherwise no pair and the status, DevicePending while the person has not decided, DeviceSlowDown when the client polled before the interval passed, DeviceDenied, or DeviceExpired. A device code that is unknown or was redeemed already is NotFound.
func (*AuthAPI[S, U, Tx]) RefreshTokens ¶
func (p *AuthAPI[S, U, Tx]) RefreshTokens(ctx context.Context, refreshToken string) (*TokenPair, error)
RefreshTokens exchanges a refresh token for the next pair: the one presented is revoked and the pair is issued in its family, for its person, outlet and client. A token that is not a live refresh token is NotFound. A refresh token presented again after its exchange is a reuse: the whole family is revoked, so the client that holds the current pair loses it too, and the error is sessionstorage.ErrTokenReuse under an Unauthorized refusal.
func (*AuthAPI[S, U, Tx]) ResetFactors ¶
ResetFactors is an administrator's reset of a user's second factor: every browser the person asked to be remembered is forgotten, so their next sign-in from any of them asks for the factor. The email code itself has nothing to reset: a person who lost their mailbox is given a new address (SetSessionUserEmail), unverified, and the next code proves it. Live sessions are not touched; DestroyUserSessions ends them.
func (*AuthAPI[S, U, Tx]) ResetSessionUserPassword ¶
func (p *AuthAPI[S, U, Tx]) ResetSessionUserPassword(ctx context.Context, userID impulse.UUID, temporary string) error
ResetSessionUserPassword sets a temporary password an operator chose: the user must change it before anything else is served (SessionUser.PasswordChangeRequired; see "Users and the forced password change" in the README), its sessions are destroyed and the name's sign-in attempts are reset.
func (*AuthAPI[S, U, Tx]) RevokeInvitation ¶
RevokeInvitation withdraws an invitation that stands; its link is then dead. One that no longer stands is NotFound.
func (*AuthAPI[S, U, Tx]) RevokeToken ¶
RevokeToken revokes the live token id of userID: an application token alone, or a device grant's token with its family. A token that is not live, or not the user's, is NotFound.
func (*AuthAPI[S, U, Tx]) RevokeUserTokens ¶
RevokeUserTokens revokes every live token of a person, for example when an operator takes their access away.
func (*AuthAPI[S, U, Tx]) SendEmailCode ¶
func (p *AuthAPI[S, U, Tx]) SendEmailCode(ctx context.Context) (codeEmail string, expiresAt time.Time, err error)
SendEmailCode mails the pending identity's user a one-time code for the second factor, to the address the user holds, replacing a code standing, and returns the masked address and when the code stops being accepted. The pending identity must wait for MFA and the policy accept the email code (Conflict otherwise), and the user must hold an address (Conflict: EnrollEmail takes one). It reads the pending identity StartSession found, and needs mail (WithMail).
func (*AuthAPI[S, U, Tx]) SetSessionUserEmail ¶
func (p *AuthAPI[S, U, Tx]) SetSessionUserEmail(ctx context.Context, userID impulse.UUID, email *string) error
SetSessionUserEmail puts an address on a user by hand, unverified, or takes it off (nil): an operator's entry for an invitation or a migration. The entry reserves the address: one another user holds, verified or not, is a Conflict, and a sign-up with it is pointed at this account by mail. The address is trusted for nothing until the person verifies it. When the password method declares the username as the email address the entry is refused (Conflict): the address is the username, set at creation and changed through a verified link.
func (*AuthAPI[S, U, Tx]) SetSessionUserPassword ¶
func (p *AuthAPI[S, U, Tx]) SetSessionUserPassword(ctx context.Context, userID impulse.UUID, password string) error
SetSessionUserPassword sets a password the user chose, without the old one: the end of a flow of the application's own that proved who they are (a reset link, an enrollment). The password change mark is cleared, the user's sessions are destroyed and the name's sign-in attempts are reset. A password an operator chose is ResetSessionUserPassword.
func (*AuthAPI[S, U, Tx]) StartAuthenticatedSession ¶
func (p *AuthAPI[S, U, Tx]) StartAuthenticatedSession(ctx context.Context, w http.ResponseWriter, userID impulse.UUID, events []sessioninfo.AuthEvent, customData ...*S) (impulse.UUID, error)
StartAuthenticatedSession starts a session for an existing user the application authenticated itself, recording how in events, which must name at least one method: a sign-up that just created the user, a factor the application ran on its own. It is decided like a login: the sign-in policy, when one is set, answers with the request's ReasonExternalAuth, and the library refuses a missing or disabled user. An Allow establishes the session under a new session ID; a Deny is a refusal (sessioninfo.LoginRefusal); a RequireMFA holds the sign-in as the browser's pending identity and returns a *signin.PendingSignInError, as CompletePending does, for CompletePending to finish. There is no session start that skips the policy: a support session is StartImpersonatedSession.
An event with a zero At records the session's creation time. Optional customData (at most one *S) is written atomically with the session insert, and the custom session data resolver is not called for it; without it the resolver receives ReasonExternalAuth.
func (*AuthAPI[S, U, Tx]) StartDeviceAuthorization ¶
func (p *AuthAPI[S, U, Tx]) StartDeviceAuthorization(ctx context.Context, req *DeviceAuthorizationRequest) (*DeviceAuthorization, error)
StartDeviceAuthorization starts a device authorization for req: the client shows the person the user code and the verification URI, and polls RedeemDeviceCode with the device code until the person decides. The client id must be set and the outlet registered, else 400.
func (*AuthAPI[S, U, Tx]) StartImpersonatedSession ¶
func (p *AuthAPI[S, U, Tx]) StartImpersonatedSession(ctx context.Context, w http.ResponseWriter, req *ImpersonationRequest, customData ...*S) (impulse.UUID, error)
StartImpersonatedSession starts an impersonated session, with the same semantics as the other session types. A user principal resolves against the users, as on PasswordAuth.
A user principal's session belongs to the impersonated user (SessionData.UserID). A role principal's session belongs to no user (null UserID). The session records an impersonation auth event whose connection is the actor.
func (*AuthAPI[S, U, Tx]) Tokens ¶
func (p *AuthAPI[S, U, Tx]) Tokens(ctx context.Context, userID impulse.UUID) ([]*sessionstorage.Token, error)
Tokens lists a person's live tokens, newest first, their hashes left out: their application tokens and the access and refresh tokens of their device grants.
func (*AuthAPI[S, U, Tx]) UnlinkIdentity ¶
UnlinkIdentity removes an identity link. The last means of sign-in of a password-less user is refused (sessionstorage.ErrLastSignInMethod, Conflict).
func (*AuthAPI[S, U, Tx]) UpdateCustomSessionData ¶
func (p *AuthAPI[S, U, Tx]) UpdateCustomSessionData(ctx context.Context, sessionID impulse.UUID, mutate func(data *S) error) error
UpdateCustomSessionData updates the custom session data of an active session.
func (*AuthAPI[S, U, Tx]) UpdateCustomUserData ¶
func (p *AuthAPI[S, U, Tx]) UpdateCustomUserData(ctx context.Context, userID impulse.UUID, mutate func(data *U) error) error
UpdateCustomUserData updates a user's custom user data.
func (*AuthAPI[S, U, Tx]) User ¶
func (p *AuthAPI[S, U, Tx]) User(ctx context.Context, userID impulse.UUID) (*sessionstorage.SessionUser, error)
User returns a user by ID, or a NotFound error.
func (*AuthAPI[S, U, Tx]) UserByEmail ¶
func (p *AuthAPI[S, U, Tx]) UserByEmail(ctx context.Context, email string) (*sessionstorage.SessionUser, error)
UserByEmail returns the user holding the address, verified or not, matched without regard to case, or a NotFound error.
func (*AuthAPI[S, U, Tx]) UserByUsername ¶
func (p *AuthAPI[S, U, Tx]) UserByUsername(ctx context.Context, username string) (*sessionstorage.SessionUser, error)
UserByUsername returns a user by username, matched without regard to case, or a NotFound error.
func (*AuthAPI[S, U, Tx]) Users ¶
func (p *AuthAPI[S, U, Tx]) Users(ctx context.Context) ([]*sessionstorage.SessionUser, error)
Users lists every user, by username. A user carries its username, whether it is disabled, its password hash (nil for a password-less user), whether it must change its password, when it was created and when it last signed in.
func (*AuthAPI[S, U, Tx]) ValidateCredentials ¶
func (p *AuthAPI[S, U, Tx]) ValidateCredentials(ctx context.Context, username, password string) (impulse.UUID, error)
ValidateCredentials checks a username and password and returns the user ID. A password-less user always fails validation. It starts no session and asks no sign-in policy. It is limited as the login is: a failure counts against the name, and a name whose attempts reached the limit is refused with a *sessioninfo.LoginRefusal carrying RefusedTooManyAttempts and the wait (sessioninfo.RetryAfterOf), before the user is looked up or the password hashed. The call has no client, so only the name is counted.
func (*AuthAPI[S, U, Tx]) ValidateSession ¶
ValidateSession validates the session cookie and stores the session data and its user (sessioninfo.UserFromCtx) in the context. Like Auth.ValidateSession, it refuses a session whose user is missing or disabled as unauthorized, and the request of a user who must change their password as forbidden, with a *sessioninfo.LoginRefusal carrying RefusedPasswordChangeRequired.
func (*AuthAPI[S, U, Tx]) VerifyEmailCode ¶
func (p *AuthAPI[S, U, Tx]) VerifyEmailCode(ctx context.Context, w http.ResponseWriter, code string, rememberDevice bool) (impulse.UUID, error)
VerifyEmailCode completes the pending identity when code is the one sent, as CompletePending does with an email-code event, and returns the session's id; with rememberDevice the browser is remembered as a trusted device of the user. A wrong code is a *sessioninfo.LoginRefusal carrying RefusedInvalidCode and leaves the code standing with one fewer attempt; a code that expired, was used or took its last attempt, or entered before one was sent, is one carrying RefusedCodeExpired. If the sign-in must wait again, the error is a *signin.PendingSignInError.
type AuthOption ¶
type AuthOption = sessioncore.AuthOption
AuthOption configures an Auth session: the cookie options, the session options and the Auth settings (WithIdentityLinked, WithPendingHook, WithPendingTimeout, WithPendingCookieName).
func WithDeviceCodeLifetime ¶
func WithDeviceCodeLifetime(lifetime, pollInterval time.Duration) AuthOption
WithDeviceCodeLifetime sets how long a device authorization waits for the person's decision, and the interval a client is held to between polls. (default: ten minutes, five seconds)
func WithDeviceCodesTableName ¶
func WithDeviceCodesTableName(name string) AuthOption
WithDeviceCodesTableName sets the name of the group's device codes table. (default: SessionDeviceCodes)
func WithDeviceVerificationURL ¶
func WithDeviceVerificationURL(path string) AuthOption
WithDeviceVerificationURL sets the path of the application's page where a signed-in person approves a device, as the device authorization tells the client (verification_uri). It must be a path in the application. (default: /device)
func WithEmailCodeTimeout ¶
func WithEmailCodeTimeout(d time.Duration) AuthOption
WithEmailCodeTimeout sets how long a mailed sign-in code is accepted. (default: 10m)
func WithFactorCodesTableName ¶
func WithFactorCodesTableName(name string) AuthOption
WithFactorCodesTableName sets the name of the group's factor codes table. (default: SessionFactorCodes)
func WithIdentitiesTableName ¶
func WithIdentitiesTableName(name string) AuthOption
WithIdentitiesTableName sets the name of the group's identities table, beside WithSessionTableName and WithUserTableName. (default: SessionIdentities)
func WithIdentityLinked ¶
func WithIdentityLinked(hook IdentityLinkedHook) AuthOption
WithIdentityLinked sets the hook called after every identity link, whether made by a pending identity's password confirmation or by the account rules during a sign-in (LinkIdentity or ProvisionUser). A resolver's link is committed before the sign-in policy runs, so it is reported even when the policy then denies the sign-in or holds it for MFA. An error from the hook is logged. The link and the sign-in stand.
func WithInvitationCookieName ¶
func WithInvitationCookieName(name string) AuthOption
WithInvitationCookieName sets the name of the cookie that carries an invitation the browser opened into the sign-in. (default: auth-invitation)
func WithMail ¶
func WithMail(sender mail.Sender, settings MailSettings) AuthOption
WithMail gives the Auth the means to send mail: sender delivers the messages (mail/workspace is the Google Workspace relay), and settings say as whom and where the links lead. It is needed by invitations (AuthAPI.Invite, Invitation()), the add-address step (Email()) and sign-up (SignUp(), with OpenSignUp on the password method); an Auth without it offers none of them. NewAuth refuses a nil sender, an empty application name and a login URL that is not an absolute http or https URL.
func WithMailLinksTableName ¶
func WithMailLinksTableName(name string) AuthOption
WithMailLinksTableName sets the name of the group's mail links table. (default: SessionMailLinks)
func WithPendingCookieName ¶
func WithPendingCookieName(name string) AuthOption
WithPendingCookieName sets the name of the pending cookie, which carries the opaque token of the browser's pending sign-in. (default: "auth-pending")
func WithPendingHook ¶
func WithPendingHook(hook PendingHook) AuthOption
WithPendingHook sets the hook called when PasswordMethod.Login(), an external method's Callback() or Pending().ConfirmWithPassword() holds a sign-in as a pending identity. The AuthAPI methods never call it. They return a *signin.PendingSignInError instead.
func WithPendingSignInsTableName ¶
func WithPendingSignInsTableName(name string) AuthOption
WithPendingSignInsTableName sets the name of the group's pending sign-ins table. (default: SessionPendingSignIns)
func WithPendingTimeout ¶
func WithPendingTimeout(d time.Duration) AuthOption
WithPendingTimeout sets how long a pending identity waits for confirmation or MFA. (default: 10m)
func WithSignInAttemptsTableName ¶
func WithSignInAttemptsTableName(name string) AuthOption
WithSignInAttemptsTableName sets the name of the group's sign-in attempts table. (default: SessionSignInAttempts)
func WithTokenLifetimes ¶
func WithTokenLifetimes(access, refresh, applicationMax time.Duration) AuthOption
WithTokenLifetimes sets how long the tokens live: an access token for access, a refresh token for refresh (at least access), and an application token for at most applicationMax, the default an application token is issued with. (default: an hour, thirty days, a year)
func WithTokensTableName ¶
func WithTokensTableName(name string) AuthOption
WithTokensTableName sets the name of the group's tokens table. (default: SessionTokens)
func WithTrustedDeviceCookieName ¶
func WithTrustedDeviceCookieName(name string) AuthOption
WithTrustedDeviceCookieName sets the name of the cookie that carries a trusted device's token. (default: "auth-trusted")
func WithTrustedDevicePeriod ¶
func WithTrustedDevicePeriod(d time.Duration) AuthOption
WithTrustedDevicePeriod sets how long a browser the person asked to be remembered after a second factor stands in for it. (default: 30 days)
func WithTrustedDevicesTableName ¶
func WithTrustedDevicesTableName(name string) AuthOption
WithTrustedDevicesTableName sets the name of the group's trusted devices table. (default: SessionTrustedDevices)
type BaseSessionOption ¶
type BaseSessionOption = sessioncore.BaseSessionOption
BaseSessionOption configures the session itself. It is an option of every session type.
func WithImpersonationAudit ¶
func WithImpersonationAudit(hook ImpersonationAuditHook) BaseSessionOption
WithImpersonationAudit registers the hook that receives impersonation lifecycle events (see ImpersonationAuditHook). Events are logged with the canonical evidence attributes whether or not a hook is registered.
func WithImpersonationTimeout ¶
func WithImpersonationTimeout(d time.Duration) BaseSessionOption
WithImpersonationTimeout sets the hard cap on an impersonated session's lifetime. The cap is absolute: it is fixed when the session is established and idle-activity renewal never extends past it. The idle session timeout applies independently. The default is one hour.
func WithLogHandler ¶
func WithLogHandler(l LogHandler) BaseSessionOption
WithLogHandler sets the LogHandler. (default: httpio.Log)
func WithPrincipalResolver ¶
func WithPrincipalResolver(resolve PrincipalResolver) BaseSessionOption
WithPrincipalResolver installs the resolver that chooses each validated request's authorization subject (sessioninfo.PrincipalFromCtx). It is the seam for the narrow case of a session whose subject genuinely is not a user — a service or API-key session acting as the role bound to its credential, or membership held in an external system and read live — without an impersonation record and without storing anything: the choice is made per request at validation time. It is not for a role snapshotted into custom session data, and not for a user choosing a role for one session (that is an impersonation record: evidenced, capped, revocable). See the README, "Choosing the principal".
The resolver runs for ordinary sessions and for user-principal impersonations (so an impersonated user's session acts as that user would); a role-principal impersonation already names its subject and skips it. When the resolver changes the principal the choice is stamped on the request's log entry and trace span as principal.kind and principal (sessioninfo.AttrPrincipalKind, sessioninfo.AttrPrincipal).
func WithSessionTableName ¶
func WithSessionTableName(name string) BaseSessionOption
WithSessionTableName sets the name of the session table. (default: Sessions) A name that is not a plain identifier (a letter or underscore, then up to 127 letters, digits or underscores) is refused by the session type's constructor, as every table-name option's is.
func WithSessionTimeout ¶
func WithSessionTimeout(d time.Duration) BaseSessionOption
WithSessionTimeout sets the session timeout. (default: 10m)
func WithUserTableName ¶
func WithUserTableName(name string) BaseSessionOption
WithUserTableName sets the name of the user table. (default: SessionUsers)
type ChangeSessionUserPasswordRequest ¶
ChangeSessionUserPasswordRequest takes in the user information for changing a SessionUser password
type CookieOption ¶
type CookieOption = sessioncore.CookieOption
CookieOption configures the session cookie client. It is an option of every session type.
func WithCookieDomain ¶
func WithCookieDomain(domain string) CookieOption
WithCookieDomain sets the domain for the session cookie.
func WithCookieName ¶
func WithCookieName(name string) CookieOption
WithCookieName sets the cookie name for the session cookie.
func WithXSRFCookieName ¶
func WithXSRFCookieName(name string) CookieOption
WithXSRFCookieName sets the cookie name for the XSRF cookie.
func WithXSRFHeaderName ¶
func WithXSRFHeaderName(name string) CookieOption
WithXSRFHeaderName sets the header name for the XSRF header.
type CreateUserRequest ¶
type CreateUserRequest struct {
Username string `json:"username"`
Password *string `json:"password"`
Disabled bool `json:"disabled"`
PasswordChangeRequired bool `json:"passwordChangeRequired"`
// Email is the user's email address as an operator enters it, unverified: it
// reserves the address, and a link may be sent to it. Nil for none. When the
// username is the address (UsernameIsEmail) it is nil or the username.
Email *string `json:"email"`
}
CreateUserRequest takes in the user information for creating a new SessionUser. A nil Password creates a password-less user. PasswordChangeRequired marks the password as one an operator set: the user changes it before anything else is served (see the README's "Users and the forced password change"); it needs a Password. Email is the address the operator enters, unverified (see "Users and their email address").
type DeviceAuthorization ¶
type DeviceAuthorization struct {
DeviceCode string
UserCode string
VerificationURI string
VerificationURIComplete string
ExpiresIn time.Duration
Interval time.Duration
}
DeviceAuthorization is what a client is told when it starts a device authorization (RFC 8628, 3.2): the device code it polls with, the user code the person types, the application's page to type it at, that page with the code already in, how long the authorization waits, and the interval between polls.
type DeviceAuthorizationRequest ¶
type DeviceAuthorizationRequest struct {
// ClientID names the client, as the person is told and the grant records.
ClientID string
// Outlet is the registered machine outlet the grant's tokens are for.
Outlet string
}
DeviceAuthorizationRequest is what a command-line client asks for when it starts a device authorization.
type DeviceHandlers ¶
type DeviceHandlers struct {
// contains filtered or unexported fields
}
DeviceHandlers are the HTTP handlers of the device flow.
func (*DeviceHandlers) Approve ¶
func (h *DeviceHandlers) Approve() http.HandlerFunc
Approve accepts {"userCode"} from the signed-in person and approves the client as them; the client's next poll receives its tokens. A code that names no pending authorization is 404. Route it behind ValidateSession and ValidateXSRFToken.
func (*DeviceHandlers) Authorize ¶
func (h *DeviceHandlers) Authorize() http.HandlerFunc
Authorize is the device authorization endpoint (RFC 8628, 3.1): the client posts client_id and outlet, form-encoded or as JSON, and is answered {"device_code", "user_code", "verification_uri", "verification_uri_complete", "expires_in", "interval"}. An outlet that is not registered, or a missing client id, is 400 {"error": "invalid_request", "error_description"}. Route it outside ValidateSession and ValidateXSRFToken: the client has no session.
func (*DeviceHandlers) Deny ¶
func (h *DeviceHandlers) Deny() http.HandlerFunc
Deny accepts {"userCode"} from the signed-in person and denies the client. A code that names no pending authorization is 404. Route it behind ValidateSession and ValidateXSRFToken.
func (*DeviceHandlers) Lookup ¶
func (h *DeviceHandlers) Lookup() http.HandlerFunc
Lookup answers the approval page's question about the code the person typed, ?userCode=, with {"clientId", "outlet", "expiresAt"} while the authorization waits, and 404 otherwise. Route it behind ValidateSession.
func (*DeviceHandlers) Token ¶
func (h *DeviceHandlers) Token() http.HandlerFunc
Token is the token endpoint (RFC 8628, 3.4; RFC 6749, 5): the client posts grant_type with device_code, or grant_type=refresh_token with refresh_token, and is answered {"access_token", "token_type": "Bearer", "expires_in", "refresh_token"}, or 400 {"error", "error_description"} with the RFC's codes: authorization_pending and slow_down while the person has not decided, access_denied, expired_token, invalid_grant for an unknown, redeemed, rotated or revoked token, and unsupported_grant_type. Route it outside ValidateSession and ValidateXSRFToken.
type DirectorySeatedHook ¶
type DirectorySeatedHook[Tx any] = func(ctx context.Context, tx Tx, userID impulse.UUID, username string, seats []signin.DirectorySeat) (committed func(ctx context.Context), err error)
DirectorySeatedHook is the application's half of a directory's default seat: it seats the user a first sign-in provisions, named by id and by username (the key an application's memberships are held under), with seats, the default seats of the directories the tenants declared for the identity's connection, inside the transaction that provisions the user, which it is handed: the account is made and seated together, or neither. A seat the invitation this sign-in consumes names too (the same role in the same tenant) is not among seats: InvitationAcceptedHook gives it, in the same transaction, and the two hooks never write one membership twice. The hook is not called for no seats. It is held to what InvitationAcceptedHook is: tx alone for its reads and writes, the user not readable in it, a committed function (nil for none) the library runs once the transaction has committed and before the sign-in policy decides, and an error that fails the transaction and ends the sign-in, so no account is left holding nothing.
type DisabledRoleSyncConfig ¶
type DisabledRoleSyncConfig = signin.DisabledRoleSyncConfig
DisabledRoleSyncConfig is the type returned by DisableRoleSync. See signin.DisabledRoleSyncConfig.
func DisableRoleSync ¶
func DisableRoleSync() DisabledRoleSyncConfig
DisableRoleSync disables role synchronization. See signin.DisableRoleSync.
type EmailHandlers ¶
type EmailHandlers struct {
// contains filtered or unexported fields
}
EmailHandlers are the HTTP handlers of a user's email address.
func (*EmailHandlers) Add ¶
func (h *EmailHandlers) Add() http.HandlerFunc
Add accepts {"email"} from the signed-in user and mails that address a link to confirm it; nothing is written until the link is followed. It answers {} whatever the address's state, so the screen reveals nothing: an address another account holds is told so by mail, and an address the user already holds verified gets no mail. An address that is not one is 400; a mailbox sent five links within fifteen minutes and using none is refused with too_many_emails and the wait. Route it behind ValidateSession.
func (*EmailHandlers) Verify ¶
func (h *EmailHandlers) Verify() http.HandlerFunc
Verify accepts {"token"}, the token the mailed link carried, and writes the address on the signed-in user as verified, replacing whatever they held; when the password method declares the username as the email address, the user is renamed to it with their live sessions. It answers {"email"}. A token whose link is not the user's own, or is no longer live, is 404; an address another user has taken meanwhile is 409. Route it behind ValidateSession.
type EmailRoutes ¶
EmailRoutes are the paths of the email address handlers, as a MethodList names them.
type IdentityLinkedHook ¶
type IdentityLinkedHook = func(ctx context.Context, userID impulse.UUID, identity *sessioninfo.Identity) error
IdentityLinkedHook is called after an external identity is linked to a user, for example to notify the user.
type ImpersonationAuditHook ¶
type ImpersonationAuditHook = func(ctx context.Context, event sessioninfo.ImpersonationEvent) error
ImpersonationAuditHook receives every lifecycle event of an impersonated session. For the Started event a returned error fails the establishment — the session is destroyed and the caller sees the error — so an application that must persist evidence before the session lives can guarantee it. Errors from other events are logged.
type ImpersonationQuery ¶
type ImpersonationQuery = sessioninfo.ImpersonationQuery
ImpersonationQuery narrows an ActiveImpersonations listing; see sessioninfo.ImpersonationQuery. The zero query lists every active impersonation.
type ImpersonationRequest ¶
type ImpersonationRequest = sessioncore.ImpersonationRequest
ImpersonationRequest describes the impersonated session to establish. It is a struct so future fields can be added without breaking callers.
type InvitationAcceptedHook ¶
type InvitationAcceptedHook[Tx any] = func(ctx context.Context, tx Tx, userID impulse.UUID, username string, inv *sessioninfo.Invitation) (committed func(ctx context.Context), err error)
InvitationAcceptedHook is the application's half of an invitation's acceptance: it gives what the invitation names, its roles in its tenant, to the user who accepted it, inside the transaction that consumes the invitation, which it is handed (tx, the storage's transaction type): the invitation is spent and its roles given together, or neither. It runs for every acceptance: the one a sign-in or a sign-up performs with the invitation the browser carries, and Invitation().Accept() for a person already signed in. The user is named by id and by username, the key an application's memberships are held under; a user the same transaction provisioned is buffered in it and is not readable until the commit, so the hook writes under the name it is given and looks nobody up.
The hook reads and writes through tx alone. The Spanner emulator allows one read-write transaction at a time, so a second transaction, or a read through another client, inside the hook waits on the transaction the hook runs in and never returns.
committed, nil for none, is work the library runs once that transaction has committed and before the sign-in policy decides: the word to a permission engine that its rows changed, so the policy sees the membership. Spanner runs a transaction's closure again when it aborts, so the hook may be called more than once for one acceptance; only the committed function of the call whose transaction committed is run, once. A hook that fails fails the transaction and ends the sign-in with its error: nothing is consumed, a user the sign-in would have provisioned is not created, and the invitation stands for the next attempt.
type InvitationHandlers ¶
type InvitationHandlers struct {
// contains filtered or unexported fields
}
InvitationHandlers are the HTTP handlers of invitations.
func (*InvitationHandlers) Accept ¶
func (h *InvitationHandlers) Accept() http.HandlerFunc
Accept accepts the invitation the browser carries for the signed-in user: the invitation is consumed, the user's address is set from it when they hold no verified address, and the application's hook grants what it names, in one transaction. It answers {"accepted": true}; 404 when the browser carries no live invitation. Route it behind ValidateSession.
func (*InvitationHandlers) Open ¶
func (h *InvitationHandlers) Open() http.HandlerFunc
Open accepts {"token"}, the token the mailed link carried, and answers {"email", "tenant", "expiresAt", "signUp", "usernameIsEmail", "methods"}: the address the invitation was sent to, the tenant it seats the person in ("" for the application's global surface), when it stops being accepted, whether the person may create an account with a password here (the password method is registered), whether that account's username is the address, and the names of the listed external registrations that could admit the address (as the methods listing advertises them; empty when none could), so the page hides the methods that would refuse the person. It sets the invitation cookie, so the sign-in that follows carries the invitation. A token whose invitation is no longer live is 404. Route it behind StartSession and ValidateXSRFToken.
func (*InvitationHandlers) SignUp ¶
func (h *InvitationHandlers) SignUp() http.HandlerFunc
SignUp accepts {"password", "username"} and creates the invited person's account with a password, then signs them in and accepts the invitation: the address the invitation was sent to is the account's, verified. username is the address when the password method declares the username as the email address, and chosen otherwise. It answers as the password login does ({"mfaIsRequired"}); a taken username or address is 409, a password under eight characters 400, no password method or no live invitation 404. Route it beside the password login, behind ValidateXSRFToken.
type InvitationRequest ¶
type InvitationRequest struct {
// Email is the address to invite.
Email string
// Tenant is the tenant the invitation seats the person in, "" for the
// application's global surface.
Tenant string
// RoleNames are the roles the acceptance grants, as the application's hook
// understands them.
RoleNames []string
// InvitedBy is the user sending the invitation, null when unknown.
InvitedBy impulse.NullUUID
}
InvitationRequest is an invitation to send.
type InvitationRoutes ¶
InvitationRoutes are the paths of the invitation handlers, as a MethodList names them.
type InvitationRow ¶ added in v0.3.0
type InvitationRow struct {
// ID is the invitation's id.
ID impulse.UUID
// TokenHash is the hash the link's token is found by. The token itself is in the
// message alone; the hash is a secret of the table and is served nowhere.
TokenHash []byte
// Email is the invited address, bare.
Email string
// Tenant is the tenant the acceptance seats the person in, "" for the
// application's global surface, and RoleNames the roles it grants.
Tenant string
RoleNames []string
// InvitedBy is the user who sent the invitation, null when unknown.
InvitedBy impulse.NullUUID
// ExpiresAt is when the link stops being accepted.
ExpiresAt time.Time
}
InvitationRow is the row a prepared invitation is stored as, in the mail links table (Tables.MailLinks), for a caller that writes it in a transaction of its own. The caller writes every field to the column of its name (TokenHash as the bytes they are), Kind as sessionstorage.MailLinkInvitation, CreatedAt as the commit time, and leaves UserId and ConsumedAt null; Tenant is null for the application's global surface (""), and InvitedBy null when unknown. The row is what the sign-in reads when the link is followed, so a row written otherwise is an invitation nobody can accept.
type IssuedToken ¶
type IssuedToken struct {
Secret string
Token *sessionstorage.Token
}
IssuedToken is a token as it leaves the library, once: Secret is what the person or the client holds and is never read back, and Token is the row the store keeps, its hash left out.
type LogHandler ¶
type LogHandler = basesession.LogHandler
LogHandler defines the handler signature required for handling logs.
type MachineOutlet ¶
type MachineOutlet struct {
// contains filtered or unexported fields
}
MachineOutlet is a machine outlet registered on an Auth: the tokens the Auth issues for it are the credentials its requests carry.
func RegisterMachineOutlet ¶
func RegisterMachineOutlet(auth outletRegistry, name string) *MachineOutlet
RegisterMachineOutlet registers the machine outlet name on auth and returns it. Tokens are issued only for registered outlets, and a token is accepted only on the outlet it was issued for. Register every outlet after NewAuth and before serving the first request; a name that is empty or not an identifier of letters, digits, hyphens and underscores, a name registered twice, or an outlet registered once the Auth is in use is a wiring mistake and panics, as a misregistered sign-in method does.
func (*MachineOutlet) ValidateToken ¶
func (o *MachineOutlet) ValidateToken(next http.Handler) http.Handler
ValidateToken authenticates a request on the outlet by the bearer token it carries (Authorization: Bearer <token>) and binds it to the token's person the way ValidateSession binds a browser request to its user: the session read, the user (sessioninfo.UserFromCtx), the principal and the evidence are the token's, and sessioninfo.TokenFromCtx names the token. A request without a bearer token, or with one that is unknown, expired, revoked, not a bearer kind, issued for another outlet, or whose person is missing or disabled, is refused with 401 and a WWW-Authenticate challenge; a person who must change a password an operator set is refused with 403 and {"message", "code": "password_change_required"}, as everywhere. No cookie is read or written and no XSRF token is checked: a bearer token is nothing a browser sends on its own.
type MailSettings ¶
type MailSettings struct {
// Application is the application's name as the messages say it ("Harbor").
Application string
// LoginURL is the absolute URL of the application's login page
// (https://harbor.example.com/login), where every mailed link leads: with
// ?invitation=<token> for an invitation, ?verify=<token> for an address
// verification and ?signUp=<token> for a sign-up. The page posts the token to the
// matching route.
LoginURL string
// InvitationTimeout is how long an invitation stands; zero is seven days.
InvitationTimeout time.Duration
// LinkTimeout is how long a verification or sign-up link stands; zero is a day.
LinkTimeout time.Duration
}
MailSettings is how the Auth sends mail: through sender, as the application, with links to its login page.
type MethodList ¶
type MethodList struct {
// Methods are the methods the page offers, in the order it renders them. Each
// names a registration on the Auth; a method that is registered but not listed
// here is not offered.
Methods []AdvertisedMethod
// Pending are the paths of the pending sign-in handlers (Pending().Status(),
// ConfirmWithPassword() and Cancel()), all three or none. The page needs them once a
// sign-in waits for a confirmation or the application's MFA step.
Pending PendingRoutes
// ChangePassword is the path of the password method's ChangeUserPassword handler,
// which the page needs when a sign-in finds the user must change a password an
// operator set. It is required when the password method is listed, since every
// user an operator gives a password must change it, and refused when it is not.
ChangePassword string
// Invitation are the paths of the invitation handlers (Invitation().Open(),
// Accept() and SignUp()), or none. Open and Accept go together; SignUp is named
// when the password method is listed and refused when it is not.
Invitation InvitationRoutes
// Email are the paths of the email address handlers (Email().Add() and Verify()),
// both or none.
Email EmailRoutes
// SignUp are the paths of the sign-up handlers (SignUp().Start(), Open() and
// Complete()), all three or none; they need the password method listed and
// registered with OpenSignUp.
SignUp SignUpRoutes
}
MethodList is what an Auth tells its login page (Methods): the sign-in methods the page offers, each with the path the application mounted it at, and the pending sign-in routes. The application writes it where it wires the routes, so the paths the page is told are the paths the router serves.
type NoCustomData ¶
type NoCustomData = sessioncore.NoCustomData
NoCustomData is the custom data type of session types that do not use custom session data (the SessionData type parameter) or custom user data (the UserData type parameter). Instantiate with NoCustomData for each axis the application does not use, e.g. session.NewAuth[session.NoCustomData, session.NoCustomData](...).
type PasswordMethod ¶
type PasswordMethod struct {
// contains filtered or unexported fields
}
PasswordMethod holds the handlers of the username and password sign-in method.
func PasswordSignIn ¶
func PasswordSignIn(auth signInRegistry, options ...PasswordOption) *PasswordMethod
PasswordSignIn registers username and password sign-in on auth and returns its handlers. It takes the password options (HashAlgorithm, AutoUpgradeHashes, AttemptLimit, UsernameIsEmail, OpenSignUp); cookie and session options belong to NewAuth.
It panics when the method is already registered on auth, when auth has served a request, when it is given an option that is not a password option, or when the attempt limit is not at least one failure within a positive window and lock. The registration is named "password".
func (*PasswordMethod) ChangeUserPassword ¶
func (m *PasswordMethod) ChangeUserPassword() http.HandlerFunc
ChangeUserPassword accepts {"oldPassword", "newPassword"} and changes the signed-in user's password to one they chose: the old one must match and the new one differ (400 otherwise). The password change mark is cleared, every session of the user is destroyed and the caller continues in a new one. It is the one route a user who must change their password reaches, so it validates the session itself: route it beside the session read and the logout, outside ValidateSession and behind ValidateXSRFToken, and name its path to Methods (MethodList.ChangePassword).
func (*PasswordMethod) Login ¶
func (m *PasswordMethod) Login() http.HandlerFunc
Login accepts {"username", "password"}. On success it applies the sign-in policy and either starts the session or creates a pending identity for MFA. It answers {"mfaIsRequired": bool}, plus "redirectUrl" when a PendingHook chose one. A refusal is 401 with {"message", "code"}, where code is a sessioninfo.LoginRefusalCode.
type PasswordOption ¶
type PasswordOption = sessioncore.PasswordOption
PasswordOption configures the password method (PasswordSignIn): AutoUpgradeHashes, HashAlgorithm and AttemptLimit.
func AttemptLimit ¶
func AttemptLimit(failures int, window, lock time.Duration) PasswordOption
AttemptLimit sets how failed password attempts are limited: failures failed attempts on a name within window lock the name for lock, whether a user exists under the name or not, and an attempt during the lock is refused with too_many_attempts and the wait. The client's address and the login's XSRF cookie are each allowed ten times failures, across names, within window before they are locked for lock, and every attempt a client makes during a wait extends its own lock. A success, an MFA completion and a password change reset the name. (default: 5 failures within 15 minutes lock the name for 15 minutes) See "Attempt limiting and the after-sign-in hook" in the README.
func AutoUpgradeHashes ¶
func AutoUpgradeHashes(a bool) PasswordOption
AutoUpgradeHashes controls if password hashes will be auto upgraded (default: true)
func HashAlgorithm ¶
func HashAlgorithm(hasher securehash.HashAlgorithm) PasswordOption
HashAlgorithm controls hashing algrorithm (default: securehash.Argon2())
func OpenSignUp ¶
func OpenSignUp() PasswordOption
OpenSignUp declares, on the password method, that anyone may create an account: the person gives their address, follows the link mailed to it, and sets a password (SignUp handlers). Without it an account is created by an operator (CreateSessionUser) or by the person through an invitation. It needs mail (WithMail). (default: no sign-up)
func UsernameIsEmail ¶
func UsernameIsEmail() PasswordOption
UsernameIsEmail declares, on the password method, that the username is the user's email address: one value, which the users table derives from the username (see the README's "Users and their email address" for the DDL). The login page asks for the address, a sign-up's username is the address, renaming a user is refused, and a person who verifies a new address is renamed to it, with their live sessions. Without it the two are apart: the username is chosen, the address is added and verified separately, and sign-in is by username. (default: apart)
type PendingHandlers ¶
type PendingHandlers struct {
// contains filtered or unexported fields
}
PendingHandlers are the HTTP handlers for pending identities.
func (*PendingHandlers) Cancel ¶
func (h *PendingHandlers) Cancel() http.HandlerFunc
Cancel discards the pending identity.
func (*PendingHandlers) ConfirmWithPassword ¶
func (h *PendingHandlers) ConfirmWithPassword() http.HandlerFunc
ConfirmWithPassword accepts {"password"}. On success it links the pending identity to its user and starts the session. It answers {"mfaIsRequired": bool}. When the sign-in policy requires MFA after the link, the pending identity remains with reason "mfa", the PendingHook runs, and the application completes it with AuthAPI.CompletePending. A wrong password is 401 and leaves the pending identity.
func (*PendingHandlers) EnrollEmail ¶
func (h *PendingHandlers) EnrollEmail() http.HandlerFunc
EnrollEmail accepts {"email"} from a pending identity whose user holds no address, and mails that address the code as SendCode does; the address is written on the user, verified, when the code is entered. It answers as SendCode does, and 409 when the user already holds an address: the code goes there, and an administrator changes it. An address another account holds is answered as sent and told so by mail to that address, as the add-address step does, so the screen reveals nothing. Route it as SendCode.
func (*PendingHandlers) SendCode ¶
func (h *PendingHandlers) SendCode() http.HandlerFunc
SendCode mails the pending identity's user a one-time code for the second factor, to the address the user holds, and answers {"codeEmail", "codeSent", "codeExpiresAt"}: the masked address and when the code stops being accepted. A code already standing is replaced. It answers 409 when the pending identity does not wait for MFA, when the sign-in policy does not accept the email code, or when the user holds no address (the page then asks for one and posts it to EnrollEmail()); an address sent five codes within fifteen minutes and using none is refused with too_many_emails and the wait; a code that is used resets the count. Route it behind StartSession and ValidateXSRFToken; it panics at wiring on an Auth without mail.
func (*PendingHandlers) Status ¶
func (h *PendingHandlers) Status() http.HandlerFunc
Status returns {"reason", "email", "expiresAt", "returnUrl"[, "factors"]} for the current pending identity, and for one that waits for MFA and may take the library's email code, the code's state under "emailCode": the masked address the code goes to ("codeEmail"), whether one is standing ("codeSent", "codeExpiresAt") and whether the user must first give an address ("enrollEmail"); see "The second factor" in the README. It answers 404 when there is none, and 401 with {"message", "code": "pending_expired"} when it has expired.
func (*PendingHandlers) VerifyCode ¶
func (h *PendingHandlers) VerifyCode() http.HandlerFunc
VerifyCode accepts {"code", "rememberDevice"} and completes the pending identity when code is the one sent: the session starts under a new ID, recording the sign-in's events and an email-code event, and the address the code went to is written on the user verified when it was not. With rememberDevice the browser is remembered as a trusted device of the user for the trusted device period, so its next sign-ins skip the factor. It answers as the password login does: {"mfaIsRequired": false}, or the policy's next wait. A wrong code is 401 with {"code": "invalid_code"} and the code stands with one fewer attempt; a code entered while none stands, because none was sent or the one sent expired, was used or took its last attempt, is 401 with {"code": "code_expired"}, and the page asks for a new one. Route it as SendCode.
type PendingHook ¶
type PendingHook = func(ctx context.Context, w http.ResponseWriter, r *http.Request, pending *sessioninfo.PendingIdentity) (redirectURL string, err error)
PendingHook is called after a sign-in handler holds a sign-in as a pending identity, for example to send an MFA code or choose the next page. It runs after the pending identity is stored and its cookie set, and cannot change either.
The hook may write the response itself, and the handler then writes nothing more. Otherwise it returns where the browser goes: Callback() redirects there and the JSON handlers return it as "redirectUrl". An empty URL keeps the default. The URL must be the application's own, never built from request input.
An error discards the pending identity and fails the sign-in. See the README's "The redirect and response contract".
type PendingRoutes ¶
type PendingRoutes struct {
Status string
Confirm string
Cancel string
SendCode string
VerifyCode string
EnrollEmail string
}
PendingRoutes are the paths of the pending sign-in handlers, as a MethodList names them: Status, Confirm and Cancel together, and the email code's SendCode, VerifyCode and EnrollEmail together or not at all, which the page needs when a sign-in waits for the library's second factor (see "The second factor" in the README).
type Preauth ¶
type Preauth[SessionData any] struct { // contains filtered or unexported fields }
Preauth handles session management for pre-authentication scenarios, with custom session data typed as SessionData (caller-supplied at Login); use NoCustomData when custom session data is not used. Preauth is trust-the-caller with no user record, so it has no custom user data axis — durable per-user data needs a user anchor (password auth's SessionUsers, or the OIDC user anchor).
func NewPreauth ¶
func NewPreauth[SessionData any](storage sessionstorage.PreauthStore, cookieKey string, options ...PreauthOption) (*Preauth[SessionData], error)
NewPreauth creates a new Preauth for the custom session data struct type SessionData (use NoCustomData when custom session data is not used). The storage must carry a custom session data configuration built for the same SessionData; a mismatch is a construction error, as is any custom user data configuration — Preauth has no user record to anchor durable data to. Preauth custom session data is caller-supplied at Login (trust-the-caller); there is no resolver input source. cookieKey: A Base64-encoded string representing at least 32 bytes of cryptographically secure random data.
func (*Preauth[T]) API ¶
func (p *Preauth[T]) API() *PreauthAPI[T]
API provides programatic access to Preauth handler internals
func (*Preauth[T]) Authenticated ¶
func (p *Preauth[T]) Authenticated() http.HandlerFunc
Authenticated is the handler reports if the session is authenticated
func (*Preauth[T]) EndImpersonation ¶
func (p *Preauth[T]) EndImpersonation() http.HandlerFunc
EndImpersonation ends the impersonated session (record ended Released) and, for a local actor whose own session is still live, returns the browser to that session; the body's restored flag says whether it did. Route it inside the validated group. See the "Impersonated sessions" section of the README.
func (*Preauth[T]) EnforceReadOnlyMask ¶
EnforceReadOnlyMask refuses non-safe requests from a read-only impersonated session with 403 Forbidden, evidenced as a WriteBlocked event; every other request passes. Place it after ValidateSession. See the "Impersonated sessions" section of the README.
func (*Preauth[T]) Logout ¶
func (p *Preauth[T]) Logout() http.HandlerFunc
Logout destroys the current session
func (*Preauth[T]) SetXSRFToken ¶
SetXSRFToken sets the XSRF Token
func (*Preauth[T]) StartSession ¶
StartSession initializes a session by restoring it from a cookie, or if that fails, initializing a new session. The session cookie is then updated and the sessionID is inserted into the context.
func (*Preauth[T]) ValidateSession ¶
ValidateSession checks the sessionID in the database to validate that it has not expired and updates the last activity timestamp if it is still valid. StartSession handler must be called before calling ValidateSession
type PreauthAPI ¶
type PreauthAPI[SessionData any] struct { // contains filtered or unexported fields }
PreauthAPI provides programatic access to Preauth handler internals
func (*PreauthAPI[T]) ActiveImpersonations ¶
func (p *PreauthAPI[T]) ActiveImpersonations(ctx context.Context, q *ImpersonationQuery) ([]*sessioninfo.Impersonation, error)
ActiveImpersonations lists the impersonated sessions that are live right now, newest first — the admin surface's view of who is acting as whom. A session is active while its record has not ended, its hard cap has not passed, its session row is not expired, and it has seen activity within the idle session timeout. q narrows the listing by actor and/or principal; nil lists every active impersonation. It errors when the storage has no impersonation table.
func (*PreauthAPI[T]) Cookie ¶
func (p *PreauthAPI[T]) Cookie() *cookie.Client
Cookie returns the underlying cookie.Client
func (*PreauthAPI[T]) CustomData ¶
func (p *PreauthAPI[T]) CustomData(ctx context.Context) (T, error)
CustomData returns the strongly typed custom session data for the current session from the context. A session with no custom data row yields a zero-value T.
func (*PreauthAPI[T]) DestroyAllUserSessions ¶
func (p *PreauthAPI[T]) DestroyAllUserSessions(ctx context.Context, username string) error
DestroyAllUserSessions destroys all sessions for a given user
func (*PreauthAPI[T]) DestroyImpersonatedSession ¶
func (p *PreauthAPI[T]) DestroyImpersonatedSession(ctx context.Context, sessionID impulse.UUID) error
DestroyImpersonatedSession ends one live impersonated session — the operator's action on an ActiveImpersonations row: the session row is expired and the record ended with reason Revoked, in one transaction, so the next request on that session is refused as expired. A session that is not impersonated, or whose record has already ended, is left untouched. Who may revoke is the application's guard. It errors when the storage has no impersonation table.
func (*PreauthAPI[T]) DestroyImpersonatedSessions ¶
func (p *PreauthAPI[T]) DestroyImpersonatedSessions(ctx context.Context, actor string) error
DestroyImpersonatedSessions expires every live impersonated session established by actor and ends their records with reason Revoked — the offboarding and incident tool. It errors when the storage has no impersonation table.
func (*PreauthAPI[T]) EndImpersonation ¶
func (p *PreauthAPI[T]) EndImpersonation(ctx context.Context, w http.ResponseWriter) (restored bool, err error)
EndImpersonation ends the impersonated session in ctx with reason Released and, for a local actor whose own session is still live, gives the response that session's cookies so the actor is back in it without logging in; restored reports whether that happened. See EndImpersonation on the handler type and the "Impersonated sessions" section of the README.
func (*PreauthAPI[T]) Login ¶
func (p *PreauthAPI[T]) Login(ctx context.Context, w http.ResponseWriter, username string, customData ...*T) (impulse.UUID, error)
Login creates a new session for a pre-authenticated user.
Preauth is trust-the-caller: no user record is required or consulted, which makes it the right tool for stepping-stone sessions (e.g. MFA-pending) where identity is not yet fully established. For a full session backed by an existing user record after external authentication, use PasswordAuth's StartAuthenticatedSession instead.
Optional customData (at most one *T) is written atomically with the session insert — the session and its custom data row land together or not at all. The library does not validate the data beyond the custom session data configuration, which must be attached to the storage for customData to be accepted. See the "Custom session data" section of the README for the full lifecycle.
func (*PreauthAPI[T]) Logout ¶
func (p *PreauthAPI[T]) Logout(ctx context.Context) error
Logout destroys the current session. For an impersonated session the end is announced as an Ended event, as on every other session type.
func (*PreauthAPI[T]) StartImpersonatedSession ¶
func (p *PreauthAPI[T]) StartImpersonatedSession(ctx context.Context, w http.ResponseWriter, req *ImpersonationRequest, customData ...*T) (impulse.UUID, error)
StartImpersonatedSession establishes a session that operates as req.Principal on behalf of req.Actor; see AuthAPI.StartImpersonatedSession for the model.
Preauth has no user record, so a user principal is taken as given: the session's username is the principal's name and its user ID is zero, exactly as Login trusts the caller's username. Whether that user exists is the application's guard.
Establishment is refused when the storage has no impersonation table and when the calling context is itself an impersonated session (no chaining). Optional customData (at most one *T) follows Login's semantics.
func (*PreauthAPI[T]) StartSession ¶
func (p *PreauthAPI[T]) StartSession(ctx context.Context, w http.ResponseWriter, r *http.Request) (context.Context, error)
StartSession initializes a session by restoring it from a cookie, or if that fails, initializing a new session. The session cookie is then updated and the sessionID is inserted into the context.
func (*PreauthAPI[T]) UpdateCustomSessionData ¶
func (p *PreauthAPI[T]) UpdateCustomSessionData(ctx context.Context, sessionID impulse.UUID, mutate func(data *T) error) error
UpdateCustomSessionData updates the custom session data for an active session via a transactional read-modify-write: mutate receives the current row (zero-value T when no row exists), and the full row is written back; a mutate error aborts with nothing written. It is intended for genuine mid-session updates only — initial population belongs in the creation path (caller-supplied data on Login), which is atomic with the session insert. See the "Custom session data" section of the README for the full lifecycle.
func (*PreauthAPI[T]) ValidateSession ¶
ValidateSession checks the sessionID in the database to validate that it has not expired and updates the last activity timestamp if it is still valid. StartSession handler must be called before calling ValidateSession
type PreauthHandlers ¶
type PreauthHandlers interface {
basesession.Handlers
}
PreauthHandlers defines the interface for pre-authentication session handlers.
type PreauthOption ¶
type PreauthOption = sessioncore.PreauthOption
PreauthOption configures a Preauth session: the cookie options and the session options.
type PreparedInvitation ¶ added in v0.3.0
type PreparedInvitation interface {
// Row answers the row to store, the caller's own copy.
Row() *InvitationRow
// Send mails the invitation's link to its address. Call it once the row is
// committed. A message that could not be sent withdraws the invitation, in the
// Auth's own storage, so no link stands that nobody holds, and is the error; the
// caller reports that the mail did not go, and the invitation is sent again by
// inviting again.
Send(ctx context.Context) error
}
PreparedInvitation is an invitation checked and made, and neither stored nor mailed yet: the row to store, and the step that mails its link. The token, the message and the sender stay inside it. It is for a caller that stores the row in a transaction of its own beside other writes (the generated user management): the row is written there, and Send runs once that transaction has committed, since a message cannot be taken back if the commit fails. It is an interface so that code written over one is tested without an Auth; the Auth's is the only one that mails.
type PrincipalResolver ¶
type PrincipalResolver = func(ctx context.Context) (accesstypes.Principal, error)
PrincipalResolver chooses the authorization subject of a validated request. It runs inside session validation with the session in ctx — sessioninfo.FromCtx, the custom session data (sessioninfo.CustomDataFromCtx) and the impersonation record are all available — and returns the principal the request evaluates permissions against. Returning the zero Principal keeps the default (the impersonation record's principal, or the session user's own). An error fails the request as a server error, not an unauthorized one: the session is valid; the application could not decide what it acts as.
A resolver chooses which subject, never which grants: grants come from the permission store at check time. A resolver must therefore derive the subject from something live (the credential a machine session was established with, an external system read per request), never from role membership copied into the session at login — that freezes the user's role for the life of the session and defeats the store. Put membership in the permission store instead and let the default user principal apply.
type RoleSyncConfig ¶
type RoleSyncConfig = signin.RoleSyncConfig
RoleSyncConfig is the required role-synchronization slot of the Microsoft Entra ID method (azure.Config.RoleSync) and of the legacy OIDCAzure. See signin.RoleSyncConfig.
func RoleSync ¶
func RoleSync(manager UserRoleManager) RoleSyncConfig
RoleSync enables directory-driven role synchronization. See signin.RoleSync.
type SignUpHandlers ¶
type SignUpHandlers struct {
// contains filtered or unexported fields
}
SignUpHandlers are the HTTP handlers of sign-up.
func (*SignUpHandlers) Complete ¶
func (h *SignUpHandlers) Complete() http.HandlerFunc
Complete accepts {"token", "password", "username"}, creates the account with the address verified, and signs the person in, answering as the password login does ({"mfaIsRequired"}). username is the address when the password method declares the username as the email address, and chosen otherwise. A taken username or address is 409, a password under eight characters 400, a token whose link is no longer live 404. Route it beside the password login, behind ValidateXSRFToken.
func (*SignUpHandlers) Open ¶
func (h *SignUpHandlers) Open() http.HandlerFunc
Open accepts {"token"}, the token the mailed link carried, and answers {"email", "usernameIsEmail"}: the address, and whether the account's username is the address or the person chooses one. A token whose link is no longer live is 404.
func (*SignUpHandlers) Start ¶
func (h *SignUpHandlers) Start() http.HandlerFunc
Start accepts {"email"} and mails that address a link to finish the sign-up. It answers {} whatever the address's state, so the screen reveals nothing: an address an account already holds is told so by mail. An address that is not one is 400; a mailbox sent five links within fifteen minutes and using none is refused with too_many_emails and the wait; 404 when sign-up is not offered. Route it behind StartSession and ValidateXSRFToken.
type SignUpRoutes ¶
SignUpRoutes are the paths of the sign-up handlers, as a MethodList names them.
type SignedIn ¶
type SignedIn struct {
// SessionID is the new session's ID.
SessionID impulse.UUID
// UserID and Username are the user the session belongs to.
UserID impulse.UUID
Username string
// Reason is how the session came about: ReasonLogin for a password or external
// sign-in, ReasonExternalAuth for one the application started
// (StartAuthenticatedSession), ReasonStepUp for an MFA completion,
// ReasonIdentityLinked for a password confirmation.
Reason sessioninfo.NewSessionReason
// Events are the auth events the session recorded, the sign-in's method first.
Events []sessioninfo.AuthEvent
}
SignedIn is a session a sign-in established, as the SignedInHook receives it.
type SignedInHook ¶
SignedInHook is called once for every session a sign-in establishes, after the transaction that inserted it has committed: a password or external sign-in, a confirmation, an MFA completion, a session the application started. It is never called for a refused sign-in or one held as a pending identity. An error is logged and the session stands.
type Tables ¶ added in v0.3.0
type Tables struct {
// Sessions holds the sessions and Users the people who sign in.
Sessions string
Users string
// Identities holds the links between a user and the external identities a
// directory verified for them.
Identities string
// PendingSignIns holds the sign-ins that wait for a confirmation or a second
// factor, and SignInAttempts what the password method's attempt limiter counts.
PendingSignIns string
SignInAttempts string
// MailLinks holds the invitations, address verifications and sign-ups the Auth
// mails, FactorCodes the sign-in codes it mails, and TrustedDevices the browsers
// people asked to be remembered after a code.
MailLinks string
FactorCodes string
TrustedDevices string
// Tokens holds the bearer tokens the Auth issues for its machine outlets, and
// DeviceCodes the device authorizations command-line clients wait on.
Tokens string
DeviceCodes string
// AuthEvents holds how each session was authenticated, and Impersonations who
// established a view-as or act-as-role session; the storage attaches both
// (sessionstorage.NewAuthEventsTable, sessionstorage.NewImpersonationTable).
AuthEvents string
Impersonations string
}
Tables names the tables one Auth keeps, by what each holds. An application that runs several Auths in one database keeps each under a prefix of its own (TablesWithPrefix), and everything that must agree on the names reads them from here: the Auth's own construction, the application's migrations, and the code generator, which declares the management resources over the same tables.
func DefaultTables ¶ added in v0.3.0
func DefaultTables() Tables
DefaultTables answers the library's own names, the ones an Auth reads and writes when no option names another and the library's schema sets create.
func TablesWithPrefix ¶ added in v0.3.0
TablesWithPrefix answers the names of an Auth kept under prefix: the library's own name for each table, led by the prefix (Crew gives CrewSessions, CrewSessionUsers and so on). It is the one rule for the names of an Auth that shares its database with another, so the Auth's construction and whatever else names its tables cannot spell them two ways. A prefix that leaves a name no plain identifier is refused.
type TokenPair ¶
TokenPair is what a device grant or a refresh hands the client: the access token it presents on the outlet, how long that lives, and the refresh token it exchanges for the next pair.
type UserRenamedHook ¶
UserRenamedHook is told that a user's username changed by the library's own doing: under a password method declared UsernameIsEmail, the person who verifies a new address is renamed to it, live sessions included, as a rename does. An application that keys anything by the username, role memberships above all, moves it from the old name to the new here. The hook runs after the rename is written and outside any transaction; an error is logged and answered to the person as the verification having failed, with the address verified and the username changed, so the hook is written to be safe to run again (adding under the new name before removing under the old).
type UserRoleManager ¶
type UserRoleManager = signin.UserRoleManager
UserRoleManager is the role store a role-synchronizing sign-in reconciles through. See signin.UserRoleManager.
Source Files
¶
- auth.go
- auth_api.go
- auth_attempts.go
- auth_device.go
- auth_email.go
- auth_external.go
- auth_factor.go
- auth_invitation.go
- auth_mail.go
- auth_methods.go
- auth_methods_list.go
- auth_pending.go
- auth_signin.go
- auth_signup.go
- auth_tokens.go
- auth_tokens_api.go
- auth_tokens_handlers.go
- custom_data.go
- impersonation.go
- options.go
- preauth.go
- preauth_iface.go
- principal.go
- rolesync.go
- session_iface.go
- tables.go
- user_requests.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package azure is the Microsoft Entra ID (Azure) sign-in method: the OpenID Connect authorization code flow with PKCE against the tenants the registration admits, and its registration on an Auth session.
|
Package azure is the Microsoft Entra ID (Azure) sign-in method: the OpenID Connect authorization code flow with PKCE against the tenants the registration admits, and its registration on an Auth session. |
|
Package cookie provides cookie encryption using PASETO
|
Package cookie provides cookie encryption using PASETO |
|
Package deviceflow signs a command-line program in to an impulse application's machine outlet through the device flow (RFC 8628) the session library serves, keeps the token pair in the person's configuration directory, and hands the program an http.Client that carries the access token and refreshes it.
|
Package deviceflow signs a command-line program in to an impulse application's machine outlet through the device flow (RFC 8628) the session library serves, keeps the token pair in the person's configuration directory, and hands the program an http.Client that carries the access token and refreshes it. |
|
Package google is the Google Workspace sign-in method: the OpenID Connect authorization code flow with PKCE (Proof Key for Code Exchange), restricted to the Workspaces the registration admits and keyed by the connection the slot selects for the account.
|
Package google is the Google Workspace sign-in method: the OpenID Connect authorization code flow with PKCE (Proof Key for Code Exchange), restricted to the Workspaces the registration admits and keyed by the connection the slot selects for the account. |
|
internal
|
|
|
attempts
Package attempts limits the failed password attempts of an Auth.
|
Package attempts limits the failed password attempts of an Auth. |
|
basesession
Package basesession implements the session management for the application.
|
Package basesession implements the session management for the application. |
|
cookie
Package cookie implements all cookie handling for the session package
|
Package cookie implements all cookie handling for the session package |
|
dbtype
Package dbtype contains types used by the database driver packages for session storage.
|
Package dbtype contains types used by the database driver packages for session storage. |
|
oidctest
Package oidctest holds the test doubles the OIDC authenticator tests share: a minimal identity provider that signs real ID tokens, and a cookie client with a fresh key.
|
Package oidctest holds the test doubles the OIDC authenticator tests share: a minimal identity provider that signs real ID tokens, and a cookie client with a fresh key. |
|
sessioncore
Package sessioncore is what the session types are built from: the base session over the storage and the cookie client, the options every session type takes, session establishment, the API methods every session type shares, impersonation establishment and its guards, the custom data type checks, the password comparison and the login refusal redirect.
|
Package sessioncore is what the session types are built from: the base session over the storage and the cookie client, the options every session type takes, session establishment, the API methods every session type shares, impersonation establishment and its guards, the custom data type checks, the password comparison and the login refusal redirect. |
|
signinflow
Package signinflow establishes the session of an Auth sign-in over a storage driver: it resolves the identity's user, decides the sign-in and inserts the session, once for every driver, generic over the driver's transaction type.
|
Package signinflow establishes the session of an Auth sign-in over a storage driver: it resolves the identity's user, decides the sign-in and inserts the session, once for every driver, generic over the driver's transaction type. |
|
simulated
Package simulated is the development build's simulated sign-in: under the skipAuth build tag the Azure and Google methods contact no provider and take who signed in, and which roles they hold, from the environment.
|
Package simulated is the development build's simulated sign-in: under the skipAuth build tag the Azure and Google methods contact no provider and take who signed in, and which roles they hold, from the environment. |
|
testkey
Package testkey holds the one cookie master key the test suites share.
|
Package testkey holds the one cookie master key the test suites share. |
|
util
Package util is used for general utility function such as generic sorting/filtering and more.
|
Package util is used for general utility function such as generic sorting/filtering and more. |
|
workos
Package workos is the WorkOS SSO sign-in method: a client for the Standalone SSO authorization code flow.
|
Package workos is the WorkOS SSO sign-in method: a client for the Standalone SSO authorization code flow. |
|
Package mail is how the session library sends mail: the invitation a tenant's administrator sends to an address, the link that verifies an address a person adds or changes, and the link a password sign-up starts from.
|
Package mail is how the session library sends mail: the invitation a tenant's administrator sends to an address, the link that verifies an address a person adds or changes, and the link a password sign-up starts from. |
|
workspace
Package workspace sends the session library's mail through the Google Workspace SMTP relay: a plain mail submission to smtp-relay.gmail.com on port 587 over TLS, which Google Cloud's compute products allow (they block port 25, the port a mail server of our own would need), authenticated as one mailbox of the organization's Workspace domain with an app password.
|
Package workspace sends the session library's mail through the Google Workspace SMTP relay: a plain mail submission to smtp-relay.gmail.com on port 587 over TLS, which Google Cloud's compute products allow (they block port 25, the port a mail server of our own would need), authenticated as one mailbox of the organization's Workspace domain with an app password. |
|
Package mock is used to generate mock files for testing.
|
Package mock is used to generate mock files for testing. |
|
mock_azure
Package mock_azure is a generated GoMock package.
|
Package mock_azure is a generated GoMock package. |
|
mock_cookie
Package mock_cookie is a generated GoMock package.
|
Package mock_cookie is a generated GoMock package. |
|
mock_google
Package mock_google is a generated GoMock package.
|
Package mock_google is a generated GoMock package. |
|
mock_oidc
Package mock_oidc is a generated GoMock package.
|
Package mock_oidc is a generated GoMock package. |
|
mock_session
Package mock_session is a generated GoMock package.
|
Package mock_session is a generated GoMock package. |
|
mock_signin
Package mock_signin is a generated GoMock package.
|
Package mock_signin is a generated GoMock package. |
|
Package oidc is the OpenID Connect machinery the identity provider packages build on: the provider loader (discovery), the authorization code flow with PKCE and the state cookie, and the claims decoding.
|
Package oidc is the OpenID Connect machinery the identity provider packages build on: the provider loader (discovery), the authorization code flow with PKCE and the state cookie, and the claims decoding. |
|
Package sessioninfo handles session information.
|
Package sessioninfo handles session information. |
|
Package sessionstorage implements database storage for session data.
|
Package sessionstorage implements database storage for session data. |
|
internal/drivertest
Package drivertest is the conformance suite the PostgreSQL and Spanner drivers share.
|
Package drivertest is the conformance suite the PostgreSQL and Spanner drivers share. |
|
internal/postgres
Package postgres implements the session storage driver for PostgreSQL.
|
Package postgres implements the session storage driver for PostgreSQL. |
|
internal/spanner
Package spanner provides the session storage driver for Spanner.
|
Package spanner provides the session storage driver for Spanner. |
|
mock/mock_sessionstorage
Package mock_sessionstorage is a generated GoMock package.
|
Package mock_sessionstorage is a generated GoMock package. |
|
Package signin is the contract between the Auth session and a sign-in method.
|
Package signin is the contract between the Auth session and a sign-in method. |