sessionstorage

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT, MIT Imports: 16 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package sessionstorage implements database storage for session data. There are implementations for both Spanner and Postgres.

Index

Constants

View Source
const (
	MailLinkInvitation   = dbtype.MailLinkInvitation
	MailLinkVerification = dbtype.MailLinkVerification
	MailLinkSignUp       = dbtype.MailLinkSignUp
	// MailLinkFirstPassword is the code a signed-in person who has no password is
	// mailed to choose their first one.
	MailLinkFirstPassword = dbtype.MailLinkFirstPassword
)

The mail link kinds.

View Source
const (
	TokenApplication = dbtype.TokenApplication
	TokenAccess      = dbtype.TokenAccess
	TokenRefresh     = dbtype.TokenRefresh
)

The token kinds.

View Source
const (
	TokenRevokedByHand   = dbtype.TokenRevokedByHand
	TokenRevokedRotated  = dbtype.TokenRevokedRotated
	TokenRevokedReuse    = dbtype.TokenRevokedReuse
	TokenRevokedWithUser = dbtype.TokenRevokedWithUser
)

The token revocations.

View Source
const (
	DevicePending  = dbtype.DevicePending
	DeviceSlowDown = dbtype.DeviceSlowDown
	DeviceApproved = dbtype.DeviceApproved
	DeviceDenied   = dbtype.DeviceDenied
	DeviceExpired  = dbtype.DeviceExpired
)

The device code statuses.

Variables

View Source
var ErrLastSignInMethod = dbtype.ErrLastSignInMethod

ErrLastSignInMethod is returned when UnlinkIdentity would remove the last identity that can sign in a user that has no password, and when RemoveUserPassword would remove the password of a user none of whose identities can sign them in: either would leave the user no means of sign-in. It is a Conflict client message.

View Source
var ErrNoAuthEvents = dbtype.ErrNoAuthEvents

ErrNoAuthEvents is returned by AppendAuthEvent on a store that records no auth events (no WithAuthEvents): there is no table to record the event in. A caller for whom the event is a record beside what it did, not the thing it did, tells this apart from a failure.

View Source
var ErrPasswordChanged = dbtype.ErrPasswordChanged

ErrPasswordChanged is returned by the password writes that follow a proof of the password (UpgradeUserPasswordHash, ChangeUserPassword and RemoveProvenUserPassword) and by the inserts made on the strength of one (SignIn, HoldSignIn and LinkConfirmedIdentity with a PasswordProof) when the user no longer holds the hash that was proved: the password was changed, reset or removed after the caller read it. Nothing is written, so the other write stands whole. It is a Conflict client message.

View Source
var ErrPasswordHeld = dbtype.ErrPasswordHeld

ErrPasswordHeld is returned by SetFirstUserPassword for a user who holds a password already (a Conflict): a first password is given to an account that has none, and an account that has one changes it with the old one (ChangeUserPassword). Nothing is written.

View Source
var ErrTokenReuse = dbtype.ErrTokenReuse

ErrTokenReuse is the error of a refresh exchange given a token already rotated: the family is revoked.

Functions

This section is empty.

Types

type Auth

type Auth[Tx any] struct {
	// contains filtered or unexported fields
}

Auth is the storage for Auth sessions: their users, identities and auth events. Tx is the database's transaction type.

func NewPostgresAuth

func NewPostgresAuth(pg postgres.Queryer, opts ...PostgresOption) *Auth[pgx.Tx]

NewPostgresAuth creates PostgreSQL Auth storage over the auth schema (the base migrations plus schema/postgresql/auth/migrations). Attach the auth events and impersonation tables with WithAuthEvents and WithImpersonation, and custom session and user data with the store's WithCustomSessionData and WithCustomUserData.

func NewSpannerAuth

func NewSpannerAuth(client *cloudspanner.Client, opts ...SpannerOption) *Auth[*cloudspanner.ReadWriteTransaction]

NewSpannerAuth creates Spanner Auth storage over the auth schema (the base migrations plus schema/spanner/auth/migrations). Attach the auth events and impersonation tables with WithAuthEvents and WithImpersonation, and custom session and user data with the store's WithCustomSessionData and WithCustomUserData.

func (*Auth[Tx]) AcceptInvitation

func (a *Auth[Tx]) AcceptInvitation(ctx context.Context, userID impulse.UUID, username, email string, inv *sessioninfo.Invitation, accept signinflow.InvitationAcceptor[Tx]) error

AcceptInvitation implements AuthStore.

func (*Auth) ActivateUser

func (s *Auth) ActivateUser(ctx context.Context, id impulse.UUID) error

ActivateUser activates a user

func (*Auth[Tx]) AppendAuthEvent

func (a *Auth[Tx]) AppendAuthEvent(ctx context.Context, sessionID impulse.UUID, event *sessioninfo.AuthEvent) error

AppendAuthEvent implements AuthStore.

func (*Auth[Tx]) ApproveDeviceCode

func (a *Auth[Tx]) ApproveDeviceCode(ctx context.Context, id, userID impulse.UUID) error

ApproveDeviceCode implements AuthStore.

func (*Auth[Tx]) ChangeUserPassword added in v0.5.0

func (a *Auth[Tx]) ChangeUserPassword(ctx context.Context, id impulse.UUID, proven, hash *securehash.Hash) error

ChangeUserPassword implements AuthStore.

func (*Auth[Tx]) ClaimUserName added in v0.5.0

func (a *Auth[Tx]) ClaimUserName(ctx context.Context, id impulse.UUID, name string) (bool, error)

ClaimUserName implements AuthStore.

func (*Auth[Tx]) ClaimVerifiedEmail

func (a *Auth[Tx]) ClaimVerifiedEmail(ctx context.Context, id impulse.UUID, email string) (bool, error)

ClaimVerifiedEmail implements AuthStore.

func (*Auth[Tx]) ClearSignInAttempts

func (a *Auth[Tx]) ClearSignInAttempts(ctx context.Context, name string) error

ClearSignInAttempts implements AuthStore.

func (*Auth[Tx]) ConsumeFactorCode

func (a *Auth[Tx]) ConsumeFactorCode(ctx context.Context, id impulse.UUID) error

ConsumeFactorCode implements AuthStore.

func (a *Auth[Tx]) ConsumeMailLink(ctx context.Context, tokenHash []byte) error

ConsumeMailLink implements AuthStore.

func (*Auth[Tx]) ConsumePendingSignIn

func (a *Auth[Tx]) ConsumePendingSignIn(ctx context.Context, tokenHash []byte) error

ConsumePendingSignIn implements AuthStore.

func (*Auth) CreateSession

func (s *Auth) CreateSession(ctx context.Context, req *sessioninfo.NewSessionRequest) (impulse.UUID, error)

CreateSession creates a new session for the request and returns its ID. When a custom session data configuration with a resolver is attached to the storage, the resolver runs inside the session-insert transaction; a resolver error aborts session creation. With no resolver it is a plain insert.

func (*Auth) CreateUser

func (s *Auth) CreateUser(ctx context.Context, user *dbtype.InsertSessionUser, customData any) (*dbtype.SessionUser, error)

CreateUser creates a new user. customData is nil or *U for the configured custom user data struct type; when non-nil it is written atomically with the user insert and requires a custom user data configuration on the storage.

func (*Auth) DeactivateUser

func (s *Auth) DeactivateUser(ctx context.Context, id impulse.UUID) error

DeactivateUser deactivates a user

func (*Auth) DeleteUser

func (s *Auth) DeleteUser(ctx context.Context, id impulse.UUID) error

DeleteUser deletes a user

func (*Auth[Tx]) DenyDeviceCode

func (a *Auth[Tx]) DenyDeviceCode(ctx context.Context, id impulse.UUID) error

DenyDeviceCode implements AuthStore.

func (*Auth[Tx]) DestroySessionsByProviderSessionID

func (a *Auth[Tx]) DestroySessionsByProviderSessionID(ctx context.Context, issuer, providerSessionID string) error

DestroySessionsByProviderSessionID implements AuthStore.

func (*Auth[Tx]) DestroyUserSessions

func (a *Auth[Tx]) DestroyUserSessions(ctx context.Context, userID impulse.UUID) error

DestroyUserSessions implements AuthStore.

func (*Auth[Tx]) DeviceCode

func (a *Auth[Tx]) DeviceCode(ctx context.Context, userCode string) (*DeviceCode, error)

DeviceCode implements AuthStore.

func (*Auth[Tx]) ExchangeRefreshToken

func (a *Auth[Tx]) ExchangeRefreshToken(ctx context.Context, tokenHash []byte, access, refresh *Token) error

ExchangeRefreshToken implements AuthStore.

func (*Auth[Tx]) FactorCode

func (a *Auth[Tx]) FactorCode(ctx context.Context, pendingID impulse.UUID) (*FactorCode, error)

