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.
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 additionally supports custom user data: an app-defined table keyed by the durable user record (SessionUsers), written atomically with user creation and read on demand — it survives logout, expiry, and regeneration, and dies with the user. See the "Custom user data" section of the README.
Index ¶
- func SeedUserID(auth, username string) impulse.UUID
- func SeedUserIDThrough(auth, registration, username string) impulse.UUID
- 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]) ChangeLook() http.HandlerFunc
- func (a *Auth[S, U, Tx]) ChangeName() 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]) FirstPassword() *FirstPasswordHandlers
- func (a *Auth[S, U, Tx]) ForgetBrowser() http.HandlerFunc
- 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], hook DirectorySeatedHook[Tx])
- 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]) SetSignUpSeated(hook SignUpSeatedHook[Tx])
- func (a *Auth[SessionData, UserData, Tx]) SetSignedInHook(hook SignedInHook)
- func (a *Auth[SessionData, UserData, Tx]) SetTenantNames(names TenantNamer)
- 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]) SignInMeans() http.HandlerFunc
- 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]) DirectoryName(method sessioninfo.AuthMethod, connection string) (name, label string)
- 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]) RemoveSessionUserPassword(ctx context.Context, userID impulse.UUID) 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]) SetSessionUserName(ctx context.Context, userID impulse.UUID, name *string) error
- func (p *AuthAPI[S, U, Tx]) SetSessionUserPassword(ctx context.Context, userID impulse.UUID, password string) error
- func (p *AuthAPI[S, U, Tx]) SignInMeans(ctx context.Context, userID impulse.UUID) (*SignInMeans, error)
- func (p *AuthAPI[S, U, Tx]) SignInMethods() []RegisteredMethod
- func (p *AuthAPI[S, U, Tx]) SignsInThrough(method sessioninfo.AuthMethod, connection string) []string
- 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 WithSignInMethodsTableName(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 FirstPasswordHandlers
- type FirstPasswordRoutes
- type IdentityLinkedHook
- type ImpersonationAuditHook
- type ImpersonationQuery
- type ImpersonationRequest
- type InvitationAcceptedHook
- type InvitationHandlers
- type InvitationRequest
- type InvitationRoutes
- type InvitationRow
- type IssuedToken
- type LinkedDirectory
- 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 RegisteredMethod
- type RoleSyncConfig
- type SignInMeans
- type SignUpHandlers
- type SignUpRoutes
- type SignUpSeatedHook
- type SignedIn
- type SignedInHook
- type SuperAdministrators
- type Tables
- type TenantNamer
- type TokenPair
- type UserRenamedHook
- type UserRoleManager
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func SeedUserID ¶ added in v0.5.0
SeedUserID returns the id a seed creates a user under: the id of the username within the auth named auth, the same on every run, and the same for a username spelled in another case, which the users table holds to be the same name. A role is held by the id of an account, so a seed that gives a user its roles needs the id before the user exists. It writes the roles under this id first and creates the user under it last (CreateUserRequest.ID): the user's row then says the seed is done, a run that stopped before it is repeated whole, and the same memberships are written again instead of a second set under another id. No other user can come to hold the id: every other id is generated, and a request body cannot name one.
func SeedUserIDThrough ¶ added in v0.5.0
SeedUserIDThrough returns the id a seed creates a user under who holds no password and signs in through a directory: the first administrator of an auth whose roles the application gives. It is SeedUserID with the name of the sign-in registration the person comes through, so the account's id carries the deployment's word twice: that the account is a seed's, which no request can make (CreateUserRequest.ID), and which of the Auth's registrations the name is believed from.
The second is what the first sign-in needs. Such an account has no password and no link, so nothing but its name ties it to whoever signs in under it, and a directory asserts the names it likes. In an application whose tenants have directories the standard rule therefore links an account created ahead only when something vouches for it (SetDirectoryAdmission), and for this account the deployment does: the Auth's directory admission recognizes the id (DirectorySeatedHook.Seeded) and links the account at its person's first sign-in through that registration, where the registration admits one organization and nobody else. A sign-in under the name through any other registration, a customer's own provider among them, or through a registration open to more than one organization, is refused as a stranger's is.
Seeding an account under this id says that whoever the registration's directory presents under the username is the person: it is for the deployment's own directory, whose sign-in names only its administrators give, and never for a provider that lets a person choose a name. The id names the registration and not the organization behind it, so a registration pointed at another organization before the person has signed in believes that organization's word instead.
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 (the WorkOS method is in an internal package, which an application cannot import). 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, superAdministrators SuperAdministrators, 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. Tx is inferred from the storage: an application writes NewAuth[SessionData, UserData](store, cookieKey, superAdministrators, options...).
superAdministrators says who holds the Super Administrator role (SuperAdministratorsBy, or NoSuperAdministrators for an application with no permission engine). It is an argument and not an option so that no Auth is built without it: a holder always signs in with a second factor, whether or not the application's sign-in rule asks anyone for one. A sign-in the rule allows, or any sign-in where no rule is set, is held for the code the library mails when the person holds the role, unless the sign-in already carries a second factor as any account's may (the directory's attestation, or a browser the person asked to be remembered). So an Auth with super administrators must send mail (WithMail), and NewAuth refuses one that does not.
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", "name", "look", "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. name is the person's name as people read it, present when the user holds one: what a page shows for the person in place of the username, which stays what identifies them. look is the look the person chose ({"scheme", "palette"}, each present where they chose it), present when the user holds one: what their pages draw themselves in on every browser. directory is the organization's directory the session was established through ({"method", "connection"}: a Google Workspace by its connection, a Microsoft Entra tenant by its tenant id), present for a sign-in through one and absent for a password, for a personal account, which is no organization's directory, and for an impersonated session: what a page offers the person to make a tenant's directory.
func (*Auth[S, U, Tx]) ChangeLook ¶ added in v0.5.0
func (a *Auth[S, U, Tx]) ChangeLook() http.HandlerFunc
ChangeLook is the handler a signed-in person's pages call to keep the look the person chose, so it follows them to every browser they sign in from: it accepts {"scheme", "palette"} and answers the look as it is kept, each half absent when the person now holds none. The scheme is light or dark; the palette is an id as the application names its palettes, which the session library does not know, so a page drops one its application no longer offers. A scheme that is neither, or a palette id longer than a user row keeps, is a 400. The look replaces the one held as a whole: a half left out is taken off.
The handler validates the session itself, as the password change does, so it is routed beside it, outside ValidateSession; an impersonated session is refused, since the look is the person's own to choose. Nothing else writes it: no operator's entry and no method of the generated user management.
func (*Auth[S, U, Tx]) ChangeName ¶ added in v0.5.0
func (a *Auth[S, U, Tx]) ChangeName() http.HandlerFunc
ChangeName is the handler a signed-in person's account page calls to write their own name: it accepts {"name"} and answers {"name"}, the name as it is kept (without the space around it), absent when the person now holds none. A name of nothing but space takes the name off; one longer than a user row keeps is a 400. The name is what pages show for the person in place of the username, which stays what identifies them: changing it renames nobody and ends no session.
The handler validates the session itself, as the password change does, so it is routed beside it, outside ValidateSession; an impersonated session is refused, since the name is the person's own to write. A name a directory asserts at a later sign-in never replaces the one written here; after the name is taken off, the next such sign-in fills it again.
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]) FirstPassword ¶ added in v0.5.0
func (a *Auth[S, U, Tx]) FirstPassword() *FirstPasswordHandlers
FirstPassword returns the handlers of a person's first password. It panics on an Auth without mail, as a wiring mistake. On an Auth with no password method the handlers refuse every request: there is no password to choose.
func (*Auth[S, U, Tx]) ForgetBrowser ¶ added in v0.4.0
func (a *Auth[S, U, Tx]) ForgetBrowser() http.HandlerFunc
ForgetBrowser is the handler a signed-in person's account page calls to forget this browser as a trusted device of theirs (AuthAPI.ForgetTrustedDevice): their next sign-in from it asks for the second factor again, and the other people the browser was remembered for keep theirs. It validates the session itself, as the password change does, so it is routed beside it, outside ValidateSession; an impersonated session is refused. A browser that is not remembered for the person answers 200 too: there is nothing to forget. The session read says whether there is (browserRemembered).
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, with the route that removes the password when the list names it. 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 (for an invitation that makes a tenant, "newTenant" with the tenant's name, and "directoryOnly" where it is accepted through an organization's directory alone), 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. The sign-up block is in the answer only while the password method is open to sign-up: an administrator's choice in the running application, which the answer reads as each request arrives, so a page loaded after the method is opened offers to sign up and one loaded after it is closed does not.
{"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 or the remove-password 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) reach it through signin.Register, so an application never calls it directly. It panics on a registration rule, as refuseRegistration documents, and when a registration that synchronizes roles would stand beside another method, as refuseBeside documents. A person the registration has no account for is decided by its own account rule where it has one, and otherwise by what an administrator chose for the method in the running application: open to sign-up, or invite only, which every method is until it is opened (signin.AccountRule).
func (*Auth[SessionData, UserData, Tx]) SetDirectoryAdmission ¶
func (a *Auth[SessionData, UserData, Tx]) SetDirectoryAdmission(reader signin.DirectoryReader[Tx], hook DirectorySeatedHook[Tx])
SetDirectoryAdmission sets what a tenanted application gives a person's first sign-in through a tenant's directory: reader, which reads the declaration of the directory the identity came through (signin.DirectoryReader: the tenant whose directory it is, since a directory belongs to one tenant), and hook, which seats the person with the default seat the declaration names. With them the standard rule asks the tenant first: its declaration decides before the sign-in method's own choice, open or invite only. 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 person who has an account is no stranger. One with a password confirms the link with it, and the default seat is given with the link when they hold no role in the tenant. One with no password who has never signed in (an account an administrator created ahead) is tied to the sign-in by nothing but the name the directory asserts, so the identity is linked only when the directory is that of the one tenant the person belongs to, holding a role there and nothing anywhere else (hook.OnlyIn), or the sign-in carries the person's own invitation, or the account is the deployment's own seed for the registration the sign-in came through and that registration admits one organization alone (hook.Seeded, the first administrator of an Auth whose people sign in through a directory); any other sign-in under the name is refused as a stranger is, and says nothing of the account. A directory no tenant declares, and a personal account, which is no organization's directory (signin.Directory.PersonalAccounts), fall to the sign-in method's choice as without them. Set the two after NewAuth and before serving the first request; a nil reader, a hook missing either function, 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]) SetSignUpSeated ¶ added in v0.5.0
func (a *Auth[SessionData, UserData, Tx]) SetSignUpSeated(hook SignUpSeatedHook[Tx])
SetSignUpSeated sets the hook that gives a person who signed up through an open sign-in method the method's default role. Whether a method is open is no setting of the Auth's: an administrator chooses it in the running application, for each method, and the choice is a row of the Auth's sign-in methods table (Tables.SignInMethods), which each sign-in reads in its own transaction; a method with no row is invite only. A row that names a role on an Auth with no hook fails the sign-up, so no account is made holding nothing. Set it after NewAuth and before serving the first request; a nil hook, a second call, or a call once the Auth is in use is a wiring mistake and panics, as SetDirectoryAdmission 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]) SetTenantNames ¶ added in v0.5.0
func (a *Auth[SessionData, UserData, Tx]) SetTenantNames(names TenantNamer)
SetTenantNames sets what names the tenant an invitation seats a person in. The invitation screen is read by a person who is not signed in, who can read no tenant record and to whom the tenant's key, an id, says nothing: with names, the opened invitation (Invitation().Open()) and the invitation a sign-in methods answer reports carry the tenant's name beside its key (tenantName), and the screen says where the person is invited. Without them, or for a tenant the namer does not know, the name is empty and the screen names no tenant. Set it after NewAuth and before serving the first request; a nil namer, a second call, or a call once the Auth is in use is a wiring mistake and panics, as SetDirectoryAdmission 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 anything of its own by the 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]) SignInMeans ¶ added in v0.5.0
func (a *Auth[S, U, Tx]) SignInMeans() http.HandlerFunc
SignInMeans is the handler a signed-in person's account page reads what they sign in with from: {"password", "directories": [{"name", "label"}]} (see SignInMeans the type), for the session's user and nobody else. The page hides the change and the removal of a password from a person who holds none, offers the removal only where a directory sign-in can sign the person in, and names what the removal leaves by its label. The server's own refusals stand whatever the page shows.
The handler validates the session itself, as the name change does, so it is routed beside it, outside ValidateSession, and its path is named to the page as the methods list's SignInMeans. A session that acts for someone else is answered for the person it acts as, as the session read is. The labels are those of the methods list that names the path the read is served at, so an Auth served on two outlets, each with a list of its own, answers each outlet's page in that outlet's words; a read served at a path no list names, or one that two lists name, answers each method under the label it was first listed under.
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. Every application with the password method and mail routes them: whether sign-up is offered is an administrator's choice in the running application, read 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 old password is checked under the attempt limiter, counted under the user's name as a login is: a wrong one counts, and a name whose attempts reached the limit is refused with a *sessioninfo.LoginRefusal carrying RefusedTooManyAttempts and the wait (sessioninfo.RetryAfterOf), before anything is hashed. The call has no client, so only the name is counted; the password method's ChangeUserPassword handler counts the request's client too. The store is handed the hash the old password matched and writes the new one only while the user still holds it: a password that was changed, reset or removed after this call read the user stands as it is, and the call answers a Conflict that says to try again, with nothing written and no session destroyed. The store writes the password, clears the password change mark and destroys every session of the user, by UserId, in one transaction (AuthStore.ChangeUserPassword): the password is changed and the sessions ended together, or neither is. The caller then continues in a new session (ReasonRegeneration) that carries the auth events of the session the change was made in, its establishment and its factors (continuedAuthEvents); a call with no session of the user's own in the context starts one that records a password event. The new password is held to the rule every password is (acceptedPassword).
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.
A pending identity that a password started, or confirmed, completes only while the user still holds that password: once it was changed, reset or removed, the completion is refused as a wrong password is (Unauthorized, "Invalid Credentials", with sessionstorage.ErrPasswordChanged as its cause), the pending identity stays consumed and the person signs in again.
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).
The link and the session rest on the password that confirmed: both are made only while the user still holds it. A password changed, reset or removed after it was compared links nothing and starts no session; the confirmation is then refused as a wrong password is and counted as one, and the pending identity stays consumed.
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. req.Name, when given, is the person's name, kept without the space around it; one too long to keep is a BadRequest.
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]) DirectoryName ¶ added in v0.5.0
func (p *AuthAPI[S, U, Tx]) DirectoryName(method sessioninfo.AuthMethod, connection string) (name, label string)
DirectoryName answers what the Auth's sign-in registrations call the directory an identity of method and connection came through, for a sentence that names it to a person: name is the name a registration that takes the connection gives it (a listed Entra tenant's or Workspace's name, a provider's), "" where none names it, and label is the label of the button of the first registration of the login page that takes the connection, "" where the page offers none. A sentence says the name where there is one and otherwise the directory by the button a person signs in to it with, never the connection itself, which for an Entra tenant is an id. It reads nothing: the answer is what the registrations fixed in code. It closes registration, as every read of the Auth's methods does.
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]) RemoveSessionUserPassword ¶ added in v0.5.0
func (p *AuthAPI[S, U, Tx]) RemoveSessionUserPassword(ctx context.Context, userID impulse.UUID) error
RemoveSessionUserPassword removes a user's password: from then on the user signs in through their identity links alone, and a password sign-in under their name is refused as a wrong password is. A user keeps the password, their last means of sign-in (sessionstorage.ErrLastSignInMethod, Conflict), unless an identity linked to them can sign them in: a link counts when its method is a registration the login page offers and that registration still takes the link's connection (signsInThrough), so a link left from a method the Auth no longer offers, or from a tenant or a Workspace its registration no longer takes, does not, and neither does a user with no link at all. The links that count are named to the store, which removes the password only while one of them still stands, in the transaction that removes it, so an unlink asked at once cannot leave the user with neither. A user that holds no password is a BadRequest. The password change mark goes with the password, and the name's sign-in attempts are reset. The user's sessions stand, the ones the password established among them, as a removed identity link's do.
It asks for no proof and removes whatever password the user holds: it is an administrator's removal, or the end of a flow of the application's own that proved who the person is. A person removes their own through the password method's RemoveUserPassword handler, which asks for the password first and removes that password and no other.
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]) SetSessionUserName ¶ added in v0.5.0
func (p *AuthAPI[S, U, Tx]) SetSessionUserName(ctx context.Context, userID impulse.UUID, name *string) error
SetSessionUserName writes a person's name on a user, or takes it off (nil, or nothing but space): an operator's entry. The name is kept without the space around it; one longer than sessioninfo.MaxNameLength is a BadRequest, and a user that does not exist a NotFound. It replaces whatever the user held, and stands until it is written again: a later sign-in through a directory fills a name only where the user holds none.
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]) SignInMeans ¶ added in v0.5.0
func (p *AuthAPI[S, U, Tx]) SignInMeans(ctx context.Context, userID impulse.UUID) (*SignInMeans, error)
SignInMeans answers what a user signs in with (see SignInMeans the type): for an administrator's page, or a flow of the application's own. The caller guards who may ask about whom. A user that does not exist is a NotFound. Each method carries the label it was first listed under.
func (*AuthAPI[S, U, Tx]) SignInMethods ¶ added in v0.5.0
func (p *AuthAPI[S, U, Tx]) SignInMethods() []RegisteredMethod
SignInMethods lists the sign-in methods registered on the Auth, in the login page's order, then every other registration by name. It reads nothing: the answer is what the registrations fixed in code. It closes registration, as every read of the Auth's methods does.
func (*AuthAPI[S, U, Tx]) SignsInThrough ¶ added in v0.5.0
func (p *AuthAPI[S, U, Tx]) SignsInThrough(method sessioninfo.AuthMethod, connection string) []string
SignsInThrough names the sign-in registrations of the login page that an identity of method and connection (a link's Method and Connection) can sign its person in through, and none for an identity that signs nobody in: see signsInThrough. The generated user management judges a person's links by it, so its refusal of a password's removal is this library's.
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 establishes a session that operates as req.Principal on behalf of req.Actor. A user principal names the person by the id of their account and resolves against the users: a principal that is no id is a BadRequest, a missing user is an error and a disabled one is refused. An actor from another application (req.ActorRealm set) is refused when their name reads as the id of an account, and, for a role principal, when their name is already a user's username.
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. A user that holds no password keeps a means of sign-in: the unlink is refused (sessionstorage.ErrLastSignInMethod, Conflict) unless another identity linked to them can sign them in, by the judgment the removal of a password is held to (signsInThrough). The last link that counts is therefore not unlinked while only links that sign nobody in would remain: one left from a method the Auth no longer offers, or from a tenant or a Workspace its registration no longer takes. The store judges the user's other links in the transaction that unlinks, so two unlinks asked at once cannot take the user's last two between them. A user that holds a password may lose every link; the password of a user with no link that counts is refused the same way (RemoveSessionUserPassword).
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(), while an administrator has the password method open to it); 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 WithSignInMethodsTableName ¶ added in v0.5.0
func WithSignInMethodsTableName(name string) AuthOption
WithSignInMethodsTableName sets the name of the group's sign-in methods table. (default: SessionSignInMethods)
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 {
// ID is the id the new user is created under, for a seed that must know the id
// before the user exists: one that names its people in rows of its own (who filed a
// row, whose record a row is), so a development database reads the same on every
// machine, and one that gives a user its roles before it creates the user
// (SeedUserID). Null, as everywhere else, has the library generate one. It is set by
// Go callers alone and never read from a request body. An id another user holds
// fails, and so does the nil id.
ID impulse.NullUUID `json:"-"`
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"`
// Name is the person's name as people read it, nil for none: kept without the
// space around it, and refused when longer than sessioninfo.MaxNameLength.
Name *string `json:"name"`
}
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"). Name is the person's name as people read it (see "A person's name").
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] struct { Seat func(ctx context.Context, tx Tx, userID impulse.UUID, username string, seats []signin.DirectorySeat) (committed func(ctx context.Context), err error) OnlyIn func(ctx context.Context, tx Tx, userID impulse.UUID, tenant accesstypes.Domain) (bool, error) Seeded func(userID impulse.UUID, username, registration string) bool }
DirectorySeatedHook is the application's half of a tenant directory's admission: what it alone can read and write of a person's roles, in two functions.
Seat seats the user at their first sign-in through a tenant's directory, named by id (the key an application's memberships are held under) and by username (what a log line reads), with seats, the default seat of the tenant whose directory the identity came through, inside the transaction that links the identity to the user, which it is handed: the link is made and the person seated together, or neither. The first sign-in through a directory is the one that makes the link, whether it makes the account too or the account stood before, and whether the link is made at once or once the user's password has confirmed it. The library calls it once for a link: a later sign-in finds the link and gives nothing, so a seat an administrator removed is not given back, and a link that was deleted and is made again is a first sign-in again. It gives a seat only where the person holds no role in the tenant: a person who holds one keeps what they hold. 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. It is not called for no seats. It is held to what InvitationAcceptedHook is: tx alone for its reads and writes, a user the transaction made 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 and no link is left that gave nothing.
OnlyIn reports whether tenant is the only place the user holds anything, read through tx: the user holds a role, or a place in a group, in tenant itself, and nothing in another tenant, in every tenant or outside the tenants. The library asks it before it links an identity, on its sign-in name alone, to an account that has no password and has never signed in. A directory asserts the names it likes, and the link hands whoever it signs in everything the account holds, so such a link is made only through the directory of the one tenant the person belongs to, which is given nothing the tenant's own administrators could not give, or by a sign-in that carries the person's own invitation; any other sign-in under the name is refused as a person no account was created for is.
Seeded is optional and reports whether the account with this id and username is the one the deployment's own seed created for a person who signs in through the registration named: the first administrator of an Auth whose people sign in through a directory, who holds roles for the whole application and belongs to no tenant, so no tenant's directory vouches for them. The seed creates the account under SeedUserIDThrough, and the function answers by that id, which no request can give an account. Such an account is linked on its name at its person's first sign-in through that registration, where the registration admits one organization and nobody else (signin.Audience.OneOrganization) and the account is not disabled; through any other registration, or a wider one, the name links nothing. Nil recognizes no account, and a seeded first administrator is then held to the rule every account created ahead is.
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 FirstPasswordHandlers ¶ added in v0.5.0
type FirstPasswordHandlers struct {
// contains filtered or unexported fields
}
FirstPasswordHandlers are the HTTP handlers of a person's first password.
func (*FirstPasswordHandlers) SendCode ¶ added in v0.5.0
func (h *FirstPasswordHandlers) SendCode() http.HandlerFunc
SendCode takes no body. It mails the signed-in user, who holds no password, a code at the address their account holds confirmed, replacing the code that stood, and answers {"codeEmail", "codeExpiresAt"}: the address masked and when the code stops being accepted. It is refused (409) for an account that holds a password, which is changed with the old one; for an account with no confirmed address, since the code has nowhere to go that the person has shown is theirs (they add and confirm one first, Email()); and on an Auth with no password method. A mailbox sent five codes within fifteen minutes and using none is refused with too_many_emails and the wait, and an account held after five wrong codes with too_many_attempts and the wait. It is refused in an impersonated session. Route it behind ValidateSession.
func (*FirstPasswordHandlers) Set ¶ added in v0.5.0
func (h *FirstPasswordHandlers) Set() http.HandlerFunc
Set accepts {"code", "password"} from the signed-in user who holds no password and writes the password, with the code SendCode mailed. The password is held to the rule a sign-up's is (400 when it is shorter than eight characters). A code that is not the one sent is 400, and the fifth wrong one within fifteen minutes ends the code and holds the account's first password for fifteen minutes (429, too_many_attempts and the wait); a code entered when none stands, because none was sent or the one sent expired, was used or was ended, is 409. It is refused (409) for an account that holds a password and on an Auth with no password method, and in an impersonated session. No session of the user ends, this one among them; where the Auth records auth events, this session records a password event beside the ones it had. It answers {}. Route it behind ValidateSession.
type FirstPasswordRoutes ¶ added in v0.5.0
FirstPasswordRoutes are the paths of the first password 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, the key role memberships are held under, and by username, what a log line reads; a user the same transaction provisioned is buffered in it and is not readable until the commit, so the hook writes under the id 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. The hook is told how the session was established (its first auth event), and an invitation that makes a tenant entered through its directory only is refused (403, naming what to do) for a session that came through no organization's directory, the invitation left standing. 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. An invitation that makes a tenant answers "newTenant" true and the tenant's name as the invitation carries it ("tenantName"; it has no id yet), and "directoryOnly" true where it is accepted through an organization's directory alone: "signUp" is then false, since an account with a password could not accept it, and the page offers the directory buttons. 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. An invitation that makes a tenant entered through its directory only is refused as a sign-in is (organization_account_required) before any account is created. Route it beside the password login, behind ValidateXSRFToken.
type InvitationRequest ¶
type InvitationRequest struct {
// Email is the address to invite.
Email string
// Name is the person's name as the inviter gives it, "" for none: the account the
// acceptance creates carries it unless the sign-in asserts a name of its own, and
// an existing account that holds none takes it.
Name string
// TenantID is the tenant the invitation seats the person in, "" for the
// application's global surface.
TenantID string
// RoleNames are the roles the acceptance grants, as the application's hook
// understands them.
RoleNames []string
// InvitedByUserID is the user sending the invitation, null when unknown.
InvitedByUserID impulse.NullUUID
// NewTenant is the tenant the invitation makes when it is accepted, nil for an
// invitation into a tenant that exists or into the application's global surface.
// An invitation that makes a tenant names none and carries no roles (TenantID is
// "" and RoleNames empty): the application's hook makes the tenant from the
// details and seats the person in it. The tenant's name is required, since the
// invitation page shows it.
NewTenant *sessioninfo.NewTenant
}
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
// Name is the invited person's name as the inviter gave it, without the space
// around it; "" for none.
Name string
// TenantID is the tenant the acceptance seats the person in, "" for the
// application's global surface, and RoleNames the roles it grants.
TenantID string
RoleNames []string
// InvitedByUserID is the user who sent the invitation, null when unknown.
InvitedByUserID impulse.NullUUID
// NewTenant is the tenant the invitation makes when it is accepted, nil for none.
// The caller writes the NewTenant column as NewTenantColumn answers it: the
// tenant's JSON document, and null when it is nil.
NewTenant *sessioninfo.NewTenant
// 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; TenantId is null for the application's global surface (""), InvitedByUserID null when unknown, and NewTenant null for an invitation that makes no tenant. The row is what the sign-in reads when the link is followed, so a row written otherwise is an invitation nobody can accept.
func (*InvitationRow) NewTenantColumn ¶ added in v0.5.0
func (r *InvitationRow) NewTenantColumn() (*string, error)
NewTenantColumn renders the row's NewTenant as the mail links table's NewTenant column holds it: the tenant's JSON document, or nil, which is NULL, for an invitation that makes none. It is what the library's own storage writes for an invitation it stores, so a row a caller stores with it is read back as the same tenant.
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 LinkedDirectory ¶ added in v0.5.0
LinkedDirectory is a sign-in method of the login page that an identity linked to a user can sign them in through: the registration's name and the label its button carries, as the methods list gives them (MethodList). Where the page lists two registrations of one method (two Entra tenants), a link answers the ones that take its connection; a method that cannot tell one connection from another answers every registration of it.
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
// RemovePassword is the path of the password method's RemoveUserPassword handler,
// where a signed-in person's account page removes their password once they sign in
// through a directory, or none. It is refused when the password method is not
// listed.
RemovePassword string
// FirstPassword are the paths of the first password handlers
// (FirstPassword().SendCode() and Set()), where the account page of a signed-in
// person who holds no password mails them a code and takes the password they
// choose with it; both or none. They are refused when the password method is not
// listed.
FirstPassword FirstPasswordRoutes
// ForgetBrowser is the path of the Auth's ForgetBrowser handler, where a signed-in
// person's account page forgets the browser the second factor remembered for them,
// or none. The page shows the action only where the session says the browser is
// remembered for the person.
ForgetBrowser string
// ChangeName is the path of the Auth's ChangeName handler, where a signed-in
// person's account page writes their own name, or none.
ChangeName string
// SignInMeans is the path of the Auth's SignInMeans handler, where a signed-in
// person's account page reads what they sign in with (whether they hold a password,
// and the directory sign-ins that can sign them in), or none. The read answers in
// this list's labels. Without it the page offers the change of a password to
// everyone the password method serves and the removal to nobody, since it cannot
// say what a removal would leave the person.
SignInMeans string
// ChangeLook is the path of the Auth's ChangeLook handler, where a signed-in
// person's pages keep the look the person chose, or none.
ChangeLook 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. The page
// is told them only while an administrator has the password method open to
// sign-up, which the answer reads as each request arrives.
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); cookie and session options belong to NewAuth. Whether a person with no account may sign up with a password is no option: an administrator opens the method in the running application (see "Sign-up" in the README), and until then it is invite only.
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 old password is checked under the attempt limit, counted under the user's name as a login is: a name at the limit is answered 429 with too_many_attempts and the wait. 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.
func (*PasswordMethod) RemoveUserPassword ¶ added in v0.5.0
func (m *PasswordMethod) RemoveUserPassword() http.HandlerFunc
RemoveUserPassword accepts {"password"}, the signed-in user's current password, and removes it: from then on they sign in through their identity links alone. The password must match (400 otherwise), as a change asks, checked under the attempt limit as the change checks the old one (429 with too_many_attempts and the wait for a name at the limit), and a user with no identity link that can sign them in keeps it, their last means of sign-in (409). The user's sessions stand, this one among them. It validates the session itself, so it is routed beside the change, outside ValidateSession and behind ValidateXSRFToken, and refuses a user who must change their password as ValidateSession does (403, password_change_required): a temporary password is changed, not removed. Name its path to Methods (MethodList.RemovePassword) for the account page to offer it.
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 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 record (an Auth's SessionUsers).
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, attached with the store's WithCustomSessionData; 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); a resolver the configuration carries is asked for a session started with none, with the reason and the username alone. 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 AuthAPI.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. Without customData, a resolver the configuration carries runs in the insert's transaction with ReasonPreauth and the username. 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, or the resolver), 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 RegisteredMethod ¶ added in v0.5.0
type RegisteredMethod struct {
// Name is the name the method is registered under on the Auth: "password", or the
// application's name for an external registration ("google", "lakeside-entra"). It
// is the key of the method's row of the sign-in methods table.
Name string
// Method is the method behind the registration (password, azure, google, oidc).
Method sessioninfo.AuthMethod
// Label is what the login page shows for the method, "" for a method the login
// page does not offer.
Label string
// Audience is how wide the method is: the organizations it is limited to, or the
// kind of account it admits. It is whom opening the method to sign-up admits.
Audience signin.Audience
// SyncsRoles reports a method whose directory writes the roles of the people it
// signs in. Such a method has no choice to make: the directory says who holds a
// role, a person it gives one is admitted, and one it gives none is refused.
SyncsRoles bool
// OwnRule reports a registration that carries an account rule of its own
// (signin.AccountRule): the application's code decides who may sign in through it,
// so an administrator neither opens it to sign-up nor makes it invite only.
OwnRule bool
}
RegisteredMethod is one sign-in method registered on an Auth, as the code that registered it fixed it: what the page where an administrator opens a method to sign-up, or makes it invite only, lists beside the administrator's choice. The choice itself is no part of it: it is a row of the Auth's sign-in methods table (Tables.SignInMethods), keyed by Name.
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 generic OpenID Connect method (oidc.Config.RoleSync). See signin.RoleSyncConfig.
func RoleSync ¶
func RoleSync(manager UserRoleManager) RoleSyncConfig
RoleSync enables directory-driven role synchronization. See signin.RoleSync.
type SignInMeans ¶ added in v0.5.0
type SignInMeans struct {
// Password reports whether the user holds a password.
Password bool `json:"password"`
// Directories are the sign-in methods the login page offers that an identity linked
// to the user can sign them in through, in the page's order (signsInThrough). It is
// empty, never nil, when none can: the user holds no identity link, or only links
// that sign nobody in any more, and then the password is their only means of
// sign-in and its removal is refused.
Directories []LinkedDirectory `json:"directories"`
}
SignInMeans is what a user signs in with: whether they hold a password, and the directory sign-ins an identity linked to them can sign them in through. It is what a page needs to offer the removal of a password only where it can happen (a password is held, and something else signs the person in) and to say what the removal leaves. The password's hash is no part of it.
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 the method's default role, 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, and a sign-up through a method that was closed since the link was mailed 404: the link is spent, the account made and the role given in one transaction that reads the method's row, or none of it is. 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, as is every token while the password method is not open to sign-up.
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 while the password method is not open to sign-up. Route it behind StartSession and ValidateXSRFToken.
type SignUpRoutes ¶
SignUpRoutes are the paths of the sign-up handlers, as a MethodList names them.
type SignUpSeatedHook ¶ added in v0.5.0
type SignUpSeatedHook[Tx any] = func(ctx context.Context, tx Tx, userID impulse.UUID, username, method, role string) (committed func(ctx context.Context), err error)
SignUpSeatedHook is the application's half of a sign-up through a method an administrator opened: it gives the person the default role the method's row names, inside the transaction that makes their account, which it is handed, so the account is made and holds the role together, or neither. The user is named by id (the key an application's memberships are held under) and by username (what a log line reads); method is the name the method is registered under, and role the row's default role, as the application wrote it there. The library calls the hook for a person the open method alone admitted and made an account for: a person who came with an invitation is given the invitation's roles (InvitationAcceptedHook), and one whose account stood before signs in as before and is given nothing. It is not called where the row names no role, which is what an application whose people get their roles in a tenant writes. It is held to what InvitationAcceptedHook is: tx alone for its reads and writes, a user the transaction made 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-up, so no account is left holding nothing.
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 SuperAdministrators ¶ added in v0.5.0
type SuperAdministrators struct {
// contains filtered or unexported fields
}
SuperAdministrators is what NewAuth is told about the holders of the Super Administrator role (accesstypes.SuperAdministrator), the role the access library defines in every auth. An Auth is not built without one: a holder who signed in with no second factor would be the one account no tenant's sign-in settings shut out, behind a password alone. Build one with SuperAdministratorsBy, or with NoSuperAdministrators for an application that has no permission engine; the zero value is refused.
func NoSuperAdministrators ¶ added in v0.5.0
func NoSuperAdministrators() SuperAdministrators
NoSuperAdministrators tells an Auth that nobody of its application is a super administrator, because the application has no permission engine and so no role of any kind. An application whose people hold roles passes SuperAdministratorsBy: with this, a person who holds the Super Administrator role would sign in as anyone else does.
func SuperAdministratorsBy ¶ added in v0.5.0
func SuperAdministratorsBy(check signin.SuperAdministratorCheck) SuperAdministrators
SuperAdministratorsBy tells an Auth who its super administrators are: the people check reports. Pass signin.SuperAdministrators over the access library's user manager (on Spanner over resource.SignInRoles of it, as the tenant policy is), built before the Auth. The Auth then holds a holder's sign-in for the code it mails, whatever the application's sign-in rule asks of anyone else (signin.SuperAdministratorFactor), so the Auth must send mail (WithMail): NewAuth refuses one that sends none, and a nil check. A sign-in through a method that synchronizes roles is not held: there the directory is the authority on who is a super administrator, and the application's own rule is asked of that person as of anyone. NewAuth asks such an Auth for mail all the same.
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
// SignInMethods holds what an administrator chose for each sign-in method: whether
// it is open to sign-up, and the role a person who signs up through it is given. A
// method with no row is invite only.
SignInMethods 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 TenantNamer ¶ added in v0.5.0
type TenantNamer interface {
Name(tenant accesstypes.Domain) string
}
TenantNamer names a tenant by its key: what people call it, "" for a tenant it does not know. The application's tenant roster (resource.TenantRoster) is one, answering from its copy with no read.
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. Role memberships are held by the id of the account and follow nothing; an application that keys anything of its own by the username 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_first_password.go
- auth_invitation.go
- auth_look.go
- auth_mail.go
- auth_methods.go
- auth_methods_list.go
- auth_name.go
- auth_pending.go
- auth_signin.go
- auth_signin_means.go
- auth_signin_methods.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 password attempts of an Auth.
|
Package attempts limits the 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. |