sessioninfo

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: 12 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package sessioninfo handles session information.

Index

Constants

View Source
const (
	// AttrImpersonationActor is the real user acting, by username.
	AttrImpersonationActor = "impersonation.actor"
	// AttrImpersonationActorID is the id of the actor's account, for an actor who has one
	// in this application.
	AttrImpersonationActorID = "impersonation.actor_id"
	// AttrImpersonationActorRealm is the application or IdP that authenticated the actor.
	AttrImpersonationActorRealm = "impersonation.actor_realm"
	// AttrImpersonationPrincipalKind is "User" or "Role".
	AttrImpersonationPrincipalKind = "impersonation.principal_kind"
	// AttrImpersonationPrincipal is the impersonated user or role name.
	AttrImpersonationPrincipal = "impersonation.principal"
	// AttrImpersonationMask is the permission allowlist, "unrestricted" when none.
	AttrImpersonationMask = "impersonation.mask"
	// AttrImpersonationSessionID is the impersonated session's ID — the record's key.
	AttrImpersonationSessionID = "impersonation.session_id"
	// AttrImpersonationSourceSessionID is the actor's session in the source application, when known.
	AttrImpersonationSourceSessionID = "impersonation.source_session_id"

	// AttrPrincipalKind is "User" or "Role": the kind of the principal a configured
	// resolver chose for the request, stamped only when it differs from the default.
	AttrPrincipalKind = "principal.kind"
	// AttrPrincipal is the name of the principal a configured resolver chose for the
	// request, stamped only when it differs from the default.
	AttrPrincipal = "principal"
)

Canonical attribute keys for impersonation evidence. Session validation stamps them onto the request logger (the request-level entry and every line logged within the request); applications, dashboards and alerting should reference these constants rather than respell them.

View Source
const (
	// PrincipalKindUser is an impersonated user.
	PrincipalKindUser = "User"
	// PrincipalKindRole is an impersonated role.
	PrincipalKindRole = "Role"
)

Principal kinds as rendered for evidence and storage.

View Source
const (
	SchemeLight = "light"
	SchemeDark  = "dark"
)

The two schemes a look is drawn in.

View Source
const (
	// TokenKindApplication is a token a person issued to an application of their own.
	TokenKindApplication = "application"
	// TokenKindAccess is the access token of a device grant a command-line client
	// obtained.
	TokenKindAccess = "access"
)

The token kinds as a request's TokenInfo names them.

View Source
const (
	// AttrTokenID is the token's id, the row's key.
	AttrTokenID = "token.id"
	// AttrTokenKind is the token's kind: "application" or "access".
	AttrTokenKind = "token.kind"
	// AttrTokenName is the name the person gave an application token; absent for an
	// access token.
	AttrTokenName = "token.name"
	// AttrTokenClient is the client a device grant's access token was issued to; absent
	// for an application token.
	AttrTokenClient = "token.client"
)

The evidence attributes of a request a bearer token authenticated, on the request's log entry, every line logged within it and its trace span.

View Source
const MaxNameLength = 200

MaxNameLength is the longest name a user holds, in characters.

View Source
const MaxPaletteLength = 64

MaxPaletteLength is the longest palette id a user holds, in characters.

Variables

This section is empty.

Functions

func ActorFromCtx

func ActorFromCtx(ctx context.Context) string

ActorFromCtx returns the username of the real user behind the session in the context: the impersonation record's actor for an impersonated session, otherwise the session's username. It is what a person reads and what evidence carries; the permission store names the same person by ActorUserFromCtx.

func ActorUserFromCtx added in v0.5.0

func ActorUserFromCtx(ctx context.Context) accesstypes.User

ActorUserFromCtx returns the real user behind the session in the context as the permission store names them: the impersonation record's actor for an impersonated session (Impersonation.ActorUser), otherwise the session's own user (SessionData.User). It panics when no session is in the context, like FromCtx.

func CleanName added in v0.5.0

func CleanName(name *string) (*string, error)

CleanName is a person's name as a user row keeps it: without the space around it, nil for none (nil, or nothing but space). A name longer than MaxNameLength, and one that is not text on one line (a control character in it, a line break and a tab among them, or bytes that are no text), are refused as a bad request. Everything that writes a name holds it to this one rule: the session library's own writes and the management an application generates for its people.

func CustomDataFromCtx

func CustomDataFromCtx[T any](ctx context.Context) (T, error)

CustomDataFromCtx returns the strongly typed custom session data from the context. The stored dynamic type is a POINTER to the struct type the custom session data configuration was built for (sessionstorage.NewCustomSessionData), so instantiate with the pointer type: CustomDataFromCtx[*MySessionData](ctx). The typed session APIs' CustomData(ctx) method wraps this and returns the value directly. See the "Custom session data" section of the README for the full lifecycle.

func CustomDataFromRequest

func CustomDataFromRequest[T any](r *http.Request) (T, error)

CustomDataFromRequest returns the strongly typed custom session data from the request context. The stored dynamic type is a pointer to the configuration's struct type, so instantiate with the pointer type: CustomDataFromRequest[*MySessionData](r).

func IDFromCtx

func IDFromCtx(ctx context.Context) impulse.UUID

IDFromCtx returns the sessionID from the request context

func IDFromRequest

func IDFromRequest(r *http.Request) impulse.UUID

IDFromRequest returns the sessionID from the request

func KeptName added in v0.5.0

func KeptName(name string) string

KeptName is a name somebody else gave for a person (a directory at a sign-in, the sender of an invitation) as a user row would keep it: "" where CleanName keeps none and where it refuses the name. What the person did not type is dropped, never refused, so the sign-in it came with stands.

func MaskFromCtx

func MaskFromCtx(ctx context.Context) accesstypes.PermissionMask

MaskFromCtx returns the permission mask of the session in the context: the impersonation record's mask for an impersonated session, otherwise the unrestricted mask.

func NewLoginRefusal

func NewLoginRefusal(code LoginRefusalCode, cause error) error

NewLoginRefusal attaches code to cause. A custom session data resolver returns it to refuse a login with a code the application's login page holds text for; cause may be an httpio client message, any other error, or nil when the code says enough.

func NewTooManyAttemptsRefusal

func NewTooManyAttemptsRefusal(wait time.Duration) error

NewTooManyAttemptsRefusal is the refusal of a password attempt on a locked name: RefusedTooManyAttempts over a TooManyRequests client message, carrying wait, the time until the name may be tried again. It says nothing about the name.

func NewTooManyAttemptsRefusalSaying added in v0.5.0

func NewTooManyAttemptsRefusalSaying(wait time.Duration, message string) error