FactorCode implements AuthStore.

func (*Auth[Tx]) HoldSignIn

func (a *Auth[Tx]) HoldSignIn(ctx context.Context, p *PendingSignIn) (impulse.UUID, error)

HoldSignIn implements AuthStore.

func (*Auth[Tx]) IdentitiesByUser

func (a *Auth[Tx]) IdentitiesByUser(ctx context.Context, userID impulse.UUID) ([]*SessionIdentity, error)

IdentitiesByUser implements AuthStore.

func (*Auth[Tx]) Identity

func (a *Auth[Tx]) Identity(ctx context.Context, method sessioninfo.AuthMethod, connection, subject string) (*SessionIdentity, error)

Identity implements AuthStore.

func (*Auth[Tx]) InsertDeviceCode

func (a *Auth[Tx]) InsertDeviceCode(ctx context.Context, d *DeviceCode) error

InsertDeviceCode implements AuthStore.

func (*Auth[Tx]) InsertFactorCode

func (a *Auth[Tx]) InsertFactorCode(ctx context.Context, c *FactorCode) error

InsertFactorCode implements AuthStore.

func (a *Auth[Tx]) InsertMailLink(ctx context.Context, l *MailLink) error

InsertMailLink implements AuthStore.

func (*Auth[Tx]) InsertToken

func (a *Auth[Tx]) InsertToken(ctx context.Context, t *Token) error

InsertToken implements AuthStore.

func (*Auth[Tx]) InsertTrustedDevice

func (a *Auth[Tx]) InsertTrustedDevice(ctx context.Context, d *TrustedDevice) error

InsertTrustedDevice implements AuthStore.

func (*Auth[Tx]) LinkConfirmedIdentity added in v0.5.0

func (a *Auth[Tx]) LinkConfirmedIdentity(
	ctx context.Context, userID impulse.UUID, username string, identity *sessioninfo.Identity, tenant string,
	directories signin.DirectoryReader[Tx], seat signinflow.DirectorySeater[Tx], proven PasswordProof,
) error

LinkConfirmedIdentity implements AuthStore.

func (*Auth[Tx]) LinkIdentity

func (a *Auth[Tx]) LinkIdentity(ctx context.Context, userID impulse.UUID, identity *sessioninfo.Identity, tenant string) (*SessionIdentity, error)

LinkIdentity implements AuthStore.

func (a *Auth[Tx]) LiveMailLinks(ctx context.Context, kind MailLinkKind) ([]*MailLink, error)

LiveMailLinks implements AuthStore.

func (a *Auth[Tx]) MailLink(ctx context.Context, tokenHash []byte) (*MailLink, error)

MailLink implements AuthStore.

func (*Auth[Tx]) PendingSignIn

func (a *Auth[Tx]) PendingSignIn(ctx context.Context, tokenHash []byte) (*PendingSignIn, error)

PendingSignIn implements AuthStore.

func (*Auth[Tx]) ProviderSessionIssuers

func (a *Auth[Tx]) ProviderSessionIssuers(ctx context.Context, providerSessionID string) ([]string, error)

ProviderSessionIssuers implements AuthStore.

func (*Auth[Tx]) RecordFactorCodeAttempt

func (a *Auth[Tx]) RecordFactorCodeAttempt(ctx context.Context, id impulse.UUID) (int, error)

RecordFactorCodeAttempt implements AuthStore.

func (*Auth[Tx]) RecordSignInFailure

func (a *Auth[Tx]) RecordSignInFailure(ctx context.Context, name string, limit SignInAttemptLimit) (*SignInAttempts, error)

RecordSignInFailure implements AuthStore.

func (*Auth[Tx]) RedeemDeviceCode

func (a *Auth[Tx]) RedeemDeviceCode(ctx context.Context, deviceCodeHash []byte, interval time.Duration, access, refresh *Token) (code *DeviceCode, status DeviceCodeStatus, err error)

RedeemDeviceCode implements AuthStore.

func (*Auth[Tx]) RemoveProvenUserPassword added in v0.5.0

func (a *Auth[Tx]) RemoveProvenUserPassword(ctx context.Context, userID impulse.UUID, proven *securehash.Hash, standing []impulse.UUID) error

RemoveProvenUserPassword implements AuthStore.

func (*Auth[Tx]) RemoveUserPassword added in v0.5.0

func (a *Auth[Tx]) RemoveUserPassword(ctx context.Context, userID impulse.UUID, standing []impulse.UUID) error

RemoveUserPassword implements AuthStore.

func (*Auth[Tx]) ReplaceUserPassword added in v0.5.0

func (a *Auth[Tx]) ReplaceUserPassword(ctx context.Context, id impulse.UUID, hash *securehash.Hash, changeRequired bool) error

ReplaceUserPassword implements AuthStore.

func (a *Auth[Tx]) RevokeMailLink(ctx context.Context, id impulse.UUID) error

RevokeMailLink implements AuthStore.

func (*Auth[Tx]) RevokeTrustedDevice

func (a *Auth[Tx]) RevokeTrustedDevice(ctx context.Context, tokenHash []byte) error

RevokeTrustedDevice implements AuthStore.

func (*Auth[Tx]) RevokeTrustedDevices

func (a *Auth[Tx]) RevokeTrustedDevices(ctx context.Context, userID impulse.UUID) error

RevokeTrustedDevices implements AuthStore.

func (*Auth[Tx]) RevokeUserToken

func (a *Auth[Tx]) RevokeUserToken(ctx context.Context, userID, id impulse.UUID, reason TokenRevocation) error

RevokeUserToken implements AuthStore.

func (*Auth[Tx]) RevokeUserTokens

func (a *Auth[Tx]) RevokeUserTokens(ctx context.Context, userID impulse.UUID, reason TokenRevocation) error

RevokeUserTokens implements AuthStore.

func (*Auth[Tx]) SetDeviceCodesTableName

func (a *Auth[Tx]) SetDeviceCodesTableName(name string) error

SetDeviceCodesTableName implements AuthStore.

func (*Auth[Tx]) SetFactorCodesTableName

func (a *Auth[Tx]) SetFactorCodesTableName(name string) error

SetFactorCodesTableName implements AuthStore.

func (*Auth[Tx]) SetFirstUserPassword added in v0.5.0

func (a *Auth[Tx]) SetFirstUserPassword(ctx context.Context, id impulse.UUID, hash *securehash.Hash) error

SetFirstUserPassword implements AuthStore.

func (*Auth[Tx]) SetIdentitiesTableName

func (a *Auth[Tx]) SetIdentitiesTableName(name string) error

SetIdentitiesTableName implements AuthStore.

func (*Auth[Tx]) SetMailLinksTableName

func (a *Auth[Tx]) SetMailLinksTableName(name string) error

SetMailLinksTableName implements AuthStore.

func (*Auth[Tx]) SetPendingSignInsTableName

func (a *Auth[Tx]) SetPendingSignInsTableName(name string) error

SetPendingSignInsTableName implements AuthStore.

func (*Auth[Tx]) SetSignInAttemptsTableName

func (a *Auth[Tx]) SetSignInAttemptsTableName(name string) error

SetSignInAttemptsTableName implements AuthStore.

func (*Auth[Tx]) SetSignInMethod added in v0.5.0

func (a *Auth[Tx]) SetSignInMethod(ctx context.Context, m *SignInMethod) error

SetSignInMethod implements AuthStore.

func (*Auth[Tx]) SetSignInMethodsTableName added in v0.5.0

func (a *Auth[Tx]) SetSignInMethodsTableName(name string) error

SetSignInMethodsTableName implements AuthStore.

func (*Auth[Tx]) SetTokensTableName

func (a *Auth[Tx]) SetTokensTableName(name string) error

SetTokensTableName implements AuthStore.

func (*Auth[Tx]) SetTrustedDevicesTableName

func (a *Auth[Tx]) SetTrustedDevicesTableName(name string) error

SetTrustedDevicesTableName implements AuthStore.

func (*Auth[Tx]) SetUserEmail

func (a *Auth[Tx]) SetUserEmail(ctx context.Context, id impulse.UUID, email *string) error

SetUserEmail implements AuthStore.

func (*Auth[Tx]) SetUserLook added in v0.5.0

func (a *Auth[Tx]) SetUserLook(ctx context.Context, id impulse.UUID, look sessioninfo.Look) error

SetUserLook implements AuthStore.

func (*Auth[Tx]) SetUserName added in v0.5.0

func (a *Auth[Tx]) SetUserName(ctx context.Context, id impulse.UUID, name *string) error

SetUserName implements AuthStore.

func (*Auth) SetUserUsername

func (s *Auth) SetUserUsername(ctx context.Context, id impulse.UUID, newUsername string) error

SetUserUsername updates the user username and, atomically, the Username on every active session row for that user.

