Documentation
¶
Overview ¶
Package dbtype contains types used by the database driver packages for session storage.
Index ¶
- Constants
- Variables
- func AuthMethods(names []string) []sessioninfo.AuthMethod
- func InitialAuthEvents(req *sessioninfo.NewSessionRequest, imp *InsertImpersonation) []sessioninfo.AuthEvent
- func IsExternal(identity *sessioninfo.Identity) bool
- func IsReservedCustomColumn(name string) bool
- func IsReservedCustomUserColumn(name string) bool
- func MaskColumn(mask accesstypes.PermissionMask) *string
- func MaskFromColumn(col *string) accesstypes.PermissionMask
- func MethodNames(methods []sessioninfo.AuthMethod) []string
- func NewTenantColumn(tenant *sessioninfo.NewTenant) (*string, error)
- func NewTenantFromColumn(column *string) (*sessioninfo.NewTenant, error)
- func OptionalString(s string) *string
- func UnlinkKeepsSignIn(links []*SessionIdentity, unlinked impulse.UUID, ...) error
- func ValidateInsertUser(user *InsertSessionUser, usernameIsEmail bool) error
- func ValidateTableName(name string) error
- type CustomDataCodec
- type DeviceCode
- type DeviceCodeStatus
- type FactorCode
- type Impersonation
- type InsertImpersonation
- type InsertSession
- type InsertSessionUser
- type MailLink
- type MailLinkKind
- type PasswordProof
- type PendingSignIn
- type Session
- type SessionData
- type SessionIdentity
- type SessionUser
- type SessionUserColumns
- type SignInAttemptLimit
- type SignInAttempts
- type SignInConflict
- type SignInMethod
- type Token
- type TokenKind
- type TokenRevocation
- type TrustedDevice
- type User
Constants ¶
const ( SpannerTagKey = "spanner" PostgresTagKey = "db" )
Struct tag keys used to derive custom session data columns per backend.
const ( PrincipalKindUser = sessioninfo.PrincipalKindUser PrincipalKindRole = sessioninfo.PrincipalKindRole )
Principal kinds as stored in the impersonation table's PrincipalKind column.
const ( SessionsTable = "Sessions" UsersTable = "SessionUsers" IdentitiesTable = "SessionIdentities" PendingSignInsTable = "SessionPendingSignIns" SignInAttemptsTable = "SessionSignInAttempts" MailLinksTable = "SessionMailLinks" SignInMethodsTable = "SessionSignInMethods" FactorCodesTable = "SessionFactorCodes" TrustedDevicesTable = "SessionTrustedDevices" TokensTable = "SessionTokens" DeviceCodesTable = "SessionDeviceCodes" AuthEventsTable = "SessionAuthEvents" ImpersonationsTable = "SessionImpersonations" )
The library's own names for an Auth's tables: what each driver reads and writes until an option or a storage constructor names another, what the library's schema sets create (schema/spanner/migrations and schema/spanner/auth/migrations), and what an Auth kept under a prefix leads with the prefix (session.TablesWithPrefix).
const SessionIDColumn = "SessionId"
SessionIDColumn is the primary-key column of the custom session data table, referencing the session table's primary key.
const UserIDColumn = "UserId"
UserIDColumn is the primary-key column of the custom user data table, referencing the user table's primary key (SessionUsers.Id).
Variables ¶
var ErrLastSignInMethod = errors.New("sessionstorage: the identity is the user's last means of sign-in")
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; see sessionstorage for its documentation.
var ErrNoAuthEvents = errors.New("auth events are not configured: attach WithAuthEvents")
ErrNoAuthEvents is returned when an auth event is appended to a session of a store that records none; see sessionstorage for its documentation.
var ErrPasswordChanged = errors.New("sessionstorage: the user's password has changed since it was proved")
ErrPasswordChanged is returned when a password write that follows a proof of the password finds that the user no longer holds the hash that was proved; see sessionstorage for its documentation.
var ErrPasswordHeld = errors.New("sessionstorage: the user already holds a password")
ErrPasswordHeld is returned when a user's first password is written for a user who holds a password already; see sessionstorage for its documentation.
var ErrTokenReuse = errors.New("the refresh token was presented again after its rotation; its family is revoked")
ErrTokenReuse is returned by a refresh exchange that was given a refresh token already rotated: the whole family is revoked, since a rotated token presented again means two parties hold it.
Functions ¶
func AuthMethods ¶
func AuthMethods(names []string) []sessioninfo.AuthMethod
AuthMethods reverses MethodNames.
func InitialAuthEvents ¶
func InitialAuthEvents(req *sessioninfo.NewSessionRequest, imp *InsertImpersonation) []sessioninfo.AuthEvent
InitialAuthEvents returns the auth events a new session records, oldest first. An impersonated session records its impersonation first, with the actor as the connection. Then come req.AuthEvents or, when there are none and the session is not impersonated, the method that verified req.Identity. The events added here have a zero At, which the driver writes as the database's time at commit; an event of req.AuthEvents keeps the At it carries.
func IsExternal ¶
func IsExternal(identity *sessioninfo.Identity) bool
IsExternal reports whether identity is resolved through the identities table. A password identity names its user directly (req.UserID), and an impersonation identity belongs to the impersonation flow.
func IsReservedCustomColumn ¶
IsReservedCustomColumn checks if a given column name is reserved and therefore cannot be used as a custom session data column name.
func IsReservedCustomUserColumn ¶
IsReservedCustomUserColumn checks if a given column name is reserved and therefore cannot be used as a custom user data column name.
func MaskColumn ¶
func MaskColumn(mask accesstypes.PermissionMask) *string
MaskColumn renders a mask into its column form: nil for the unrestricted mask, otherwise the sorted allowlist joined with commas (the empty string for the mask that allows nothing).
func MaskFromColumn ¶
func MaskFromColumn(col *string) accesstypes.PermissionMask
MaskFromColumn parses a mask column: NULL is the unrestricted mask, any other value (the empty string included) is a restricted allowlist.
func MethodNames ¶
func MethodNames(methods []sessioninfo.AuthMethod) []string
MethodNames renders methods as the strings a database array holds; nil stays nil.
func NewTenantColumn ¶ added in v0.5.0
func NewTenantColumn(tenant *sessioninfo.NewTenant) (*string, error)
NewTenantColumn renders the tenant an invitation makes as the mail links table's NewTenant column holds it: its JSON document, or nil, which is NULL, for a link that makes none.
func NewTenantFromColumn ¶ added in v0.5.0
func NewTenantFromColumn(column *string) (*sessioninfo.NewTenant, error)
NewTenantFromColumn reads the mail links table's NewTenant column back: the tenant the invitation makes, or nil for a NULL.
func OptionalString ¶
OptionalString returns nil for the empty string, so an optional column stores NULL.
func UnlinkKeepsSignIn ¶ added in v0.5.0
func UnlinkKeepsSignIn(links []*SessionIdentity, unlinked impulse.UUID, signsIn func(method sessioninfo.AuthMethod, connection string) bool) error
UnlinkKeepsSignIn judges the unlink of the identity unlinked from a user that holds no password and whose identities are links, as the unlinking transaction read them. It is nil while another of them is a means of sign-in by signsIn, the caller's judgment of a link by its method and connection, and the refusal otherwise (ErrLastSignInMethod, a Conflict): an identity that signs nobody in is no means of sign-in, however many of them remain. A nil signsIn judges none to be one.
func ValidateInsertUser ¶
func ValidateInsertUser(user *InsertSessionUser, usernameIsEmail bool) error
ValidateInsertUser refuses a new user row the store cannot write: on a store whose usernames are the addresses (usernameIsEmail), an Email that is not the username, since the database derives the address from the username; a verified mark without an address; and a name CleanName refuses.
func ValidateTableName ¶
ValidateTableName refuses a table name that is not a plain identifier: a letter or underscore, then up to 127 letters, digits or underscores. Every table-name setter of both drivers runs it, so a name reaches SQL validated whichever way it was set.
Types ¶
type CustomDataCodec ¶
type CustomDataCodec struct {
// contains filtered or unexported fields
}
CustomDataCodec maps a custom session data struct type T to its database columns, derived from struct tags once at construction. It provides the erased operations the database drivers need: creating values, extracting column-ordered field values for writes, and producing column-ordered field addresses for scans.
func NewCustomDataCodec ¶
func NewCustomDataCodec(structType reflect.Type, tagKey string) (*CustomDataCodec, error)
NewCustomDataCodec builds a codec for structType using the given struct tag key ("spanner" or "db"). structType must be a non-pointer struct type. Columns are taken from the tag (comma options stripped); untagged exported fields use the field name; a tag of "-" skips the field. Duplicate columns, embedded pointer structs, and types with no persistable fields are errors.
func (*CustomDataCodec) Columns ¶
func (c *CustomDataCodec) Columns() []string
Columns returns the ordered column names (excluding SessionId, which is never mapped).
func (*CustomDataCodec) FieldAddrs ¶
func (c *CustomDataCodec) FieldAddrs(data any) ([]any, error)
FieldAddrs returns pointers to the fields of data (*T) aligned with Columns(), suitable as positional scan destinations.
func (*CustomDataCodec) NewStruct ¶
func (c *CustomDataCodec) NewStruct() any
NewStruct returns a pointer to a new zero value of the struct type (*T as any).
func (*CustomDataCodec) StructType ¶
func (c *CustomDataCodec) StructType() reflect.Type
StructType returns the struct type T the codec was built for.
type DeviceCode ¶
type DeviceCode struct {
ID impulse.UUID
DeviceCodeHash []byte
// UserCode is the code the person types, normalized: upper case, no separator.
UserCode string
ClientID string
Outlet string
// UserID is the person who approved the authorization; null while it is pending.
UserID impulse.NullUUID
CreatedAt time.Time
ExpiresAt time.Time
ApprovedAt *time.Time
DeniedAt *time.Time
LastPolledAt *time.Time
ConsumedAt *time.Time
}
DeviceCode is a row of the device codes table: one device authorization a command-line client started (RFC 8628). The client holds the opaque device code and the row keeps its hash; the person is shown the user code. The row is pending until a signed-in person approves or denies it, or it expires; an approved row is consumed once, when the client's poll redeems it for its tokens. CreatedAt, ApprovedAt, DeniedAt, LastPolledAt and ConsumedAt are the database's time; ExpiresAt is the library's deadline, written as given.
type DeviceCodeStatus ¶
type DeviceCodeStatus string
DeviceCodeStatus is what a client's poll of its device code learned.
const ( // DevicePending is a code the person has not decided on yet; poll again after the // interval. DevicePending DeviceCodeStatus = "pending" // DeviceSlowDown is a poll before the interval passed; nothing was read // or written for it, and it polls again after a longer interval. DeviceSlowDown DeviceCodeStatus = "slow_down" // DeviceApproved is a code the person approved, whose tokens were issued, once. DeviceApproved DeviceCodeStatus = "approved" // DeviceDenied is a code the person denied. DeviceDenied DeviceCodeStatus = "denied" // DeviceExpired is a code nobody decided on before the deadline. DeviceExpired DeviceCodeStatus = "expired" )
type FactorCode ¶
type FactorCode struct {
ID impulse.UUID
// PendingID is the pending sign-in the code was sent for.
PendingID impulse.UUID
// Email is the address the code was mailed to.
Email string
CodeHash []byte
Attempts int
CreatedAt time.Time
ExpiresAt time.Time
ConsumedAt *time.Time
}
FactorCode is a row of the factor codes table: one code the library mailed for a pending sign-in's second factor. The mail carries the code and the row keeps its hash, salted by the pending sign-in it belongs to. It is live while it is not consumed and not expired; Attempts counts the guesses made at it, each counted before it is judged, and the Auth consumes it at the limit and judges no guess past it, so a code is guessed at most that many times, however the guesses arrive. A new code for the same pending sign-in consumes the earlier one. CreatedAt and ConsumedAt are the database's time; ExpiresAt is the library's deadline, written as given.
type Impersonation ¶
type Impersonation struct {
SessionID impulse.UUID
ActorUsername string
ActorUserID *impulse.UUID
ActorRealm *string
SourceSessionID *impulse.UUID
PrincipalKind string
PrincipalUserID *string
PrincipalRole *string
Mask *string
Reason *string
StartedAt time.Time
ExpiresAt time.Time
EndedAt *time.Time
EndReason *string
}
Impersonation is the impersonation record row shared by the drivers. Nullable columns are pointers; a nil Mask is the unrestricted mask.
func (*Impersonation) ToSessionInfo ¶
func (i *Impersonation) ToSessionInfo() *sessioninfo.Impersonation
ToSessionInfo converts the row into the public record.
type InsertImpersonation ¶
type InsertImpersonation struct {
ActorUsername string
ActorUserID *impulse.UUID
ActorRealm *string
SourceSessionID *impulse.UUID
PrincipalKind string
PrincipalUserID *string
PrincipalRole *string
Mask *string
Reason *string
ExpiresAt time.Time
}
InsertImpersonation is the caller-supplied part of a new impersonation record; the driver assigns SessionID and writes StartedAt with the database's time at commit. ExpiresAt is the caller's deadline.
func NewInsertImpersonation ¶
func NewInsertImpersonation(imp *sessioninfo.Impersonation) *InsertImpersonation
NewInsertImpersonation renders a sessioninfo.Impersonation into its insert row. Only the caller-supplied fields are read.
type InsertSession ¶
InsertSession is the caller-supplied part of a new session row. The driver writes CreatedAt and UpdatedAt with the database's time at commit, never the application's.
type InsertSessionUser ¶
type InsertSessionUser struct {
// ID is the id the user is created under when the caller chose one; null has the
// driver generate it.
ID impulse.NullUUID `spanner:"-" db:"-"`
Username string `spanner:"Username" db:"Username"`
PasswordHash *securehash.Hash `spanner:"PasswordHash" db:"PasswordHash"`
Disabled bool `spanner:"Disabled" db:"Disabled"`
PasswordChangeRequired bool `spanner:"PasswordChangeRequired" db:"PasswordChangeRequired"`
Email *string `spanner:"Email" db:"Email"`
EmailVerified bool `spanner:"-" db:"-"`
Name *string `spanner:"Name" db:"Name"`
}
InsertSessionUser is the caller-supplied part of a new user row. The driver writes CreatedAt with the database's time at commit. Email, nil for none, is the user's address, written unverified unless EmailVerified says the person has proven it (a sign-up or an invitation the person completed by mail), in which case the driver stamps EmailVerifiedAt with the commit time. On a store whose usernames are the addresses (UsernameIsEmail) the address is the username and Email must be nil or match it. Name, nil for none, is the person's name, written as CleanName leaves it.
type MailLink ¶
type MailLink struct {
ID impulse.UUID
TokenHash []byte
Kind MailLinkKind
// Email is the address the link was mailed to, as given.
Email string
// UserID names the account a verification link or a first-password code belongs
// to; null for the other kinds.
UserID impulse.NullUUID
// TenantID is the tenant an invitation seats the person in, "" for the application's
// global surface or for the other kinds.
TenantID string
// RoleNames are the roles an invitation's acceptance grants; nil for the other
// kinds.
RoleNames []string
// InvitedByUserID is the user who sent an invitation; null when unknown or for the other
// kinds.
InvitedByUserID impulse.NullUUID
// Name is the invited person's name as the inviter typed it; "" for none and for
// the other kinds.
Name string
// NewTenant is the tenant an invitation makes when it is accepted; nil for an
// invitation into a tenant that exists or into the application's global surface,
// and for the other kinds. The table holds it as a JSON document (NewTenantColumn).
NewTenant *sessioninfo.NewTenant
CreatedAt time.Time
ExpiresAt time.Time
ConsumedAt *time.Time
}
MailLink is a row of the mail links table: one single-use link the library mailed. The mail carries an opaque token; the row keeps its hash. It is live while it is not consumed and not expired. CreatedAt and ConsumedAt are the database's time; ExpiresAt is the library's deadline, written as given.
type MailLinkKind ¶
type MailLinkKind string
MailLinkKind is what a mailed link does when it is followed.
const ( // MailLinkInvitation invites an address into the application, or into one of its // tenants, with the roles the row carries. Whoever signs in or signs up at it // accepts it. MailLinkInvitation MailLinkKind = "invitation" // MailLinkVerification verifies an address a signed-in person adds to their own // account; UserID names the account. MailLinkVerification MailLinkKind = "verification" // MailLinkSignUp finishes a sign-up a person started by giving their address: the // follower sets a password and the account is created, the address verified. MailLinkSignUp MailLinkKind = "sign-up" // MailLinkFirstPassword is the code a signed-in person who has no password is // mailed to choose their first one: UserID names the account, Email is the // account's confirmed address, and TokenHash keeps the code's hash, since the mail // carries a code to type and no link to follow. MailLinkFirstPassword MailLinkKind = "first-password" )
func (MailLinkKind) Validate ¶
func (k MailLinkKind) Validate() error
Validate refuses a kind that is not one of the four.
type PasswordProof ¶ added in v0.5.0
type PasswordProof []byte
PasswordProof names the password a sign-in proved, without holding it: the SHA-256 of the password hash the password was compared against, in the text the users table stores. Whatever is inserted on the strength of a password just entered (a session, a pending sign-in, a confirmed link) carries it, and is inserted only while the user's row still answers to it, compared in the inserting transaction (Check): a password changed, reset or removed since it was proved gets nothing. A pending sign-in keeps it in its row, for its completion to be held the same way; the hash itself is kept nowhere but the users table, and its digest says nothing a guess could be tried against, since the salt is part of what was digested. The nil proof is the sign-in no password proved, which is held to nothing.
func ProofOf ¶ added in v0.5.0
func ProofOf(hash *securehash.Hash) (PasswordProof, error)
ProofOf is the proof of a password that was compared against hash: nil for no hash.
func ProofOfStored ¶ added in v0.5.0
func ProofOfStored(text string) PasswordProof
ProofOfStored is the proof a user row answers to whose password hash column holds text.
func (PasswordProof) Check ¶ added in v0.5.0
func (p PasswordProof) Check(held PasswordProof) error
Check answers nil while a user whose row answers to held (User.PasswordProof) still holds the password p proved, and ErrPasswordChanged (a Conflict) once the row holds another hash, or none. The nil proof proved nothing and is held to nothing.
type PendingSignIn ¶
type PendingSignIn struct {
ID impulse.UUID
TokenHash []byte
// Step is why the sign-in waits.
Step sessioninfo.PendingReason
// Registration names the external registration the identity came through; empty
// for a password identity.
Registration string
// Identity is the verified identity, with its claims.
Identity sessioninfo.Identity
// UserID and Username name the user the sign-in waits on.
UserID impulse.NullUUID
Username string
// PasswordProof is the proof of the password the sign-in rests on, nil when no
// password was proved (an external identity's sign-in that waits for its
// confirmation or its factor). A row that carries one names its user, is inserted
// only while the user still holds that password, and completes only while they do.
PasswordProof PasswordProof
// Tenant is the tenant key for the link to be made.
Tenant string
// Events are the steps so far, the sign-in first.
Events []sessioninfo.AuthEvent
// RoleNames are the role names the method asserted at sign-in; nil when the method
// synchronizes no roles.
RoleNames []string
// Factors are the methods the sign-in policy accepts for the MFA step; none means
// any.
Factors []sessioninfo.AuthMethod
// ReturnURL is the sanitized path the sign-in returns to; empty for a password
// sign-in.
ReturnURL string
// ProviderSessionID is the provider's session id the sign-in carried, "" when none,
// and ProviderSessionIssuer the issuer it belongs to.
ProviderSessionID string
ProviderSessionIssuer string
// ExpiresAt is the caller's deadline. CreatedAt and ConsumedAt are the database's:
// an insert writes CreatedAt with its commit time and leaves ConsumedAt null,
// whatever the value carries, and a consumption stamps ConsumedAt.
CreatedAt time.Time
ExpiresAt time.Time
ConsumedAt *time.Time
}
PendingSignIn is a row of the pending sign-ins table: a sign-in that waits for a password confirmation or the application's MFA step, with everything it carried. The browser's pending cookie holds an opaque token; TokenHash is that token's SHA-256. The row is live until ExpiresAt, or until it is consumed once (ConsumedAt).
type Session ¶
type Session struct {
ID impulse.UUID `spanner:"Id" db:"Id"`
Username string `spanner:"Username" db:"Username"`
CreatedAt time.Time `spanner:"CreatedAt" db:"CreatedAt"`
UpdatedAt time.Time `spanner:"UpdatedAt" db:"UpdatedAt"`
Expired bool `spanner:"Expired" db:"Expired"`
}
Session defines the structure for storing session data in the database.
type SessionData ¶
type SessionData struct {
*Session
CustomData any
Impersonation *Impersonation
UserID impulse.NullUUID
AuthenticatedAt *time.Time
// ProviderSessionID is the provider's session id the sign-in carried, "" when none,
// and ProviderSessionIssuer the issuer it belongs to.
ProviderSessionID string
ProviderSessionIssuer string
AuthEvents []sessioninfo.AuthEvent
}
SessionData pairs a Session with optional custom session data and, for an impersonated session, its impersonation record (nil otherwise). UserID and AuthenticatedAt are set only when the user columns are enabled, and AuthEvents only when there is an auth events table.
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 an identity link row. Its fields match sessionstorage.SessionIdentity, which converts from it.
type SessionUser ¶
type SessionUser struct {
ID impulse.UUID `spanner:"Id" db:"Id"`
Username string `spanner:"Username" db:"Username"`
PasswordHash *securehash.Hash `spanner:"PasswordHash" db:"PasswordHash"`
Disabled bool `spanner:"Disabled" db:"Disabled"`
PasswordChangeRequired bool `spanner:"PasswordChangeRequired" db:"PasswordChangeRequired"`
CreatedAt time.Time `spanner:"CreatedAt" db:"CreatedAt"`
LastSignInAt *time.Time `spanner:"LastSignInAt" db:"LastSignInAt"`
Email *string `spanner:"Email" db:"Email"`
EmailVerifiedAt *time.Time `spanner:"EmailVerifiedAt" db:"EmailVerifiedAt"`
Name *string `spanner:"Name" db:"Name"`
LookScheme *string `spanner:"LookScheme" db:"LookScheme"`
LookPalette *string `spanner:"LookPalette" db:"LookPalette"`
}
SessionUser is a person authorized to access the application. PasswordChangeRequired marks a user whose password an operator set (a new user's first password, a reset): the user changes it before anything else. CreatedAt is the database's time at the insert and LastSignInAt its time at the user's latest sign-in, nil before the first. Email is the user's email address, nil for none, and EmailVerifiedAt the database's time at which the person proved they read it, nil while it is unverified; both are nil on a store without the auth schema. An unverified address is trusted for nothing: it may be sent a link, and that is all. Name is the person's name as people read it ("Gale Reyes"), nil for none and on a store without the auth schema: what a directory asserted at a sign-in, an inviter typed, or the person wrote themselves. It identifies nobody: the username does.
func (*SessionUser) EmailVerified ¶
func (u *SessionUser) EmailVerified() bool
EmailVerified reports whether the user holds a verified address.
func (*SessionUser) Look ¶ added in v0.5.0
func (u *SessionUser) Look() sessioninfo.Look
Look is the look the person chose, the zero value for none: the two columns the row keeps it in, each empty where the row holds null.
type SessionUserColumns ¶
type SessionUserColumns struct {
UserID impulse.NullUUID
Authenticated bool
ProviderSessionID *string
ProviderSessionIssuer *string
}
SessionUserColumns holds the user columns of a new session row. UserID is null for a preauth session and a role-principal impersonation. Authenticated says whether the row's AuthenticatedAt takes the database's time at commit; it is false for a preauth session, which authenticates nothing, and the column stays null. ProviderSessionID and ProviderSessionIssuer are null unless the sign-in carried the provider's session id, which is recorded with the issuer it belongs to.
func NewSessionUserColumns ¶
func NewSessionUserColumns(req *sessioninfo.NewSessionRequest) SessionUserColumns
NewSessionUserColumns returns the user columns of a new session for req.
type SignInAttemptLimit ¶
SignInAttemptLimit is the rule a failure is recorded under: Failures within Window lock the name for Lock.
type SignInAttempts ¶
type SignInAttempts struct {
Name string
Failures int64
WindowEndsAt time.Time
LockedUntil *time.Time
UpdatedAt time.Time
// Counted is the answer of the call that recorded a failure (Failed): the failure
// was counted, since the name was not held when it was recorded. A caller that takes
// an attempt before it judges a guess reads it: of failures recorded at once, as many
// as the limit are counted and no more, decided in the transaction that wrote the
// record. It is no column of the table, and a record read back says false.
Counted bool
}
SignInAttempts is a row of the sign-in attempts table: the failed password attempts on one name, known or not, within a window, and the lock those failures earned. It is keyed by the submitted name as the users table normalizes usernames, never by the user row, so an unknown name is counted exactly as a known one. Failures is the count in the window that ends at WindowEndsAt; LockedUntil is set once Failures reached the limit and the name is refused until then. WindowEndsAt and LockedUntil are the caller's deadlines, written as given; UpdatedAt is the database's time at the write.
func (*SignInAttempts) Failed ¶
func (r *SignInAttempts) Failed(name string, now time.Time, limit SignInAttemptLimit) *SignInAttempts
Failed returns the record after a failure at now under limit, the one rule both drivers apply inside their transaction. A record that holds its name is left as it is: a failure during the lock changes nothing, and is not counted. Otherwise the failure counts in the current window, or opens a new one when there is no record, the window has ended or a lock has passed; the failure that reaches the limit locks the name until now plus limit.Lock, and is counted itself. Counted says which it was. UpdatedAt is the driver's to stamp.
type SignInConflict ¶
type SignInConflict int
SignInConflict is a driver's classification of the error a sign-in's transaction ended with.
const ( // NoSignInConflict is any other error. NoSignInConflict SignInConflict = iota // UsernameConflict is the users table refusing a provisioned user's username, // which another user already has. UsernameConflict // IdentityConflict is the identities table refusing a link of an identity that a // racing sign-in linked meanwhile. IdentityConflict // LockConflict is the database ending the transaction to break a deadlock or a // serialization failure between racing sign-ins; the sign-in runs once more. LockConflict )
type SignInMethod ¶ added in v0.5.0
type SignInMethod struct {
Name string
OpenSignUp bool
OpenedFor *string
DefaultRole *string
UpdatedAt time.Time
}
SignInMethod is a row of the sign-in methods table: what an administrator chose, in the running application, for one sign-in method of the Auth, named by the name the method is registered under ("password", or the application's name for an external registration). OpenSignUp says the method admits a person who holds no account and no invitation; OpenedFor is whom the method admitted when it was opened, as the registration's audience spells itself (signin.Audience.Key), nil for a row that opens nothing; DefaultRole names the role such a person is given with their account, as the application's hook understands it, and holds nothing in an application whose people get their roles in a tenant. A method with no row is invite only, which is what a row with OpenSignUp false says too. UpdatedAt is the database's time at the write.
func (*SignInMethod) OpenFor ¶ added in v0.5.0
func (m *SignInMethod) OpenFor(audience string) bool
OpenFor reports whether the row opens its method to a person with no account and no invitation, for a method whose registration admits audience now (signin.Audience.Key). A row is honored for the audience it was opened for and no other: the administrator who opened the method confirmed a sentence that named whom it admits, and a registration that code has since widened, or changed at all, is invite only until it is opened again. No row is invite only, so a nil row is not open, and neither is a row that does not say whom it was opened for.
func (*SignInMethod) Role ¶ added in v0.5.0
func (m *SignInMethod) Role() string
Role is the role the row gives a person who signs up through its method, "" for none and for no row.
type Token ¶
type Token struct {
ID impulse.UUID
TokenHash []byte
Kind TokenKind
// UserID is the person the token acts as.
UserID impulse.UUID
// Outlet names the machine outlet the token was issued for, the only one it is
// accepted on.
Outlet string
// Name is the name the person gave an application token; "" for the tokens of a
// device grant.
Name string
// FamilyID groups a device grant's access and refresh tokens, and every successor a
// refresh issues, so a reuse revokes them together; null for an application token.
FamilyID impulse.NullUUID
// ClientID is the client a device grant was issued to; "" for an application token.
ClientID string
CreatedAt time.Time
ExpiresAt time.Time
LastUsedAt *time.Time
RevokedAt *time.Time
RevokedReason TokenRevocation
}
Token is a row of the tokens table: one credential. The client holds an opaque secret and the row keeps its hash. It is live while it is not revoked and not expired. CreatedAt, LastUsedAt and RevokedAt are the database's time; ExpiresAt is the library's deadline, written as given.
type TokenKind ¶
type TokenKind string
TokenKind is what a row of the tokens table is.
const ( // TokenApplication is a token a person issued to an application of their own: a // bearer credential on a machine outlet that lives until its expiry or its // revocation. TokenApplication TokenKind = "application" // TokenAccess is the short-lived bearer credential a device grant or a refresh // issued to a command-line client. It and its refresh token share a family. TokenAccess TokenKind = "access" // TokenRefresh is the credential a command-line client exchanges for its next // access token. It is never presented on a machine outlet, and it rotates on every // exchange: the one presented is revoked and a successor issued in its family. TokenRefresh TokenKind = "refresh" )
type TokenRevocation ¶
type TokenRevocation string
TokenRevocation says why a token was revoked.
const ( // TokenRevokedByHand is a token the person, or the application on their behalf, // revoked. TokenRevokedByHand TokenRevocation = "revoked" // TokenRevokedRotated is a refresh token a successor replaced at an exchange. TokenRevokedRotated TokenRevocation = "rotated" // TokenRevokedReuse is a token revoked with its family because a rotated refresh // token of the family was presented again. TokenRevokedReuse TokenRevocation = "reuse" // TokenRevokedWithUser is a token revoked with every token of its user. TokenRevokedWithUser TokenRevocation = "user" )
func (TokenRevocation) Validate ¶
func (r TokenRevocation) Validate() error
Validate refuses a reason that is not one of the four.
type TrustedDevice ¶
type TrustedDevice struct {
ID impulse.UUID
UserID impulse.UUID
TokenHash []byte
CreatedAt time.Time
ExpiresAt time.Time
LastUsedAt *time.Time
RevokedAt *time.Time
}
TrustedDevice is a row of the trusted devices table: a browser the person asked to be remembered after a second factor, which then stands in for the factor at the person's next sign-ins until it expires or is revoked. The browser holds an opaque token in the trusted device cookie and the row keeps its hash. It is live while it is not revoked and not expired. CreatedAt, LastUsedAt and RevokedAt are the database's time; ExpiresAt is the library's deadline, written as given.
type User ¶
type User struct {
ID impulse.UUID
Username string
HasPassword bool
Disabled bool
// PasswordProof is the proof the row's password hash answers to (ProofOfStored), nil
// for a user with no password, as UserIn and LockUserIn read it: what a sign-in's
// own proof is checked against in the transaction that inserts on its strength.
PasswordProof PasswordProof
}
User is the part of a user row the sign-in flow decides on.