NewTooManyAttemptsRefusalSaying is NewTooManyAttemptsRefusal in the words the caller gives: the refusal of an attempt at something other than a password at the login, held by a limit of its own (the wrong codes entered for a person's first password). The code and the wait are the same, so a page that knows RefusedTooManyAttempts handles it alike, and the words say what was held and what to do.

func NewTooManyEmailsRefusal added in v0.3.0

func NewTooManyEmailsRefusal(wait time.Duration) error

NewTooManyEmailsRefusal is the refusal of a code or link to an address at its limit of mail: RefusedTooManyEmails over a TooManyRequests client message, carrying wait, the time until the address may be sent another.

func PrincipalFromCtx

func PrincipalFromCtx(ctx context.Context) accesstypes.Principal

PrincipalFromCtx returns the authorization subject of the session in the context: the principal a configured resolver chose for this request when it did; otherwise the impersonation record's principal for an impersonated session; otherwise the session user's own principal, the id of their account (SessionData.User). Callers never branch on whether the session is impersonated, or on whether a resolver is configured, to obtain the subject. It panics when no session is in the context, like FromCtx.

func RetryAfterOf

func RetryAfterOf(err error) (wait time.Duration, ok bool)

RetryAfterOf returns the wait a refused attempt asks for before the next one, and whether err asks for one: true for a RefusedTooManyAttempts or RefusedTooManyEmails refusal anywhere in err's chain, false for any other error.

Types

type Attestation

type Attestation string

Attestation is what a sign-in's connection says about a second factor: nothing, evidence or a declaration. A sign-in method sets it on the Identity it verifies, and the Auth records it as the session's second auth event (MethodAttestedByEvidence or MethodAttestedByDeclaration), which satisfies a sign-in policy's RequireMFA without a step of the library's or the application's own. See "The second factor" in the README.

const (
	// NotAttested is a sign-in no connection vouches for: a password, or a directory
	// the application does not administer whose token carries no evidence.
	NotAttested Attestation = ""
	// AttestedByEvidence is a token whose amr claim names mfa: the identity provider
	// ran a second factor at this sign-in.
	AttestedByEvidence Attestation = "evidence"
	// AttestedByDeclaration is a connection the registration declares as a directory
	// that enforces a second factor (Attesting()), which the application administers.
	AttestedByDeclaration Attestation = "declaration"
)

func AttestationOf

func AttestationOf(amr []string, declared bool) Attestation

AttestationOf is the attestation of a sign-in whose token asserts amr, through a connection the registration declares attesting (declared) or not: evidence when amr names mfa (RFC 8176, what Entra asserts after its multifactor authentication), whatever the declaration; the declaration otherwise when the connection is declared; none when neither. Evidence is read from the one value that says several factors were used, not from the values that name one method (otp, hwk), which say nothing about a second.

func (Attestation) Method

func (a Attestation) Method() AuthMethod

Method is the auth method that records the attestation, "" for NotAttested.

type Attribute

type Attribute struct {
	Key   string
	Value string
}

Attribute is one key/value pair of impersonation evidence.

type AuthEvent

type AuthEvent struct {
	Method     AuthMethod
	Connection string
	IDPAMR     []string
	// At is when the event happened. On an event given to the library, zero means the
	// time the database records it, which is the one to use unless the event happened
	// earlier; a time that is set is stored as given and must not be later than the
	// database's clock. On an event read back it is as stored.
	At time.Time
}

AuthEvent records one step that authenticated a session, such as the sign-in, a link confirmation or an MFA step. Events are stored in the auth events table and read with the session.

type AuthMethod

type AuthMethod string

AuthMethod names a way a person proved who they are. Sign-in methods use the constants below. An application may record its own step-up method (for example an emailed one-time code) under any other non-empty value.

const (
	// MethodPassword is a username and password checked against SessionUsers.
	MethodPassword AuthMethod = "password"
	// MethodAzure is Microsoft Entra ID (Azure) OIDC.
	MethodAzure AuthMethod = "azure"
	// MethodGoogle is Google Workspace OIDC.
	MethodGoogle AuthMethod = "google"
	// MethodWorkOS is WorkOS SSO (SAML or OIDC brokered by WorkOS).
	MethodWorkOS AuthMethod = "workos"
	// MethodOIDC is a generic OpenID Connect provider, known by its issuer alone
	// (session/oidc): an identity gateway, Okta, Keycloak.
	MethodOIDC AuthMethod = "oidc"
	// MethodImpersonation records that a session was established by impersonation.
	// Its AuthEvent.Connection is the actor.
	MethodImpersonation AuthMethod = "impersonation"
	// MethodLinkConfirmation records a password confirmation that linked a new
	// external identity to an existing user.
	MethodLinkConfirmation AuthMethod = "link-confirmation"
	// MethodApplication is the identity of a session the application starts for a
	// user it authenticated itself (AuthAPI.StartAuthenticatedSession): the user, named
	// by ID, with no identity to resolve; the session's auth events say how the person
	// authenticated. A pending identity held from such a start carries it.
	MethodApplication AuthMethod = "application"
	// MethodEmailCode records the library's own second factor: a one-time code mailed
	// to the user's address and entered at the pending step (Pending().SendCode() and
	// VerifyCode()). It has no connection.
	MethodEmailCode AuthMethod = "email-code"
	// MethodTrustedDevice records that a browser the person asked to be remembered
	// after a second factor stood in for it: the trusted device cookie named a live
	// device of the user. It has no connection.
	MethodTrustedDevice AuthMethod = "trusted-device"
	// MethodAttestedByEvidence records that the identity provider attested to a second
	// factor in the sign-in's token (an amr claim naming mfa): the provider ran one at
	// this sign-in. Its connection is the sign-in's and IDPAMR what the provider
	// asserted.
	MethodAttestedByEvidence AuthMethod = "attested-by-evidence"
	// MethodAttestedByDeclaration records that the registration declares the sign-in's
	// connection as a directory that enforces a second factor (Attesting() on the
	// Google and Entra organization slots): the application administers the directory
	// and vouches for it. Its connection is the sign-in's.
	MethodAttestedByDeclaration AuthMethod = "attested-by-declaration"
)
const MethodToken AuthMethod = "token"

MethodToken is the method of the auth event a request on a machine outlet records: the request was authenticated by a bearer token the Auth issued, and the event's connection is the token's kind, "application" or "access".

func (AuthMethod) Attests

func (m AuthMethod) Attests() bool

Attests reports whether m is an attestation event's method: the sign-in's connection vouched for a second factor, by evidence or by declaration.

func (AuthMethod) SecondFactor added in v0.5.0

func (m AuthMethod) SecondFactor() bool

SecondFactor reports whether m records a second factor on a session: a step beyond the sign-in that established it. The library's own are the mailed code (MethodEmailCode), a remembered browser standing in for it (MethodTrustedDevice) and a connection's attestation (Attests); a step the application records under a name of its own is one too, since that is what such a name is for. The methods that establish a session or link an identity are none: a password, a directory, an impersonation, a link confirmation, a session the application starts itself, a token.

func (AuthMethod) ThroughDirectory

func (m AuthMethod) ThroughDirectory() bool

ThroughDirectory reports whether the method signs a person in through a directory: Microsoft Entra ID, Google Workspace, WorkOS and a generic OpenID Connect provider, whose identities carry the directory as their connection (Identity.Connection, and AuthEvent.Connection on the session's first auth event). A password, a session the application starts for a user it authenticated itself, an impersonation, a link confirmation and a step the application records under its own name are not. A tenant that is directory only admits a sign-in through its own directory alone, which its declaration names (signin.Directory); see signin.TenantPolicy.

type CTXKey

type CTXKey string

CTXKey is a type for storing values in the request context

const (
	// CtxSessionInfo is the key used to store the SessionInfo in the context.
	CtxSessionInfo CTXKey = "sessionInfo"
	// CtxUserInfo is the key used to store the UserInfo in the context.
	CtxUserInfo CTXKey = "userInfo"

	// CTXSessionID is the key for storing SessionID in context
	CTXSessionID CTXKey = "sessionID"
)

type Identity

type Identity struct {
	// Method is the sign-in method that verified this identity.
	Method AuthMethod
	// Connection scopes the Subject. It is the WorkOS connection ID for MethodWorkOS,
	// the tenant ID (tid) for MethodAzure, and the registration's configured
	// Connection, the application's own name for the Workspace organization, for
	// MethodGoogle, and the registration's Connection, the application's name for the
	// provider (its issuer URL by default), for MethodOIDC. It is empty for MethodPassword.
	Connection string
	// Subject is the upstream subject. It is the WorkOS profile idp_id, the Azure oid,
	// the Google sub, the provider's sub for MethodOIDC, or the user ID (as a string)
	// for MethodPassword.
	Subject string
	// Email is the email address asserted by the method, if any.
	Email string
	// Name is the person's name as the method asserts it (the name claim of a Google,
	// Entra or OpenID Connect token, the first and last name of a WorkOS profile); ""
	// when the method has none. It is written on the account a sign-in creates and on an
	// account that holds no name yet, and never over a name the account holds. It is an
	// attribute, never a key.
	Name string
	// EmailVerified reports whether the method asserts the email is verified.
	EmailVerified bool
	// Claims is the method's verified payload (ID-token claims or WorkOS profile). It
	// is passed to resolvers and custom data hooks.
	Claims json.RawMessage
	// IDPAMR is the identity provider's authentication-method evidence (OIDC amr
	// values or SAML AuthnContextClassRef), when the method provides it. The library
	// does not interpret it.
	IDPAMR []string
	// SignInName is the name the person signs in with at the directory the identity
	// came from: the user principal name on Entra, the verified email on Google; ""
	// when the method has none. The standard account rule (signin.AccountRule)
	// uses it as the username of the account it provisions or matches. It is an
	// attribute, never a key.
	SignInName string
	// Organization is the organization the identity came from as the registration
	// names it: the tenant's name when the application gave one and its id otherwise
	// on Entra, the connection the Workspaces slot selected on Google; "" when the
	// method has none. The standard account rule stores it as the tenant key of the
	// link it makes, unless a custom rule names another. It is an attribute, never a
	// key: the key stays Connection.
	Organization string
	// Guest reports that the account is a guest of its directory, not a member: an
	// Entra B2B guest, whose preferred username is an address the directory did not
	// verify. The standard account rule refuses a guest; a custom rule decides for
	// itself.
	Guest bool
	// Attestation is what the connection says about a second factor: evidence in the
	// token, the registration's declaration, or nothing. The Auth records it as the
	// session's second auth event, after the sign-in's, and a sign-in policy's
	// RequireMFA is satisfied by it. A password identity never attests.
	Attestation Attestation
}

Identity is a verified identity produced by a sign-in method. An external identity is linked to a user by (Method, Connection, Subject). Email is an attribute and is never used as a key.

type Impersonation

type Impersonation struct {
	// SessionID is the impersonated session — the record's key, and the value
	// every piece of evidence carries under AttrImpersonationSessionID.
	SessionID impulse.UUID
	// Actor is the authenticated real user the session acts on behalf of, by username:
	// what a person reads, and what evidence carries.
	Actor string
	// ActorID is the actor's account in this application, read from the actor's own
	// session when the impersonated session is established: what the permission store
	// names the actor by (ActorUser). It is null for a foreign actor, who has no account
	// here, and for a session type whose sessions belong to no account.
	ActorID impulse.NullUUID
	// ActorRealm names the application or identity provider that authenticated
	// the actor, when it differs from this application (e.g. "admin-portal").
	// Empty means the actor is a user of this application (see IsLocalActor).
	ActorRealm string
	// SourceSessionID is the actor's own session: in this application for a local
	// actor (verified at establishment, kept alive by this session's activity, and
	// returned to by EndImpersonation), or in the source application for a
	// foreign actor, for cross-application correlation.
	SourceSessionID impulse.NullUUID
	// Principal is the authorization subject the session evaluates against. A user
	// principal names the impersonated person as the permission store does: by the id
	// of their account, for a session type whose users are accounts.
	Principal accesstypes.Principal
	// Mask is the permission allowlist the session is attenuated by; the zero
	// mask is unrestricted.
	Mask accesstypes.PermissionMask
	// Reason is the free-text justification supplied when the session was
	// established (a ticket reference, a support note); empty when none was.
	Reason string
	// StartedAt is when the session was established.
	StartedAt time.Time
	// ExpiresAt is the hard cap: the session is expired once this instant
	// passes, regardless of activity.
	ExpiresAt time.Time
	// EndedAt is when the end of the session was observed (logout, revocation,
	// or expiry noticed at validation); nil while the session is live or if it
	// expired unobserved.
	EndedAt *time.Time
	// EndReason says how the session ended; empty while EndedAt is nil.
	EndReason ImpersonationEndReason
}

Impersonation is the record of an impersonated session: who established it (the actor), what it operates as (the principal), and how it is attenuated (the mask). Its presence is what marks a session as impersonated. The session's effective identity — SessionInfo.Username — is the impersonated user for a user principal and the actor for a role principal, so every consumer that reads the session sees exactly what it would see had that identity logged in; the actor is recoverable from this record alone.

func ImpersonationFromCtx

func ImpersonationFromCtx(ctx context.Context) (*Impersonation, bool)

ImpersonationFromCtx returns the impersonation record from the context and true, or nil and false for a session that is not impersonated. It panics when no session is in the context, like FromCtx.

func ImpersonationFromRequest

func ImpersonationFromRequest(r *http.Request) (*Impersonation, bool)

ImpersonationFromRequest returns the impersonation record from the request context and true, or nil and false for a session that is not impersonated. It panics when no session is in the context, like FromRequest.

func (*Impersonation) ActorUser added in v0.5.0

func (i *Impersonation) ActorUser() accesstypes.User

ActorUser returns the actor as the permission store names them: the id of their account for an actor who has one here, and otherwise the name the record carries (a foreign actor's, which is no account's id and so holds nothing in this application).

func (*Impersonation) Attributes

func (i *Impersonation) Attributes() []Attribute

Attributes returns the record's evidence as canonical key/value pairs, in a stable order, for stamping onto loggers, spans, and events.

func (*Impersonation) IsLocalActor

func (i *Impersonation) IsLocalActor() bool

IsLocalActor reports whether the actor is a user of this application: no ActorRealm names another one. A local actor's role-principal session is their own session narrowed to a role, and their name in the session table is theirs; a foreign actor's role-principal session carries a name borrowed from another application.

func (*Impersonation) PrincipalKind

func (i *Impersonation) PrincipalKind() string

PrincipalKind renders the principal's kind for evidence and storage: PrincipalKindUser or PrincipalKindRole.

func (*Impersonation) PrincipalName

func (i *Impersonation) PrincipalName() string

PrincipalName renders the impersonated role's name, or the impersonated user as the principal names them (the id of their account, for a session type whose users are accounts), for evidence. The session's own username names the person beside it.

type ImpersonationEndReason

type ImpersonationEndReason string

ImpersonationEndReason says how an impersonated session ended.

const (
	// ImpersonationEndedByLogout is a session the actor logged out of.
	ImpersonationEndedByLogout ImpersonationEndReason = "Logout"
	// ImpersonationEndedByRevocation is a session ended administratively
	// (DestroyImpersonatedSessions).
	ImpersonationEndedByRevocation ImpersonationEndReason = "Revoked"
	// ImpersonationEndedByExpiry is a session whose hard cap or idle timeout
	// passed, observed when the next request was validated.
	ImpersonationEndedByExpiry ImpersonationEndReason = "Expired"
	// ImpersonationEndedByRelease is a session the actor ended through
	// EndImpersonation to return to their own session.
	ImpersonationEndedByRelease ImpersonationEndReason = "Released"
)

type ImpersonationEvent

type ImpersonationEvent struct {
	Kind          ImpersonationEventKind
	Impersonation *Impersonation
	// Operation names what was refused: the handler for IdentityOperationBlocked, the
	// method and path for WriteBlocked; empty otherwise.
	Operation string
	At        time.Time
}

ImpersonationEvent is delivered to the application's audit hook for each lifecycle event of an impersonated session.

type ImpersonationEventKind

type ImpersonationEventKind string

ImpersonationEventKind identifies a lifecycle event of an impersonated session.

const (
	// ImpersonationStarted fires when an impersonated session is established.
	ImpersonationStarted ImpersonationEventKind = "Started"
	// ImpersonationEnded fires when the end of an impersonated session is
	// observed; the record's EndReason says how.
	ImpersonationEnded ImpersonationEventKind = "Ended"
	// ImpersonationIdentityOperationBlocked fires when an impersonated
	// session attempts an identity operation the library refuses (a password
	// or username change on the impersonated user, or user management under
	// a mask); Operation names the handler.
	ImpersonationIdentityOperationBlocked ImpersonationEventKind = "IdentityOperationBlocked"
	// ImpersonationWriteBlocked fires when a read-only impersonated session
	// attempts a non-safe HTTP request that the EnforceReadOnlyMask middleware
	// refuses; Operation is the method and path ("POST /api/partners").
	ImpersonationWriteBlocked ImpersonationEventKind = "WriteBlocked"
)

type ImpersonationQuery

type ImpersonationQuery struct {
	// Actor limits the listing to sessions established by this actor.
	Actor string
	// Principal limits the listing to sessions operating as this principal (a user or
	// a role). The zero Principal matches any.
	Principal accesstypes.Principal
}

ImpersonationQuery narrows an active-impersonation listing. The zero query lists every active impersonated session; each set field is a required match.

type Invitation

type Invitation struct {
	// ID is the invitation's row.
	ID impulse.UUID
	// Email is the address the invitation was mailed to.
	Email string
	// Name is the person's name as the inviter typed it, "" when they gave none. It is
	// written on the account the acceptance creates when the sign-in asserts no name of
	// its own, and on an existing account that holds none.
	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 names them.
	RoleNames []string
	// InvitedByUserID is the user who sent it, null when unknown.
	InvitedByUserID impulse.NullUUID
	// ExpiresAt is when the invitation stops being accepted.
	// CreatedAt is when it was sent, ExpiresAt when it stops standing.
	CreatedAt time.Time
	ExpiresAt time.Time
	// 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 carries one names no tenant (TenantID is "") and no roles:
	// the application's acceptance hook makes the tenant and seats the person in it.
	NewTenant *NewTenant
	// SignInMethod and SignInConnection are how the person accepting signed in: the
	// method and the connection of the identity the sign-in carries (a password; the
	// Google Workspace or the Microsoft Entra tenant of a sign-in through a directory),
	// and of the session's first auth event for a person who accepts while signed in.
	// The sign-in sets them before the acceptance hook runs, which reads them to make
	// the directory the person came through the new tenant's; both are empty until
	// then.
	SignInMethod     AuthMethod
	SignInConnection string
	// Accepted is set by the sign-in: whether this sign-in accepted the invitation.
	Accepted bool
}

Invitation is a live invitation as a sign-in carries it: the invitation the browser opened before the person signed in or signed up, read from its cookie. The sign-in accepts it once the user is known, in a transaction of its own after the user is resolved and before the sign-in policy decides: the invitation is consumed, the user's address is set from it when the user holds no verified address, and the application's acceptance hook grants the roles it names, so the tenant policy sees the membership. Accepted says whether that happened; it is false when the invitation had expired or been used meanwhile, and the sign-in then goes on without it.

type LoginRefusal

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

LoginRefusal is a refused login: the code the login page receives and the cause the log receives. Unwrap returns the cause, so an httpio client message in it still answers httpio.Message and the log handler's status, and errors.Is and errors.As see the same chain as before the code was attached.

func (*LoginRefusal) Code

func (r *LoginRefusal) Code() LoginRefusalCode

Code is the code the login page receives.

func (*LoginRefusal) Error

func (r *LoginRefusal) Error() string

Error names the code and the cause.

func (*LoginRefusal) Unwrap

func (r *LoginRefusal) Unwrap() error

Unwrap returns the cause.

type LoginRefusalCode

type LoginRefusalCode string

LoginRefusalCode names why a login was refused. It is the wire contract between the session module and a login page: a refused OIDC login redirects the browser to LoginURL?code=<code>, and the page maps the code to text it holds itself, showing nothing for a code it does not know. No text travels in the URL. The library's codes are the constants below; an application's custom session data resolver may refuse with a code of its own through NewLoginRefusal. See the "Login refusal codes" section of the README.

const (
	// RefusedIdentityRejected is the code for an external identity the application's
	// user resolver rejected (for example, no invite or roster entry).
	RefusedIdentityRejected LoginRefusalCode = "identity_rejected"
	// RefusedByPolicy is the code for a sign-in the application's policy denied (for
	// example, password sign-in for a tenant that requires SSO).
	RefusedByPolicy LoginRefusalCode = "policy_denied"
	// RefusedUserDisabled is the code for a sign-in to a disabled user.
	RefusedUserDisabled LoginRefusalCode = "user_disabled"
	// RefusedPendingExpired is the code for a confirmation or MFA step that arrived
	// after its pending identity expired.
	RefusedPendingExpired LoginRefusalCode = "pending_expired"
	// RefusedNoEmail is the code for an external identity with no email address where
	// the application requires one, and for one with no sign-in name where a standard
	// account rule needs it as the username.
	RefusedNoEmail LoginRefusalCode = "no_email"
	// RefusedNotInvited is the code for an identity that is not linked yet and matches
	// no pre-created user, through a sign-in method that is invite only.
	RefusedNotInvited LoginRefusalCode = "not_invited"
	// RefusedInvitationOnly is the code for an identity that is not linked yet and
	// matches no pre-created user, from a directory a tenant declares with no default
	// seat: the tenant admits its people by invitation, the sign-in carried none, and
	// no account is created.
	RefusedInvitationOnly LoginRefusalCode = "invitation_only"
	// RefusedInvitationExpired is the code for a sign-in that an invitation alone
	// admitted, through a sign-in method that is invite only, whose invitation had expired
	// or been used by the time the sign-in accepted it.
	RefusedInvitationExpired LoginRefusalCode = "invitation_expired"
	// RefusedInvitationAddress is the code for a sign-in or an acceptance that carried
	// an invitation for another address. An invitation is accepted only by the account
	// it was mailed to: the address the sign-in asserts, the directory's for an external
	// identity and the account's own for a password one or a person signed in, differs
	// from the invited one, so the sign-in or acceptance is refused, the invitation left
	// standing and nothing consumed. An account that holds no address accepts by the
	// link. The login page names the invited address and asks for a sign-in with that
	// account.
	RefusedInvitationAddress LoginRefusalCode = "invitation_address"
	// RefusedGuestAccount is the code for an identity that is a guest of its directory
	// (Identity.Guest), which the standard account rule refuses.
	RefusedGuestAccount LoginRefusalCode = "guest_account"
	// RefusedUnlistedTenant is the code for an Entra token from a tenant the
	// registration's Tenants slot does not admit.
	RefusedUnlistedTenant LoginRefusalCode = "unlisted_tenant"
	// RefusedPersonalAccount is the code for an Entra token of a Microsoft personal
	// account under a registration that admits work or school accounts only.
	RefusedPersonalAccount LoginRefusalCode = "personal_account"
	// RefusedNoTenant is the code for a person who is a member of no tenant, under the
	// tenant policy (signin.TenantPolicy), which admits such a person only when it was
	// built with signin.AdmitWithoutTenant.
	RefusedNoTenant LoginRefusalCode = "no_tenant"
	// RefusedConnectionNotInTenant is the code for a sign-in through a directory by a
	// person whose every tenant admits its people through its own directory only, none
	// of which is the directory the sign-in came through, under the tenant policy.
	RefusedConnectionNotInTenant LoginRefusalCode = "connection_not_in_tenant"
	// RefusedDirectoryOnly is the code for a sign-in that is not through a directory (a
	// password, a personal account, a session the application starts itself) by a
	// person whose every tenant admits its people through its own directory only,
	// under the tenant policy.
	RefusedDirectoryOnly LoginRefusalCode = "directory_only"
	// RefusedOtherTenant is the code for a role in a tenant that is refused because the
	// person belongs to another tenant, in an application where a person belongs to
	// one (the identity package's WithOneTenantPerPerson). The session library never
	// answers it itself: the application's hooks do, and a sign-in ends on it when the
	// invitation it carries, or the default role of the directory it came through,
	// would seat the person in a second tenant.
	RefusedOtherTenant LoginRefusalCode = "other_tenant"
	// RefusedOrganizationAccountRequired is the code for a sign-in or an acceptance that
	// carried an invitation which makes a tenant entered through its directory only
	// (NewTenant.DirectoryOnly), by a person who did not come through an organization's
	// directory: a password, a personal account, a session the application started
	// itself. Nothing is written, no tenant is made and the invitation stands; the
	// login page asks for a sign-in with the organization's account.
	RefusedOrganizationAccountRequired LoginRefusalCode = "organization_account_required"
	// RefusedOrganizationHasTenant is the code for a sign-in or an acceptance that
	// carried an invitation which makes a tenant (NewTenant), through a directory
	// another tenant already has: a directory belongs to one tenant, so no second
	// tenant is made for the organization, and the invitation stands. The session
	// library never answers it itself: the application's acceptance hook does, in the
	// transaction it is handed, which fails with it.
	RefusedOrganizationHasTenant LoginRefusalCode = "organization_has_tenant"
	// RefusedInvalidCode is the code for an email code that is not the one sent; the
	// code sent stands, with one fewer attempt left.
	RefusedInvalidCode LoginRefusalCode = "invalid_code"
	// RefusedCodeExpired is the code for an email code entered after the one sent
	// expired, was used, or took its last attempt; the page asks for a new one.
	RefusedCodeExpired LoginRefusalCode = "code_expired"
)
const (
	// RefusedInternalError is the code for a fault the module does not classify: a
	// store error, a role-store error, a claims payload that would not decode, a
	// resolver error that is neither a LoginRefusal nor a client message.
	RefusedInternalError LoginRefusalCode = "internal_error"
	// RefusedByApplication is the code for a custom session data resolver that refused
	// the login with an httpio client message and no code. The message stays in the
	// log; the page shows its own sentence.
	RefusedByApplication LoginRefusalCode = "login_refused"
	// RefusedNoOIDCCookie is the code for a callback that arrived without the cookie the
	// login route set.
	RefusedNoOIDCCookie LoginRefusalCode = "no_oidc_cookie"
	// RefusedInvalidState is the code for a callback whose state parameter does not match
	// the login this browser started.
	RefusedInvalidState LoginRefusalCode = "invalid_state"
	// RefusedInvalidPKCE is the code for a login cookie that carries no usable PKCE
	// verifier.
	RefusedInvalidPKCE LoginRefusalCode = "invalid_pkce"
	// RefusedTokenExchange is the code for a provider that refused to exchange the
	// authorization code for tokens.
	RefusedTokenExchange LoginRefusalCode = "token_exchange_failed"
	// RefusedNoIDToken is the code for a token response that carried no id_token.
	RefusedNoIDToken LoginRefusalCode = "no_id_token"
	// RefusedIDTokenVerification is the code for an ID token that failed signature,
	// issuer, audience, or expiry verification.
	RefusedIDTokenVerification LoginRefusalCode = "verify_id_token_failed"
	// RefusedClaimsParse is the code for a verified ID token whose claims would not
	// decode.
	RefusedClaimsParse LoginRefusalCode = "parse_claims_failed"
	// RefusedNotWorkspaceMember is the code for a Google user outside the Workspace
	// domain the application restricts logins to.
	RefusedNotWorkspaceMember LoginRefusalCode = "not_workspace_member"
	// RefusedEmailNotVerified is the code for a Google user whose email address is
	// not verified.
	RefusedEmailNotVerified LoginRefusalCode = "email_not_verified"
	// RefusedOrganizationMismatch is the code for a WorkOS profile that belongs to
	// another organization than the login requested.
	RefusedOrganizationMismatch LoginRefusalCode = "organization_mismatch"
	// RefusedNoRoles is the code for a login that role synchronization left with no
	// recognized role.
	RefusedNoRoles LoginRefusalCode = "no_roles"
	// RefusedNoEmailClaim is the code for a Google ID token that carries no email claim.
	RefusedNoEmailClaim LoginRefusalCode = "no_email_claim"
	// RefusedPasswordChangeRequired is the code every request of a user who must change
	// a password an operator set is refused with (403) until the change, but the
	// password change itself, the session read and the logout: the login page shows the
	// change form. An Auth answers it from ValidateSession.
	RefusedPasswordChangeRequired LoginRefusalCode = "password_change_required"
)
const RefusedTooManyAttempts LoginRefusalCode = "too_many_attempts"

RefusedTooManyAttempts is the code for a password attempt on a name whose failed attempts reached the limit: the name is refused until its lock passes, whether a user exists under it or not. The answer is 429 with the wait in the body (retryAfter, seconds) and the Retry-After header; RetryAfterOf reads the wait from the error.

const RefusedTooManyEmails LoginRefusalCode = "too_many_emails"

RefusedTooManyEmails is the code for a sign-in code or link asked for an address that reached its limit of mail: the address was sent as many codes and links as the limit allows, none of them used, and is sent no more until its lock passes. A code or link that is used resets the count. It is told apart from RefusedTooManyAttempts so a page can say that the mail is held, not that a password was refused. The answer is 429 with the wait in the body (retryAfter, seconds) and the Retry-After header; RetryAfterOf reads the wait from the error.

func LoginRefusalCodeOf

func LoginRefusalCodeOf(err error) LoginRefusalCode

LoginRefusalCodeOf answers the code a refused login redirects with. A LoginRefusal in err's chain answers its code. Otherwise an httpio client message in the chain answers RefusedByApplication: the application refused on purpose, and its text stays in the log. Otherwise RefusedInternalError.

type Look added in v0.5.0

type Look struct {
	// Scheme is SchemeLight or SchemeDark, "" for none chosen.
	Scheme string `json:"scheme,omitempty"`
	// Palette is the id of a palette as the application names its palettes, "" for
	// none chosen. The session library does not know the palettes: a page drops an id
	// its application no longer offers.
	Palette string `json:"palette,omitempty"`
}

Look is the look a person chose for the application's pages: light or dark, and one of the palettes the application offers. The user keeps it, so it follows the person to every browser they sign in from; nobody else sets it. Either half may be none: the page then draws its default.

func CleanLook added in v0.5.0

func CleanLook(look Look) (Look, error)

CleanLook is a look as a user row keeps it: the scheme one of the two or none, the palette's id without the space around it. A scheme that is neither, a palette id longer than MaxPaletteLength, and one that is not text on one line (a control character in it) are refused as a bad request. Everything that writes a look holds it to this one rule.

func (Look) IsZero added in v0.5.0

func (l Look) IsZero() bool

IsZero reports whether the look names nothing: no scheme and no palette.

type NewSessionReason

type NewSessionReason string

NewSessionReason identifies why a new session is being created, allowing a custom session data resolver to vary its behavior by trigger.

const (
	// ReasonIdentityLinked indicates a session created when a new external identity
	// was linked to an existing user after a password confirmation.
	ReasonIdentityLinked NewSessionReason = "IdentityLinked"
	// ReasonStepUp indicates a session regenerated after a step-up (MFA) completed.
	ReasonStepUp NewSessionReason = "StepUp"
)
const (
	// ReasonLogin indicates the session is being created by an interactive credential login.
	ReasonLogin NewSessionReason = "Login"
	// ReasonExternalAuth indicates the session is being created for a user the
	// application authenticated itself (StartAuthenticatedSession); the sign-in policy
	// decides it like a login.
	ReasonExternalAuth NewSessionReason = "ExternalAuth"
	// ReasonRegeneration indicates an existing authenticated session is being replaced
	// with a new session ID (e.g. after a password change). Custom session data is
	// resolved fresh for the new session; it does not carry over.
	ReasonRegeneration NewSessionReason = "Regeneration"
	// ReasonPreauth indicates a trust-the-caller stepping-stone session with no user
	// record (e.g. MFA-pending enrollment flows).
	ReasonPreauth NewSessionReason = "Preauth"
	// ReasonImpersonation indicates an impersonated session being established
	// (StartImpersonatedSession): Username is the session's effective identity — the
	// impersonated user, or the actor for a role principal — and UserID is the
	// impersonated user's record ID, or the zero UUID for a role principal.
	ReasonImpersonation NewSessionReason = "Impersonation"
)

type NewSessionRequest

type NewSessionRequest struct {
	// Reason identifies the trigger creating this session.
	Reason NewSessionReason
	// Username is the username the session is created for.
	Username string
	// UserID is the user record's ID. It is the zero UUID for session types that do
	// not track user records (e.g. preauth).
	UserID impulse.UUID
	// CustomData is caller-supplied custom session data for this creation: nil, or a
	// pointer to the struct type the storage's custom session data configuration was
	// built for. When non-nil it is written atomically with the session insert and the
	// configured resolver is NOT invoked for this creation (per-call data wins). It
	// requires a custom session data configuration on the storage.
	CustomData any
	// Claims holds the raw claims of the verified identity that establishes the session
	// (Identity.Claims): the ID token's claims for an OpenID Connect sign-in, the profile
	// for a WorkOS one. It is nil when the identity carries none (a password sign-in, a
	// session the application starts) and for a session no identity establishes.
	// Resolvers unmarshal the fields they need — the library does not curate a claims
	// struct.
	Claims json.RawMessage
	// Identity is the verified identity establishing an Auth session. It is nil for a
	// session no sign-in establishes: a preauth session, a regeneration, an
	// impersonation.
	Identity *Identity
	// ProviderSessionID is the identity provider's session id the sign-in carried (an
	// OpenID Connect sid claim), which a provider-initiated logout names; "" when the
	// method has none. ProviderSessionIssuer is the registration's issuer it belongs
	// to, set with it or not at all. The session row records both.
	ProviderSessionID     string
	ProviderSessionIssuer string
	// RoleNames are the role names the sign-in method asserted for the person, which
	// the method reconciles once the session exists. They are nil when the method
	// synchronizes no roles, and never nil when it does: "no roles asserted" is an
	// empty list, which a standard account rule refuses (no_roles) before it writes a
	// row.
	RoleNames []string
	// AuthEvents are the auth events the new session records, in order, with the
	// session row. An impersonated session records its impersonation event first. When
	// AuthEvents is empty, a session that is not impersonated records one event for
	// Identity's method. An event with a zero At takes the session's creation time.
	// Events are written only when the storage has an auth events table.
	AuthEvents []AuthEvent
	// User is the user an Auth sign-in resolved to and how. The storage sets it
	// once the user is known, before the sign-in policy and the custom session data
	// resolver run, and leaves it set after the insert returns. It is nil while the
	// account rules run and for a session no sign-in establishes.
	User *SignInUser
	// Invitation is the live invitation the browser carries into this sign-in, nil
	// for none. The sign-in accepts it once the user is known and reports the outcome
	// in Invitation.Accepted; the application's acceptance hook runs in that
	// transaction. The sign-in policy runs afterwards and may read it.
	Invitation *Invitation
}

NewSessionRequest carries the inputs to a new-session creation. It is a struct so future fields (e.g. prior custom session data) can be added without breaking resolvers.

type NewTenant added in v0.5.0

type NewTenant struct {
	// Name is what people will call the tenant. The invitation page shows it to the
	// invited person before they sign in.
	Name string `json:"name"`
	// DirectoryOnly says the tenant is to be entered through its directory only, so
	// the invitation is accepted through an organization's directory alone (a Google
	// Workspace, a Microsoft Entra tenant): a sign-in by password or with a personal
	// account is refused (RefusedOrganizationAccountRequired), nothing is written and
	// the invitation stands.
	DirectoryOnly bool `json:"directoryOnly,omitempty"`
	// Details are the application's own details of the tenant, a JSON document its
	// acceptance hook makes the tenant from. The library stores them and hands them
	// to the hook; it reads nothing in them and serves them nowhere.
	Details json.RawMessage `json:"details,omitempty"`
}

NewTenant is the tenant an invitation makes when its first sign-in accepts it: an organization is brought into the application by inviting one person, and that person's sign-in makes the tenant from what the invitation carries. The mail links table keeps it as a JSON document on the invitation's row.

type PendingIdentity

type PendingIdentity struct {
	Identity Identity
	Reason   PendingReason
	// UserID and Username name the user the identity waits on. This includes an
	// user the sign-in has just provisioned.
	UserID    impulse.NullUUID
	Username  string
	ExpiresAt time.Time
	// ReturnURL is the path the sign-in returns to once it completes. It is empty for
	// the root.
	ReturnURL string
	// Factors are the methods the sign-in policy accepts for the MFA step, for
	// PendingMFA; none means any.
	Factors []AuthMethod
}

PendingIdentity is a verified identity that waits for a password confirmation or MFA before it becomes a session. See "What a pending identity is" in the README.

type PendingReason

type PendingReason string

PendingReason says why a verified identity is waiting instead of becoming a session.

const (
	// PendingConfirmation means the identity resolves to an existing user that has a
	// password. The user must enter that password before the identity is linked.
	PendingConfirmation PendingReason = "confirmation"
	// PendingMFA means the sign-in policy requires the application's MFA step before
	// the session is established.
	PendingMFA PendingReason = "mfa"
)

type SessionData

type SessionData struct {
	*SessionInfo
	CustomData    any
	Impersonation *Impersonation
	Principal     accesstypes.Principal
	// UserID is the user (SessionUsers.Id) the session belongs to. For a
	// user-principal impersonation it is the impersonated user. It is null for preauth
	// sessions and role-principal impersonations.
	// It is what the permission store names the person by (User).
	UserID impulse.NullUUID
	// AuthenticatedAt is when the session's most recent authentication step completed.
	AuthenticatedAt time.Time
	// ProviderSessionID is the identity provider's session id the sign-in carried; ""
	// when the method has none or the session is not an Auth session.
	// ProviderSessionIssuer is the issuer that id belongs to: a provider's session id is
	// unique only within its issuer, so a provider-initiated logout names both.
	ProviderSessionID     string
	ProviderSessionIssuer string
	// AuthEvents lists how the session was authenticated, oldest first. It is empty
	// unless the storage is configured with an auth events table.
	AuthEvents []AuthEvent
	// Token is the bearer token that authenticated a request on a machine outlet; nil
	// for a browser session. Such a request has no session row: the token stands in
	// for one, its id as the session id and its issue as the authentication.
	Token *TokenInfo
}

SessionData pairs a SessionInfo with optional custom session data. This is stored in the request context internally; consumers should use FromCtx/FromRequest to get the SessionInfo and CustomDataFromCtx[T]/CustomDataFromRequest[T] to get the strongly typed custom data.

CustomData is nil when no custom session data configuration is attached to the storage. When one is attached, it holds a *T (the configuration's struct type); a session without a custom data row yields a zero-value *T.

Impersonation is nil for a session that is not impersonated (including every session when the storage has no impersonation configuration); consumers read it through ImpersonationFromCtx, PrincipalFromCtx, ActorFromCtx and MaskFromCtx.

Principal is the authorization subject a configured principal resolver chose for this request (session.WithPrincipalResolver), set at validation and never stored. It is the zero Principal when no resolver is configured or the resolver kept the default, in which case PrincipalFromCtx derives the subject from the impersonation record or the session's own user.

func DataFromCtx

func DataFromCtx(ctx context.Context) *SessionData

DataFromCtx returns the validated session's data from the context, including the user, authentication time and auth events of an Auth session. It panics when the context carries no session, as FromCtx does.

func DataFromRequest

func DataFromRequest(r *http.Request) *SessionData

DataFromRequest returns the validated session's data from the request context.

func (*SessionData) EstablishedBy

func (s *SessionData) EstablishedBy() (event AuthEvent, ok bool)

EstablishedBy returns how the session was established: its first auth event, the method and connection of the sign-in (a password; the Entra tenant id, the Google Workspace or the WorkOS connection of a sign-in through a directory; the actor of an impersonation; the application's own first event of a session it started itself). It is what a tenant's declaration admits or refuses when the session reaches the tenant (signin.TenantDeclaration.Admits). ok is false for a session that records no events: a session Preauth's Login starts, or one on a storage without an auth events table.

func (*SessionData) SecondFactor added in v0.5.0

func (s *SessionData) SecondFactor() (event AuthEvent, ok bool)

SecondFactor returns the second factor the session carries: the first auth event after the one that established it that records one (AuthMethod.SecondFactor), such as the mailed code or a remembered browser standing in for it. It is what the administrators' way into a directory-only tenant asks for beside the password (signin.TenantDeclaration.AdmitsAdministrator). ok is false for a session whose sign-in was all there was, and for one that records no events.

func (*SessionData) User added in v0.5.0

func (s *SessionData) User() accesstypes.User

User returns the session's person as the permission store names them: the id of their account, as text. A username can change and can be the same in two auths; the id of an account does neither, so every membership, every principal and the subject of every row condition is the id. A session that belongs to no account (a preauth session, a role-principal impersonation, whose person is its actor: ActorUserFromCtx) has only its username, and is named by it. A name must therefore never read as an id where sessions of both kinds are asked of one permission store: an Auth refuses an actor from another application whose name does, and an application that runs a pre-authenticated session type beside an Auth over one store keeps the names it hands that type from reading as ids.

type SessionInfo

type SessionInfo struct {
	ID        impulse.UUID
	Username  string
	CreatedAt time.Time
	UpdatedAt time.Time
	Expired   bool
}

SessionInfo struct contains information about a session

func FromCtx

func FromCtx(ctx context.Context) *SessionInfo

FromCtx returns the session information from the context.

func FromRequest

func FromRequest(r *http.Request) *SessionInfo

FromRequest returns the session information from the request context.

type SignInUser

type SignInUser struct {
	// ID is the user (SessionUsers.Id).
	ID impulse.UUID
	// Username is the user's username.
	Username string
	// HasPassword reports whether the user has a password.
	HasPassword bool
	// Source says how the sign-in found the user.
	Source UserSource
	// Tenant is the application's tenant key on the identity's link. It is the stored
	// link's tenant, or the resolution's signin.Tenant for a link made in this sign-in. It is empty
	// for a password sign-in.
	Tenant string
}

SignInUser is the user an Auth sign-in resolved to. NewSessionRequest.User carries it to the sign-in policy and the custom session data resolver.

func (*SignInUser) Linked

func (a *SignInUser) Linked() bool

Linked reports whether the sign-in linked its identity to the user, either to an existing user or to one it provisioned.

func (*SignInUser) Provisioned

func (a *SignInUser) Provisioned() bool

Provisioned reports whether the sign-in created the user.

type TokenInfo

type TokenInfo struct {
	ID impulse.UUID
	// Kind is TokenKindApplication or TokenKindAccess.
	Kind string
	// Name is the name the person gave an application token; "" for an access token.
	Name string
	// ClientID is the client a device grant was issued to; "" for an application token.
	ClientID string
	// Outlet names the machine outlet the token was issued for and validated on.
	Outlet string
}

TokenInfo is the credential of a request a machine outlet validated (session.MachineOutlet.ValidateToken): which token acts for the person, of which kind, under what name or for which client, and for which outlet. It is on the context's SessionData; a browser session carries none.

func TokenFromCtx

func TokenFromCtx(ctx context.Context) (*TokenInfo, bool)

TokenFromCtx returns the token that authenticated the request in ctx and true, or nil and false for a browser session. It panics when no session is in the context, like FromCtx.

func TokenFromRequest

func TokenFromRequest(r *http.Request) (*TokenInfo, bool)

TokenFromRequest returns the token that authenticated the request and true, or nil and false for a browser session. It panics when no session is in the context, like FromRequest.

func (*TokenInfo) Attributes

func (t *TokenInfo) Attributes() []Attribute

Attributes renders the token as its evidence attributes.

type UserInfo

type UserInfo struct {
	ID       impulse.UUID `spanner:"Id"           db:"Id"`
	Username string       `spanner:"Username"     db:"Username"`
	Disabled bool         `spanner:"Disabled"     db:"Disabled"`
	// PasswordChangeRequired is set while the user must change a password an operator
	// set before anything else is served; Auth sessions only.
	PasswordChangeRequired bool `spanner:"PasswordChangeRequired" db:"PasswordChangeRequired"`
	// Email is the user's email address, nil for none, and EmailVerifiedAt when the
	// person proved they read it, nil while it is unverified; Auth sessions only. An
	// unverified address is trusted for nothing.
	Email           *string    `spanner:"Email"           db:"Email"`
	EmailVerifiedAt *time.Time `spanner:"EmailVerifiedAt" db:"EmailVerifiedAt"`
	// Name is the person's name as people read it, nil for none; Auth sessions only. It
	// identifies nobody: Username does.
	Name *string `spanner:"Name" db:"Name"`
	// Look is the look the person chose for the application's pages, the zero value
	// for none; Auth sessions only.
	Look Look `spanner:"-" db:"-"`
}

UserInfo struct contains information about a user

func UserFromCtx

func UserFromCtx(ctx context.Context) *UserInfo

UserFromCtx returns the user information from the context

func UserFromRequest

func UserFromRequest(r *http.Request) *UserInfo

UserFromRequest returns the user information from the request context

func (*UserInfo) EmailVerified

func (u *UserInfo) EmailVerified() bool

EmailVerified reports whether the user holds a verified address.

type UserSource

type UserSource string

UserSource says how an Auth sign-in found its user.

const (
	// UserNamed means the sign-in named its user (a password sign-in).
	UserNamed UserSource = "named"
	// UserExistingLink means the identity was already linked to the user.
	UserExistingLink UserSource = "existing-link"
	// UserNewLink means the user resolver linked the identity to an existing
	// user in this sign-in (LinkIdentity).
	UserNewLink UserSource = "new-link"
	// UserProvisioned means the user resolver created the user in this sign-in
	// (ProvisionUser) and linked the identity to it.
	UserProvisioned UserSource = "provisioned"
)

Jump to

Keyboard shortcuts

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