func (*Auth[Tx]) SetUsernameIsEmail

func (a *Auth[Tx]) SetUsernameIsEmail(same bool)

SetUsernameIsEmail implements AuthStore.

func (*Auth[Tx]) SignIn

func (a *Auth[Tx]) SignIn(ctx context.Context, req *sessioninfo.NewSessionRequest, rules SignInRules[Tx]) (impulse.UUID, error)

SignIn implements AuthStore.

func (*Auth[Tx]) SignInAttempts

func (a *Auth[Tx]) SignInAttempts(ctx context.Context, name string) (*SignInAttempts, error)

SignInAttempts implements AuthStore.

func (*Auth[Tx]) SignInMethods added in v0.5.0

func (a *Auth[Tx]) SignInMethods(ctx context.Context) ([]*SignInMethod, error)

SignInMethods implements AuthStore.

func (*Auth[Tx]) SignUp added in v0.5.0

func (a *Auth[Tx]) SignUp(ctx context.Context, method, audience string, user *InsertSessionUser, linkID impulse.UUID, seat signinflow.SignUpSeater[Tx]) (impulse.UUID, error)

SignUp implements AuthStore.

func (*Auth[Tx]) Token

func (a *Auth[Tx]) Token(ctx context.Context, tokenHash []byte) (*Token, error)

Token implements AuthStore.

func (*Auth[Tx]) Tokens

func (a *Auth[Tx]) Tokens(ctx context.Context, userID impulse.UUID) ([]*Token, error)

Tokens implements AuthStore.

func (*Auth[Tx]) TouchToken

func (a *Auth[Tx]) TouchToken(ctx context.Context, id impulse.UUID) error

TouchToken implements AuthStore.

func (*Auth[Tx]) TouchTrustedDevice

func (a *Auth[Tx]) TouchTrustedDevice(ctx context.Context, id impulse.UUID) error

TouchTrustedDevice implements AuthStore.

func (*Auth[Tx]) TouchUserSignIn

func (a *Auth[Tx]) TouchUserSignIn(ctx context.Context, userID impulse.UUID) error

TouchUserSignIn implements AuthStore.

func (*Auth[Tx]) TrustedDevice

func (a *Auth[Tx]) TrustedDevice(ctx context.Context, tokenHash []byte) (*TrustedDevice, error)

TrustedDevice implements AuthStore.

func (*Auth[Tx]) UnlinkIdentity

func (a *Auth[Tx]) UnlinkIdentity(ctx context.Context, identityID impulse.UUID, signsIn func(method sessioninfo.AuthMethod, connection string) bool) error

UnlinkIdentity implements AuthStore.

func (*Auth) UpgradeUserPasswordHash added in v0.5.0

func (s *Auth) UpgradeUserPasswordHash(ctx context.Context, id impulse.UUID, proven, hash *securehash.Hash) error

UpgradeUserPasswordHash implements UserStore.

func (*Auth) User

func (s *Auth) User(ctx context.Context, id impulse.UUID) (*dbtype.SessionUser, error)

User returns the user record associated with the username

func (*Auth[Tx]) UserByEmail

func (a *Auth[Tx]) UserByEmail(ctx context.Context, email string) (*SessionUser, error)

UserByEmail implements AuthStore.

func (*Auth) UserByUserName

func (s *Auth) UserByUserName(ctx context.Context, username string) (*dbtype.SessionUser, error)

UserByUserName returns the user record associated with the username

func (*Auth[Tx]) UsernameIsEmail

func (a *Auth[Tx]) UsernameIsEmail() bool

UsernameIsEmail implements AuthStore.

func (*Auth[Tx]) Users

func (a *Auth[Tx]) Users(ctx context.Context) ([]*SessionUser, error)

Users implements AuthStore.

func (*Auth[Tx]) VerifyUserEmail

func (a *Auth[Tx]) VerifyUserEmail(ctx context.Context, id impulse.UUID, email string) error

VerifyUserEmail implements AuthStore.

func (*Auth[Tx]) WithCustomSessionData

func (a *Auth[Tx]) WithCustomSessionData(cfg SessionDataConfig[Tx]) *Auth[Tx]

WithCustomSessionData attaches cfg, the store's one custom session data configuration, and returns the store. cfg's resolver is typed to the store's transaction, so a configuration built for the other driver does not compile here. The resolver runs inside the session-insert transaction once per session creation, and its error aborts the session creation; rows are scanned into T on every authenticated request. A later call replaces the configuration.

func (*Auth[Tx]) WithCustomUserData

func (a *Auth[Tx]) WithCustomUserData(cfg UserDataConfig) *Auth[Tx]

WithCustomUserData attaches cfg, the store's one custom user data configuration, and returns the store. Custom user data lives and dies with the user record and is read on demand. A later call replaces the configuration.

type AuthEventsTable

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

AuthEventsTable names the table that records how each session was authenticated.

func NewAuthEventsTable

func NewAuthEventsTable(tableName string) (*AuthEventsTable, error)

NewAuthEventsTable validates the auth events table name.

type AuthStore

type AuthStore[Tx any] interface {
	BaseStore
	UserStore
	// Users lists every user, by username.
	Users(ctx context.Context) ([]*SessionUser, error)
	// ReplaceUserPassword sets a user's password hash and whether the user must change
	// the password before anything else is served (SessionUser.PasswordChangeRequired:
	// true for a password an operator set, false for one the user chose), and expires
	// every session of the user, as DestroyUserSessions does, in one transaction: the
	// password is replaced and the sessions ended together, or neither is, so no
	// failure leaves the new password in place and a session alive. It follows no proof
	// of the password it replaces and overwrites whatever the row holds: it is an
	// operator's write, or the end of a flow that proved who the person is by other
	// means. A user's own change is ChangeUserPassword.
	ReplaceUserPassword(ctx context.Context, id impulse.UUID, hash *securehash.Hash, changeRequired bool) error
	// ChangeUserPassword replaces the password a user proved with one the user chose,
	// clears the password change mark and expires every session of the user, as
	// DestroyUserSessions does, in one transaction: the password is changed and the
	// sessions ended together, or neither is. proven is the hash the caller compared the
	// user's old password against, and the write lands only while the row still holds
	// it: a password changed, reset or removed since the caller read it stands as it is
	// (ErrPasswordChanged), with no session ended, so a temporary password an operator
	// set meanwhile is not overwritten on proof of the password it replaced. A write with
	// no proven hash writes nothing, and one with no new hash is refused.
	ChangeUserPassword(ctx context.Context, id impulse.UUID, proven, hash *securehash.Hash) error
	// SetFirstUserPassword gives a user who holds no password the one they chose, with
	// the password change mark clear. The write lands only while the row holds no
	// password, decided by the write itself, so of two that race one lands: a user who
	// holds one already keeps it (ErrPasswordHeld, a Conflict), and an unknown user is
	// NotFound. The user's sessions stand: a person who adds a way to sign in gives
	// nobody a reason to be signed out. A write with no hash is refused.
	SetFirstUserPassword(ctx context.Context, id impulse.UUID, hash *securehash.Hash) error
	// CreateSession inserts a session that has no identity to resolve and returns its
	// ID: a session the application starts for a user it authenticated itself, or a
	// regeneration. A configured custom session data resolver runs inside the insert
	// transaction. A pending sign-in has no session row; see HoldSignIn.
	CreateSession(ctx context.Context, req *sessioninfo.NewSessionRequest) (impulse.UUID, error)
	// SignIn establishes the session of a sign-in that carries a verified identity
	// (req.Identity) and returns its ID. An external identity resolves to its user by its
	// link, or by the account rules when it has none: rules.Account, the registration's
	// own, when it is set, and the library's standard rule when the former is nil or
	// answers signin.Standard, which reads what an administrator chose for the method
	// rules.Method names, the tenants' declarations of the
	// directory deciding a stranger first when rules.Directories is set; a password
	// identity names its user in req.UserID. rules.Policy then decides, and the
	// session is inserted with its auth events and custom session data. The sign-in
	// runs in two transactions that each commit unless a hook or the storage fails: a
	// refusal (a *sessioninfo.LoginRefusal) or a wait (a *signin.PendingSignInError)
	// keeps the hooks' own writes and writes no session. See the README's "Storage and
	// schema". A sign-in that rests on a password proof (rules.Proven) inserts its
	// session only while the user still holds the password that was proved, compared in
	// the transaction that inserts: once it was changed, reset or removed the sign-in
	// ends with ErrPasswordChanged, before the policy is asked, and no session is
	// written.
	SignIn(ctx context.Context, req *sessioninfo.NewSessionRequest, rules SignInRules[Tx]) (impulse.UUID, error)
	// Identity returns the link for (method, connection, subject), or a NotFound error.
	Identity(ctx context.Context, method sessioninfo.AuthMethod, connection, subject string) (*SessionIdentity, error)
	// IdentitiesByUser lists a user's identity links.
	IdentitiesByUser(ctx context.Context, userID impulse.UUID) ([]*SessionIdentity, error)
	// LinkIdentity links an identity to a user outside the sign-in flow.
	LinkIdentity(ctx context.Context, userID impulse.UUID, identity *sessioninfo.Identity, tenant string) (*SessionIdentity, error)
	// LinkConfirmedIdentity links an identity to the user whose password confirmed the
	// link, in one transaction, and gives the person the default seat of the tenant
	// whose directory the identity came through: directories reads the declaration and
	// seat gives the seat, handed the transaction, as at a sign-in that makes the link
	// itself (SignInRules; both nil for none). The link is made and the person seated
	// together, or neither. An identity linked meanwhile is a Conflict. proven is the
	// proof of the password that confirmed the link: the link is made only while the
	// user still holds it, compared in the transaction that links (ErrPasswordChanged
	// otherwise, nothing written).
	LinkConfirmedIdentity(
		ctx context.Context, userID impulse.UUID, username string, identity *sessioninfo.Identity, tenant string,
		directories signin.DirectoryReader[Tx], seat signinflow.DirectorySeater[Tx], proven PasswordProof,
	) error
	// UnlinkIdentity removes a link. A user that has no password keeps a means of
	// sign-in: the link goes only while another identity linked to the user is one
	// signsIn judges a means of sign-in, by its method and connection (the caller's
	// judgment of the links a sign-in is still possible through), and the unlink is
	// refused otherwise (ErrLastSignInMethod), however many identities that sign nobody
	// in the user would keep. The user's other identities are read and judged in the
	// transaction that unlinks, so two unlinks, or an unlink and a removal of the
	// password, that race cannot leave the user with no means of sign-in between them.
	// signsIn is asked about no identity of a user that has a password, who may lose
	// every one; a nil signsIn judges no identity a means of sign-in.
	UnlinkIdentity(ctx context.Context, identityID impulse.UUID, signsIn func(method sessioninfo.AuthMethod, connection string) bool) error
	// RemoveUserPassword removes a user's password, and with it the mark that the user
	// must change it. standing names the identities linked to the user that the caller
	// judged a means of sign-in (the links a sign-in is still possible through): the
	// removal goes through only while one of them is still linked to the user, read in
	// the transaction that removes the password, so a removal and an unlink that race
	// cannot both go through, and it refuses to remove the last means of sign-in
	// otherwise (ErrLastSignInMethod), a user with no identity and one whose identities
	// sign nobody in alike. The store does not judge a link: an identity standing does
	// not name is no means of sign-in to it. The user's sessions stand. A user that
	// holds no password is a BadRequest. It follows no proof of the password: it is an
	// administrator's removal. A user's own removal is RemoveProvenUserPassword.
	RemoveUserPassword(ctx context.Context, userID impulse.UUID, standing []impulse.UUID) error
	// RemoveProvenUserPassword removes the password a user proved, as RemoveUserPassword
	// removes one, under the same rule of the identities that stand. proven is the hash
	// the caller compared the user's password against, and the removal goes through
	// only while the row still holds it: a password changed, reset or removed since the
	// caller read it stands as it is (ErrPasswordChanged), answered before the user's
	// other means of sign-in are counted. A removal with no proven hash removes nothing.
	RemoveProvenUserPassword(ctx context.Context, userID impulse.UUID, proven *securehash.Hash, standing []impulse.UUID) error
	// SetTokensTableName sets the name of the tokens table (SessionTokens).
	SetTokensTableName(name string) error
	// SetDeviceCodesTableName sets the name of the device codes table
	// (SessionDeviceCodes).
	SetDeviceCodesTableName(name string) error
	// InsertToken inserts a token: created at the database's time, unused and not
	// revoked, whatever t carries.
	InsertToken(ctx context.Context, t *Token) error
	// Token returns the token holding tokenHash that is live now: not revoked and not
	// expired. Any other is NotFound.
	Token(ctx context.Context, tokenHash []byte) (*Token, error)
	// Tokens lists the live tokens of a user, newest first.
	Tokens(ctx context.Context, userID impulse.UUID) ([]*Token, error)
	// TouchToken moves a live token's LastUsedAt to the database's time; a token that
	// is not live is left as it is.
	TouchToken(ctx context.Context, id impulse.UUID) error
	// RevokeUserToken revokes the live token id of userID with reason: the token
	// alone, or its whole family when it has one. A token that is not live, or not the
	// user's, is NotFound.
	RevokeUserToken(ctx context.Context, userID, id impulse.UUID, reason TokenRevocation) error
	// RevokeUserTokens revokes every live token of a user with reason.
	RevokeUserTokens(ctx context.Context, userID impulse.UUID, reason TokenRevocation) error
	// ExchangeRefreshToken rotates the live refresh token holding tokenHash, in one
	// transaction: it is revoked as rotated and access and refresh are inserted in its
	// family, as its user, for its outlet and client, which the store fills in on the
	// two. A token that is not a live refresh token is NotFound; one already rotated is
	// a reuse, its whole family is revoked, and the error is ErrTokenReuse.
	ExchangeRefreshToken(ctx context.Context, tokenHash []byte, access, refresh *Token) error
	// InsertDeviceCode inserts a device authorization: created at the database's time
	// and pending, whatever d carries.
	InsertDeviceCode(ctx context.Context, d *DeviceCode) error
	// DeviceCode returns the device authorization userCode names that is pending now:
	// not decided, not consumed, not expired. Any other is NotFound.
	DeviceCode(ctx context.Context, userCode string) (*DeviceCode, error)
	// ApproveDeviceCode records that userID approved the pending device code id. A
	// code that is not pending is NotFound, so one decision stands.
	ApproveDeviceCode(ctx context.Context, id, userID impulse.UUID) error
	// DenyDeviceCode records that the person denied the pending device code id. A code
	// that is not pending is NotFound.
	DenyDeviceCode(ctx context.Context, id impulse.UUID) error
	// RedeemDeviceCode is the client's poll of the device code holding deviceCodeHash,
	// in one transaction: an approved code is consumed, once, and access and refresh
	// are inserted as the approving user's for the code's outlet and client, which the
	// store fills in on the two; a pending code polled before interval passed since the
	// last poll is slow_down and nothing is written; otherwise the status says what
	// the client learned. A code that is not there or was consumed is NotFound.
	RedeemDeviceCode(ctx context.Context, deviceCodeHash []byte, interval time.Duration, access, refresh *Token) (*DeviceCode, DeviceCodeStatus, error)
	// DestroyUserSessions expires every session of a user, by UserId.
	DestroyUserSessions(ctx context.Context, userID impulse.UUID) error
	// TouchUserSignIn moves a user's LastSignInAt to the database's time. The Auth calls
	// it once a sign-in has established its session, as a write of its own: inside the
	// sign-in's transaction the update would upgrade the share lock the flow holds on
	// the user row and deadlock two sign-ins of one user.
	TouchUserSignIn(ctx context.Context, userID impulse.UUID) error
	// AppendAuthEvent records a step-up or confirmation on an existing session.
	AppendAuthEvent(ctx context.Context, sessionID impulse.UUID, event *sessioninfo.AuthEvent) error
	// DestroySessionsByProviderSessionID expires every live session whose sign-in
	// carried the provider's session id under issuer, as a provider-initiated logout
	// asks; an impersonated session's record ends Logout. Both columns match: a session
	// recorded without an issuer never does.
	DestroySessionsByProviderSessionID(ctx context.Context, issuer, providerSessionID string) error
	// ProviderSessionIssuers lists the distinct issuers under which live sessions carry
	// the provider's session id, for a provider-initiated logout that names no issuer on
	// a registration serving several: the handler ends the sessions under those the
	// registration declares. A session recorded without an issuer is left out.
	ProviderSessionIssuers(ctx context.Context, providerSessionID string) ([]string, error)
	// SetIdentitiesTableName sets the name of the identities table. (default: SessionIdentities)
	SetIdentitiesTableName(name string) error
	// SetPendingSignInsTableName sets the name of the pending sign-ins table. (default: SessionPendingSignIns)
	SetPendingSignInsTableName(name string) error
	// HoldSignIn stores a sign-in that waits for a confirmation or the application's MFA
	// step and returns its row's ID. p.TokenHash is the hash of the opaque token the
	// browser's pending cookie carries. A sign-in that rests on a password proof
	// (p.PasswordProof) is stored only while its user still holds the password that was
	// proved, compared in the transaction that inserts the row (ErrPasswordChanged
	// otherwise), and the row keeps the proof for the completion to be held to.
	HoldSignIn(ctx context.Context, p *PendingSignIn) (impulse.UUID, error)
	// PendingSignIn returns the live pending sign-in holding tokenHash: not consumed and
	// not expired. Any other is NotFound.
	PendingSignIn(ctx context.Context, tokenHash []byte) (*PendingSignIn, error)
	// ConsumePendingSignIn consumes the live pending sign-in holding tokenHash by a
	// conditional update, so it is consumed once; a pending sign-in that is not live
	// (consumed, expired or unknown) is NotFound.
	ConsumePendingSignIn(ctx context.Context, tokenHash []byte) error
	// SetSignInAttemptsTableName sets the name of the sign-in attempts table. (default: SessionSignInAttempts)
	SetSignInAttemptsTableName(name string) error
	// SignInAttempts returns the sign-in attempts record of name, the submitted name as
	// the Auth normalized it: its failed password attempts in the window and its lock.
	// A name with no record is NotFound.
	SignInAttempts(ctx context.Context, name string) (*SignInAttempts, error)
	// RecordSignInFailure records a failed password attempt on name, at the time of
	// the call, under limit, and returns the record as written: the failure counts in
	// the name's window, or opens one, and the failure that reaches limit.Failures
	// locks the name for limit.Lock; a name that is locked is left as it is. The read
	// and the write are one transaction, so concurrent failures each count, and the
	// record says whether this one was counted (Counted): of failures recorded at
	// once, as many as limit.Failures are and no more, so a caller that takes the
	// failure before it judges a guess judges no more guesses than the limit. Every
	// limit the Auth keeps in this table is taken this way, before the thing it
	// bounds: a password attempt before the password is compared, a code's guess
	// before the code is, and a code or link before it is mailed.
	RecordSignInFailure(ctx context.Context, name string, limit SignInAttemptLimit) (*SignInAttempts, error)
	// ClearSignInAttempts deletes the sign-in attempts record of name: a successful
	// password check, an MFA completion and a password change reset the count.
	ClearSignInAttempts(ctx context.Context, name string) error
	// SetMailLinksTableName sets the name of the mail links table. (default: SessionMailLinks)
	SetMailLinksTableName(name string) error
	// SetSignInMethodsTableName sets the name of the sign-in methods table. (default: SessionSignInMethods)
	SetSignInMethodsTableName(name string) error
	// SignInMethods lists the rows of the sign-in methods table, by name: what an
	// administrator chose for each sign-in method they made a choice for. A method with
	// no row is invite only and is not among them.
	SignInMethods(ctx context.Context) ([]*SignInMethod, error)
	// SetSignInMethod writes the row of the sign-in method m names, replacing the one
	// it had. It holds no rule: whether the name is a registered method, and whether an
	// open method names a role, are the caller's to decide.
	SetSignInMethod(ctx context.Context, m *SignInMethod) error
	// SignUp makes the account of a person who signs up with a password through the
	// method registered under method, in one transaction, and returns its id: the method
	// must be open to sign-up for audience, whom its registration admits
	// (signin.Audience.Key), as its row says in that transaction, the mail link linkID
	// is consumed, the user row is written, and seat gives the method's default role,
	// handed the transaction (nil for none). A method that is not open and a link that
	// is no longer live are NotFound, a taken username or address a Conflict, and
	// nothing is written by a refusal.
	SignUp(ctx context.Context, method, audience string, user *InsertSessionUser, linkID impulse.UUID, seat signinflow.SignUpSeater[Tx]) (impulse.UUID, error)
	// SetUsernameIsEmail declares the users table in the shape where the address is
	// the username, generated by the database: the store never writes Email, refuses
	// a rename, and writes a verified address as the username (see the README's
	// "Users and their email address"). The password method's UsernameIsEmail option
	// sets it.
	SetUsernameIsEmail(same bool)
	// UsernameIsEmail reports whether the address is the username.
	UsernameIsEmail() bool
	// UserByEmail returns the user holding the address, verified or not, matched
	// without regard to case, or a NotFound error.
	UserByEmail(ctx context.Context, email string) (*SessionUser, error)
	// SetUserEmail puts an address on a user by hand, unverified, or takes it off
	// (nil): an administrator's entry, which reserves the address. An address another
	// user holds is a Conflict; on a store whose usernames are the addresses the
	// entry is refused.
	SetUserEmail(ctx context.Context, id impulse.UUID, email *string) error
	// VerifyUserEmail writes the address the person has just proven they read,
	// verified at the database's time, replacing whatever the user held; on a store
	// whose usernames are the addresses it is written as the username, renaming the
	// user and its live sessions. An address another user holds is a Conflict.
	VerifyUserEmail(ctx context.Context, id impulse.UUID, email string) error
	// ClaimVerifiedEmail writes email on the user as verified when the user holds no
	// verified address yet and no other user holds it, and reports whether it wrote:
	// a Google sign-in's verified address. On a store whose usernames are the
	// addresses only the verified time is written, and only when the address is the
	// username.
	ClaimVerifiedEmail(ctx context.Context, id impulse.UUID, email string) (bool, error)
	// SetUserName writes the person's name on a user, or takes it off (nil, or nothing
	// but space): the person's own change. It replaces whatever the user held; a name
	// longer than the store keeps is a BadRequest.
	SetUserName(ctx context.Context, id impulse.UUID, name *string) error
	// ClaimUserName writes name on the user when the user holds none, and reports
	// whether it wrote: the name a directory asserted at a sign-in. A user that holds
	// a name keeps it, so a name the person wrote themselves is never replaced.
	ClaimUserName(ctx context.Context, id impulse.UUID, name string) (bool, error)
	// SetUserLook writes the look the person chose on a user (sessioninfo.Look): the
	// person's own change, and nobody else's. It replaces the look held as a whole, so
	// a half the look does not name is taken off; a scheme that is neither light nor
	// dark, and a palette id longer than the store keeps, is a BadRequest.
	SetUserLook(ctx context.Context, id impulse.UUID, look sessioninfo.Look) error
	// InsertMailLink stores a mailed link's row: l.TokenHash is the hash of the opaque
	// token the mail carries. The row's ID is set on l.
	InsertMailLink(ctx context.Context, l *MailLink) error
	// MailLink returns the live mail link holding tokenHash: not consumed and not
	// expired. Any other is NotFound.
	MailLink(ctx context.Context, tokenHash []byte) (*MailLink, error)
	// LiveMailLinks lists the live links of kind, oldest first: the invitations that
	// still stand.
	LiveMailLinks(ctx context.Context, kind MailLinkKind) ([]*MailLink, error)
	// ConsumeMailLink consumes the live mail link holding tokenHash by a conditional
	// update, so it is consumed once; a link that is not live is NotFound.
	ConsumeMailLink(ctx context.Context, tokenHash []byte) error
	// RevokeMailLink consumes the live mail link id: an invitation withdrawn by hand.
	// A link that is not live is NotFound.
	RevokeMailLink(ctx context.Context, id impulse.UUID) error
	// SetFactorCodesTableName sets the name of the factor codes table.
	SetFactorCodesTableName(name string) error
	// SetTrustedDevicesTableName sets the name of the trusted devices table.
	SetTrustedDevicesTableName(name string) error
	// InsertFactorCode consumes the earlier live codes of c's pending sign-in and
	// inserts c, in one transaction, so one code stands for a pending sign-in at a
	// time; it gives c its ID. Inserts made at once for one pending sign-in run one
	// after another, each consuming the code of the one before it, so one code
	// stands after them too and none is left to be guessed at beside it.
	InsertFactorCode(ctx context.Context, c *FactorCode) error
	// FactorCode returns the live code of pendingID, or NotFound.
	FactorCode(ctx context.Context, pendingID impulse.UUID) (*FactorCode, error)
	// RecordFactorCodeAttempt counts an attempt against the live code id and returns
	// the count, in one step: attempts counted at once are each counted and answered
	// their own count, so a caller that takes the attempt before it judges a guess
	// judges no more guesses than it allows. NotFound when the code is not live.
	RecordFactorCodeAttempt(ctx context.Context, id impulse.UUID) (int, error)
	// ConsumeFactorCode marks the live code id consumed, by a conditional update, so
	// a code is used once; NotFound when it is not live.
	ConsumeFactorCode(ctx context.Context, id impulse.UUID) error
	// InsertTrustedDevice inserts d, giving it its ID.
	InsertTrustedDevice(ctx context.Context, d *TrustedDevice) error
	// TrustedDevice returns the device holding tokenHash that is live (not revoked,
	// not expired), or NotFound.
	TrustedDevice(ctx context.Context, tokenHash []byte) (*TrustedDevice, error)
	// TouchTrustedDevice moves the LastUsedAt of the live device id to the database's
	// time.
	TouchTrustedDevice(ctx context.Context, id impulse.UUID) error
	// RevokeTrustedDevice revokes the live device holding tokenHash; NotFound when it
	// is not live.
	RevokeTrustedDevice(ctx context.Context, tokenHash []byte) error
	// RevokeTrustedDevices revokes every device of userID that is not revoked yet: an
	// administrator's reset of the person's factors.
	RevokeTrustedDevices(ctx context.Context, userID impulse.UUID) error
	// AcceptInvitation accepts inv for user userID in one transaction: the
	// invitation is consumed, the user's address is set from it when the user holds
	// no verified address, and accept, the application's hook (nil for none), gives
	// what the invitation names, handed the transaction; what the hook asks to have
	// run after the commit runs once it has landed. An invitation that is no longer
	// live is NotFound (signin.ErrInvitationExpired its cause), and nothing is
	// written; a hook that fails is its error, and nothing is written either.
	AcceptInvitation(ctx context.Context, userID impulse.UUID, username, email string, inv *sessioninfo.Invitation, accept signinflow.InvitationAcceptor[Tx]) error
}

AuthStore is the storage behind an Auth session: users (SessionUsers), sessions with UserId, identity links (SessionIdentities), auth events and pending sign-ins (SessionPendingSignIns), over one database. Tx is the database's transaction type, pgx.Tx or *spanner.ReadWriteTransaction, which the sign-in hooks receive; NewPostgresAuth and NewSpannerAuth fix it.

type BaseStore

type BaseStore interface {
	// Session returns the session information from the database for given sessionID
	Session(ctx context.Context, sessionID impulse.UUID) (*sessioninfo.SessionData, error)
	// UpdateCustomSessionData updates the custom session data for an active session via
	// a transactional read-modify-write: mutate receives the current row as *T for the
	// configured struct type (zero-value when no row exists) and the full row is written
	// back; a mutate error aborts with nothing written. For genuine mid-session updates
	// only — initial population belongs in the session-creation transaction.
	UpdateCustomSessionData(ctx context.Context, sessionID impulse.UUID, mutate func(data any) error) error
	// CustomDataType returns the struct type the attached custom session data
	// configuration was built for, or nil when no configuration is attached.
	CustomDataType() reflect.Type
	// CustomUserDataType returns the struct type the attached custom user data
	// configuration was built for, or nil when no configuration is attached.
	CustomUserDataType() reflect.Type
	// UpdateSessionActivity updates the database with the current time for the session activity
	UpdateSessionActivity(ctx context.Context, sessionID impulse.UUID) error
	// DestroySession marks the session as expired. When an impersonation table is
	// configured, an impersonated session's record is ended with reason Logout.
	DestroySession(ctx context.Context, sessionID impulse.UUID) error
	// ImpersonationEnabled reports whether an impersonation record table is configured
	// (WithImpersonation). Impersonated sessions can only be created, read, and
	// evidenced when it is.
	ImpersonationEnabled() bool
	// EndImpersonation records how an impersonated session ended, once: it sets EndedAt
	// and EndReason on the session's impersonation record when the record exists and
	// has not already ended, and is a no-op otherwise. It errors when no impersonation
	// table is configured.
	EndImpersonation(ctx context.Context, sessionID impulse.UUID, reason sessioninfo.ImpersonationEndReason) error
	// CreateImpersonatedSession creates a new session for the request together with
	// its impersonation record, atomically, and returns the session ID. Custom session
	// data follows the session type's creation semantics inside the same transaction
	// (per-call data, or the configured resolver receiving ReasonImpersonation). No user
	// record is consulted or written: the request's Username is the
	// session's effective identity as the session type resolved it. It errors when no
	// impersonation table is configured.
	CreateImpersonatedSession(ctx context.Context, req *sessioninfo.NewSessionRequest, imp *sessioninfo.Impersonation) (impulse.UUID, error)
	// DestroyImpersonatedSessions expires every live impersonated session established
	// by actor and ends their records with reason Revoked. It errors when no
	// impersonation table is configured.
	DestroyImpersonatedSessions(ctx context.Context, actor string) error
	// ActiveImpersonations lists the impersonated sessions that are live, newest first:
	// record not ended, hard cap not passed, session row not expired, and session
	// activity after activeSince. q narrows the listing by actor and/or principal. It
	// errors when no impersonation table is configured.
	ActiveImpersonations(ctx context.Context, activeSince time.Time, q *sessioninfo.ImpersonationQuery) ([]*sessioninfo.Impersonation, error)
	// DestroyImpersonatedSession expires one live impersonated session and ends its record
	// with reason, atomically — the single-session form of DestroyImpersonatedSessions
	// (Revoked) and the storage step of EndImpersonation (Released). A session that is
	// not impersonated, or whose record has already ended, is left untouched. It errors
	// when no impersonation table is configured.
	DestroyImpersonatedSession(ctx context.Context, sessionID impulse.UUID, reason sessioninfo.ImpersonationEndReason) error
	// SetSessionTableName sets the name of the session table.
	SetSessionTableName(name string) error
	// SetUserTableName sets the name of the user table.
	SetUserTableName(name string) error
}

BaseStore defines an interface for managing session storage.

type CustomSessionData

type CustomSessionData[T, Tx any] struct {
	// contains filtered or unexported fields
}

CustomSessionData is the custom session data configuration of a store over Tx: the table whose rows are T, keyed by the session, and the resolver that writes a session's row when the session is created. Build it with NewCustomSessionData and attach it with the store's WithCustomSessionData (Auth and Preauth each have one); a configuration typed to the other driver's transaction does not compile there.

func NewCustomSessionData

func NewCustomSessionData[T, Tx any](tableName string, resolve NewSessionResolver[T, Tx]) (*CustomSessionData[T, Tx], error)

NewCustomSessionData validates and builds the custom session data configuration for the struct type T over the store's transaction type Tx, both inferred from resolve. With a nil resolver, name them: NewCustomSessionData[MyData, pgx.Tx]("SessionCustomData", nil); session creation then performs a plain insert, and custom data comes from per-call values or UpdateCustomSessionData.

Tx selects the driver and the struct tags that name T's columns: pgx.Tx reads `db:` tags, *spanner.ReadWriteTransaction `spanner:` tags (comma options ignored; an untagged exported field uses the field name; a tag of "-" skips the field). Fields whose columns can be NULL must use nullable Go types; a session with no custom data row yields a zero-value T.

Requirements:

  • The table MUST have a primary key column named "SessionId" that is a FK to the session table's primary key with ON DELETE CASCADE.
  • T must not map a field to "SessionId" (it is implied and reserved).

See the "Custom session data" section of the README for the full lifecycle.

func (*CustomSessionData[T, Tx]) Columns

func (c *CustomSessionData[T, Tx]) Columns() []string

Columns returns the column names derived from T's tags (excluding "SessionId").

func (*CustomSessionData[T, Tx]) TableName

func (c *CustomSessionData[T, Tx]) TableName() string

TableName returns the custom session data table name.

type CustomUserData

type CustomUserData[U any] struct {
	// contains filtered or unexported fields
}

CustomUserData is the custom user data configuration of an Auth store: the table whose rows are U, keyed by the user. Custom user data is durable: it lives and dies with the user record, untouched by logout, expiry and regeneration, and is read on demand, never joined into the per-request session read. It is written per call on CreateSessionUser and by UpdateCustomUserData, or by a custom account rule's signin.Provision hook. Build it with NewCustomUserData and attach it with Auth.WithCustomUserData. It fits either driver: columns derive from U's `db:` tags on PostgreSQL and its `spanner:` tags on Spanner.

func NewCustomUserData

func NewCustomUserData[U any](tableName string) (*CustomUserData[U], error)

NewCustomUserData validates and builds the custom user data configuration for the struct type U: NewCustomUserData[UserData]("UserCustomData").

Columns derive from U's `db:` tags on PostgreSQL and `spanner:` tags on Spanner (comma options ignored; an untagged exported field uses the field name; a tag of "-" skips the field); both derivations are validated here. Fields whose columns can be NULL must use nullable Go types; a user with no custom data row yields a zero-value U.

Requirements:

  • The table MUST have a primary key column named "UserId" that is a FK to SessionUsers.Id with ON DELETE CASCADE.
  • U must not map a field to "UserId" (it is implied and reserved).

See the "Custom user data" section of the README for the full lifecycle.

func (*CustomUserData[U]) TableName

func (c *CustomUserData[U]) TableName() string

TableName returns the custom user data table name.

type DeviceCode

type DeviceCode = dbtype.DeviceCode

DeviceCode is a row of the device codes table: one device authorization a command-line client started. See dbtype.DeviceCode.

type DeviceCodeStatus

type DeviceCodeStatus = dbtype.DeviceCodeStatus

DeviceCodeStatus is what a client's poll of its device code learned.

type FactorCode

type FactorCode = dbtype.FactorCode

FactorCode is a row of the factor codes table: one code the library mailed for a pending sign-in's second factor. See "The second factor" in the README.

type ImpersonationTable

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

ImpersonationTable is the validated impersonation configuration for storage of either backend: the name of the impersonation record table. Build it with NewImpersonationTable and attach it via WithImpersonation.

The library ships the table's canonical DDL under schema/{spanner,postgresql}/impersonation/migrations; the record deliberately has no foreign key to the session table, so it outlives the session as evidence.

func NewImpersonationTable

func NewImpersonationTable(tableName string) (*ImpersonationTable, error)

NewImpersonationTable validates and builds an impersonation configuration for the record table named tableName.

func (*ImpersonationTable) TableName

func (t *ImpersonationTable) TableName() string

TableName returns the impersonation record table name.

type InsertSessionUser

type InsertSessionUser = dbtype.InsertSessionUser

InsertSessionUser defines the structure for inserting a new SessionUser.

type MailLink = dbtype.MailLink

MailLink is a row of the mail links table: one single-use link the library mailed.

type MailLinkKind

type MailLinkKind = dbtype.MailLinkKind

MailLinkKind is what a mailed link does when it is followed.

type NewSessionResolver

type NewSessionResolver[T, Tx any] func(ctx context.Context, tx Tx, req *sessioninfo.NewSessionRequest) (*T, error)

NewSessionResolver resolves the custom session data of a session being created, returning the row to store or nil for no row. It runs inside the transaction that inserts the session row, typed to the store's transaction (pgx.Tx or *spanner.ReadWriteTransaction), once per session creation (a sign-in, a confirmation, an MFA completion and a regeneration each create a session and resolve afresh), after the user resolution: req carries the user, a provisioned one included, and req.User says how it was found. An error aborts the transaction: no session is created.

type Option

type Option interface {
	SpannerOption
	PostgresOption
}

Option configures storage of either backend at construction.

func WithAuthEvents

func WithAuthEvents(table *AuthEventsTable) Option

WithAuthEvents enables recording auth events in the given table.

func WithImpersonation

func WithImpersonation(table *ImpersonationTable) Option

WithImpersonation enables impersonated sessions on storage of either backend. The record table is LEFT JOINed into every session read, so an impersonated session's record reaches the request context together with the session, and it is written atomically with the session insert by CreateImpersonatedSession. Without this option no session is ever impersonated and the impersonation APIs return a configuration error. See the "Impersonated sessions" section of the README.

type PasswordProof added in v0.5.0

type PasswordProof = dbtype.PasswordProof

PasswordProof names the password a sign-in proved, without holding it: a digest of the hash the password was compared against. A session, a pending sign-in or a confirmed link that carries one is inserted only while the user still holds that password, compared in the inserting transaction (ErrPasswordChanged otherwise), and a pending sign-in keeps it in its row so its completion is held the same way. The nil proof is the sign-in no password proved, which is held to nothing.

func ProofOfPassword added in v0.5.0

func ProofOfPassword(hash *securehash.Hash) (PasswordProof, error)

ProofOfPassword is the proof of a password that was compared against hash, the hash the user was read with: nil for a user with no password.

type PendingSignIn

type PendingSignIn = dbtype.PendingSignIn

PendingSignIn is a sign-in held in the pending sign-ins table until its confirmation or MFA step.

type PostgresOption

type PostgresOption interface {
	// contains filtered or unexported methods
}

PostgresOption configures PostgreSQL-backed storage at construction.

type Preauth

type Preauth[Tx any] struct {
	// contains filtered or unexported fields
}

Preauth is the session storage implementation for Preauth. Tx is the database's transaction type.

func NewPostgresPreauth

func NewPostgresPreauth(db postgres.Queryer, opts ...PostgresOption) *Preauth[pgx.Tx]

NewPostgresPreauth is the function that you use to create the session manager that handles the session creation and updates. Attach custom session data with the store's WithCustomSessionData.

func NewSpannerPreauth

func NewSpannerPreauth(db *cloudspanner.Client, opts ...SpannerOption) *Preauth[*cloudspanner.ReadWriteTransaction]

NewSpannerPreauth is the function that you use to create the session manager that handles the session creation and updates. Attach custom session data with the store's WithCustomSessionData.

func (*Preauth) ActiveImpersonations

func (s *Preauth) ActiveImpersonations(ctx context.Context, activeSince time.Time, q *sessioninfo.ImpersonationQuery) ([]*sessioninfo.Impersonation, error)

ActiveImpersonations lists the impersonated sessions that are live, newest first: record not ended, hard cap not passed, session row not expired, and session activity after activeSince; q narrows the listing by actor and/or principal.

func (*Preauth) CreateImpersonatedSession

func (s *Preauth) CreateImpersonatedSession(ctx context.Context, req *sessioninfo.NewSessionRequest, imp *sessioninfo.Impersonation) (impulse.UUID, error)

CreateImpersonatedSession creates a new session for the request together with its impersonation record, atomically, and returns the session ID. Custom session data follows the session type's creation semantics inside the same transaction. The request's Username is written as the session's effective identity; no user record is consulted here — the session type resolved the identity before calling.

func (*Preauth) CustomDataType

func (s *Preauth) CustomDataType() reflect.Type

CustomDataType returns the struct type the attached custom session data configuration was built for, or nil when no configuration is attached.

func (*Preauth) CustomUserData

func (s *Preauth) CustomUserData(ctx context.Context, userID impulse.UUID) (any, error)

CustomUserData returns the custom user data row for the given user ID as *U for the configured struct type. A user with no custom data row yields a zero-value *U.

func (*Preauth) CustomUserDataType

func (s *Preauth) CustomUserDataType() reflect.Type

CustomUserDataType returns the struct type the attached custom user data configuration was built for, or nil when no configuration is attached.

func (*Preauth) DestroyAllUserSessions

func (s *Preauth) DestroyAllUserSessions(ctx context.Context, username string) error

DestroyAllUserSessions destroys all sessions for a given user

func (*Preauth) DestroyImpersonatedSession

func (s *Preauth) DestroyImpersonatedSession(ctx context.Context, sessionID impulse.UUID, reason sessioninfo.ImpersonationEndReason) error

DestroyImpersonatedSession expires one live impersonated session and ends its record with reason, atomically; a session without a live record is left untouched.

func (*Preauth) DestroyImpersonatedSessions

func (s *Preauth) DestroyImpersonatedSessions(ctx context.Context, actor string) error

DestroyImpersonatedSessions expires every live impersonated session established by actor and ends their records with reason Revoked.

func (*Preauth) DestroySession

func (s *Preauth) DestroySession(ctx context.Context, sessionID impulse.UUID) error

DestroySession marks the session as expired

func (*Preauth) EndImpersonation

func (s *Preauth) EndImpersonation(ctx context.Context, sessionID impulse.UUID, reason sessioninfo.ImpersonationEndReason) error

EndImpersonation records how an impersonated session ended, once: it sets EndedAt and EndReason on the session's impersonation record when the record exists and has not already ended, and is a no-op otherwise.

func (*Preauth) ImpersonationEnabled

func (s *Preauth) ImpersonationEnabled() bool

ImpersonationEnabled reports whether an impersonation record table is configured.

func (*Preauth) NewSession

func (s *Preauth) NewSession(ctx context.Context, username string, customData any) (impulse.UUID, error)

NewSession inserts SessionInfo into the database. customData is nil or *T for the configured custom session data struct type; when non-nil it is written atomically with the session insert (per-call data wins over any configured resolver) and requires a custom session data configuration on the storage.

func (*Preauth) Session

func (s *Preauth) Session(ctx context.Context, sessionID impulse.UUID) (*sessioninfo.SessionData, error)

Session returns the session information from the database for given sessionID

func (*Preauth) SetSessionTableName

func (s *Preauth) SetSessionTableName(name string) error

SetSessionTableName sets the name of the session table.

func (*Preauth) SetUserTableName

func (s *Preauth) SetUserTableName(name string) error

SetUserTableName sets the name of the user table.

func (*Preauth) UpdateCustomSessionData

func (s *Preauth) UpdateCustomSessionData(ctx context.Context, sessionID impulse.UUID, mutate func(data any) error) error

UpdateCustomSessionData updates the custom session data for an active session via a transactional read-modify-write: mutate receives the current row as *T for the configured struct type (zero-value when no row exists) and the full row is written back; a mutate error aborts with nothing written. The session's existence and non-expiry are verified inside the same transaction. It is intended for genuine mid-session updates only — initial population belongs in the session-creation transaction.

func (*Preauth) UpdateCustomUserData

func (s *Preauth) UpdateCustomUserData(ctx context.Context, userID impulse.UUID, mutate func(data any) error) error

UpdateCustomUserData updates the custom user data for an existing user via a transactional read-modify-write: mutate receives the current row as *U for the configured struct type (zero-value when no row exists) and the full row is written back; a mutate error aborts with nothing written. The user's existence is verified inside the same transaction.

func (*Preauth) UpdateSessionActivity

func (s *Preauth) UpdateSessionActivity(ctx context.Context, sessionID impulse.UUID) error

UpdateSessionActivity updates the database with the current time for the session activity

func (*Preauth[Tx]) WithCustomSessionData added in v0.5.0

func (p *Preauth[Tx]) WithCustomSessionData(cfg SessionDataConfig[Tx]) *Preauth[Tx]

WithCustomSessionData attaches cfg, the store's one custom session data configuration, and returns the store. cfg is typed to the store's transaction, so a configuration built for the other driver does not compile here. A row a session is started with is written with the session; when it is started with none and cfg has a resolver, the resolver runs inside the session-insert transaction, and its error aborts the session creation. Rows are scanned into T on every authenticated request. A later call replaces the configuration.

type PreauthStore

type PreauthStore interface {
	// NewSession creates a new session in the database, returning its id. customData
	// is nil or *T for the configured custom session data struct type; when non-nil it
	// is written atomically with the session insert and requires a custom session data
	// configuration on the storage.
	NewSession(ctx context.Context, username string, customData any) (impulse.UUID, error)
	// DestroyAllUserSessions destroys all sessions for a given user
	DestroyAllUserSessions(ctx context.Context, username string) error

	// shared storage methods
	BaseStore
}

PreauthStore defines an interface for managing pre-authenticated session storage.

type SessionDataConfig

type SessionDataConfig[Tx any] interface {
	// contains filtered or unexported methods
}

SessionDataConfig is a custom session data configuration typed to the store's transaction: a *CustomSessionData[T, Tx].

type SessionIdentity

type SessionIdentity struct {
	ID          impulse.UUID           `spanner:"Id"          db:"Id"`
	UserID      impulse.UUID           `spanner:"UserId"      db:"UserId"`
	Method      sessioninfo.AuthMethod `spanner:"Method"      db:"Method"`
	Connection  string                 `spanner:"Connection"  db:"Connection"`
	Subject     string                 `spanner:"Subject"     db:"Subject"`
	Tenant      *string                `spanner:"Tenant"      db:"Tenant"`
	EmailAtLink *string                `spanner:"EmailAtLink" db:"EmailAtLink"`
	CreatedAt   time.Time              `spanner:"CreatedAt"   db:"CreatedAt"`
	LastUsedAt  time.Time              `spanner:"LastUsedAt"  db:"LastUsedAt"`
}

SessionIdentity is a stored link from an external identity to a user.

type SessionUser

type SessionUser = dbtype.SessionUser

SessionUser is a person authorized to access the application.

type SignInAttemptLimit

type SignInAttemptLimit = dbtype.SignInAttemptLimit

SignInAttemptLimit is the rule a failure is recorded under: Failures within Window lock the name for Lock.

type SignInAttempts

type SignInAttempts = dbtype.SignInAttempts

SignInAttempts is the sign-in attempts record of a name: the failed password attempts in its window and the lock they earned.

type SignInMethod added in v0.5.0

type SignInMethod = dbtype.SignInMethod

SignInMethod is a row of the sign-in methods table: what an administrator chose for one sign-in method, whether it is open to sign-up and the role a person who signs up through it is given.

type SignInRules

type SignInRules[Tx any] struct {
	Account signin.AccountRule[Tx]
	Method  string
	// Audience is whom the method's registration admits now (signin.Audience.Key): the
	// method's row opens it only for the audience it was opened for.
	Audience string
	// SeededUsers says the registration declared its provider's names the
	// application's own (signin.Registration.SeededUsers): a user created ahead is
	// then linked on the name alone.
	SeededUsers bool
	Policy      signin.Policy[Tx]
	Accept      signinflow.InvitationAcceptor[Tx]
	SignUp      signinflow.SignUpSeater[Tx]
	Directories signin.DirectoryReader[Tx]
	Seat        signinflow.DirectorySeater[Tx]
	// OnlyIn reports whether a tenant is the only place a person holds anything (nil
	// for none): with Directories it decides a first link made on a name alone to an
	// account that has never signed in.
	OnlyIn signinflow.OnlyInTenant[Tx]
	// Seeded reports whether an account is the deployment's own seed for the
	// registration the sign-in came through (nil for none), and OneOrganization says
	// that registration admits exactly one organization and nobody else
	// (signin.Audience.OneOrganization): with Directories the two admit the seed's
	// first link on the name.
	Seeded          signinflow.SeededAccount
	OneOrganization bool
	// TrustedDevice reports whether the browser signing in is a trusted device of
	// the user, which stands in for the second factor a RequireMFA asks; nil for none.
	TrustedDevice signinflow.TrustedDeviceCheck
	// Proven is the proof of the password the sign-in rests on (ProofOfPassword): the
	// one just entered at a login or a confirmation, or the one a pending sign-in was
	// held with. Nil when no password was proved.
	Proven PasswordProof
}

SignInRules are the application's rules a sign-in runs under, handed to AuthStore.SignIn: the registration's own account rule (nil for none) and the name the sign-in's method is registered under, by which the standard rule reads what an administrator chose for it ("" for a sign-in through no registered method), the sign-in policy (nil for none), the invitation acceptor (nil for none), the hook that gives a person who signed up through an open method its default role (nil for none), and a tenanted application's reader of the tenants' directory declarations with the hook that seats a person at their first sign-in through a tenant's directory (both nil for none). They carry the proof of the password the sign-in rests on too (nil for none), which the session's insert is held to.

type SpannerOption

type SpannerOption interface {
	// contains filtered or unexported methods
}

SpannerOption configures Spanner-backed storage at construction.

type Token

type Token = dbtype.Token

Token is a row of the tokens table: one bearer credential of a machine outlet. See dbtype.Token.

type TokenKind

type TokenKind = dbtype.TokenKind

TokenKind is what a token is: an application token a person issued, or the access or refresh token of a device grant.

type TokenRevocation

type TokenRevocation = dbtype.TokenRevocation

TokenRevocation says why a token was revoked.

type TrustedDevice

type TrustedDevice = dbtype.TrustedDevice

TrustedDevice is a row of the trusted devices table: a browser the person asked to be remembered after a second factor. See "The second factor" in the README.

type UserDataConfig

type UserDataConfig interface {
	// contains filtered or unexported methods
}

UserDataConfig is a custom user data configuration: a *CustomUserData[U].

type UserStore

type UserStore interface {
	// User returns a session user for give user id
	User(ctx context.Context, id impulse.UUID) (*SessionUser, error)
	// UserByUsername returns a session user for give username
	UserByUserName(ctx context.Context, username string) (*SessionUser, error)
	// SetUserUsername updates the user username and, atomically, the Username
	// on every active session row for that user.
	SetUserUsername(ctx context.Context, id impulse.UUID, newUsername string) error
	// UpgradeUserPasswordHash replaces the password hash a sign-in proved with hash, the
	// same password hashed under the hasher's current parameters, leaving the password
	// change mark as it is. proven is the hash the sign-in compared the password
	// against, and the write lands only while the row still holds it: a password
	// changed, reset or removed since the sign-in read it stands as it is
	// (ErrPasswordChanged), so an upgrade never puts an old password back. A write with
	// no proven hash writes nothing, and one with no new hash is refused.
	UpgradeUserPasswordHash(ctx context.Context, id impulse.UUID, proven, hash *securehash.Hash) error
	// ActivateUser activates a user
	ActivateUser(ctx context.Context, id impulse.UUID) error
	// CreateUser creates a new user. customData is nil or *U for the configured custom
	// user data struct type; when non-nil it is written atomically with the user insert
	// and requires a custom user data configuration on the storage.
	CreateUser(ctx context.Context, user *InsertSessionUser, customData any) (*SessionUser, error)
	// DeactivateUser deactivates a user
	DeactivateUser(ctx context.Context, id impulse.UUID) error
	// DeleteUser deletes a user
	DeleteUser(ctx context.Context, id impulse.UUID) error
	// CustomUserData returns the custom user data row for the given user ID as *U for
	// the configured struct type. A user with no custom data row yields a zero-value *U.
	CustomUserData(ctx context.Context, userID impulse.UUID) (any, error)
	// UpdateCustomUserData updates the custom user data for an existing user via a
	// transactional read-modify-write: mutate receives the current row as *U (zero-value
	// when no row exists) and the full row is written back; a mutate error aborts with
	// nothing written.
	UpdateCustomUserData(ctx context.Context, userID impulse.UUID, mutate func(data any) error) error
}

UserStore is the user management of a store that has users: the Auth storage.

Directories

Path Synopsis
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.
postgres
Package postgres implements the session storage driver for PostgreSQL.
Package postgres implements the session storage driver for PostgreSQL.
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.

Jump to

Keyboard shortcuts

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