Documentation
¶
Overview ¶
Device authorization lets an input-constrained device obtain a first-party session.
HTTP request handling for the core authentication endpoints.
Package plainauth embeds authentication in the host application's HTTP server.
Index ¶
- Constants
- Variables
- func HashPassword(ctx context.Context, password string) (string, error)
- func OAuthPopupAdditionalData(ctx context.Context) map[string]any
- func VerifyPasswordHash(ctx context.Context, hash, password string) (bool, error)
- type APIError
- type AccessTokenResult
- type AccountField
- type AccountFieldRule
- type AccountFieldStore
- type AccountInfoResult
- type AccountLifecycleStore
- type AccountSelection
- type AccountStore
- type AdminBootstrapStore
- type AdminCreateUserRequest
- type AdminHostCreateStore
- type AdminOptions
- type AdminPage
- type AdminPermissions
- type AdminQuery
- type AdminRequest
- type AdminResult
- type AdminStore
- type AdminTransaction
- type AdminUserCreator
- type AdminUserFieldTransaction
- type AdminUserFields
- type AnonymousLink
- type AnonymousOptions
- type AnonymousStore
- type Auth
- func (a *Auth) AccountInfo(ctx context.Context, h http.Header, s AccountSelection) (AccountInfoResult, error)
- func (a *Auth) Admin(ctx context.Context, headers http.Header, req AdminRequest) (AdminResult, error)
- func (a *Auth) AdminCreateUser(ctx context.Context, in AdminCreateUserRequest) (*User, error)
- func (a *Auth) BasePath() string
- func (a *Auth) BindOneTapNonce(w http.ResponseWriter, origin, audience, nonce string) error
- func (a *Auth) BootstrapAdmin(ctx context.Context, name, email, password string) (User, error)
- func (a *Auth) CallbackURL(raw string) (string, error)
- func (a *Auth) ChangeEmail(ctx context.Context, h http.Header, newEmail, callback string) error
- func (a *Auth) ChangeEmailOTP(ctx context.Context, h http.Header, newEmail, code string) error
- func (a *Auth) ChangePassword(ctx context.Context, h http.Header, in ChangePasswordInput, meta RequestMeta) (AuthResult, error)
- func (a *Auth) CheckEmailOTP(ctx context.Context, email, code string, purpose EmailOTPPurpose) error
- func (a *Auth) CompleteEmailVerificationOTP(ctx context.Context, email, code string, meta RequestMeta) (AuthResult, error)
- func (a *Auth) ConsumePhoneNumberOTP(ctx context.Context, number, code string) error
- func (a *Auth) CreateEmailOTP(ctx context.Context, email string, purpose EmailOTPPurpose) (string, error)
- func (a *Auth) DeleteUser(ctx context.Context, h http.Header, in DeleteUserInput) (bool, error)
- func (a *Auth) DescribeHTTP() HTTPDescription
- func (a *Auth) ErrorPageURL() string
- func (a *Auth) ExplicitlyTrustedOrigin(raw string) bool
- func (a *Auth) GenerateOneTimeToken(ctx context.Context, h http.Header) (string, error)
- func (a *Auth) GenerateTOTP(secret string) (string, error)
- func (a *Auth) GetAccessToken(ctx context.Context, h http.Header, s AccountSelection) (AccessTokenResult, error)
- func (a *Auth) GetSession(ctx context.Context, headers http.Header) (*SessionResult, error)
- func (a *Auth) HTTPPathDisabled(r *http.Request) bool
- func (a *Auth) HasOAuthProvider(id string) bool
- func (a *Auth) HasPlugin(id string) bool
- func (a *Auth) ImportTOTP(ctx context.Context, userID, base32Secret string) error
- func (a *Auth) IsUsernameAvailable(ctx context.Context, name string) (bool, error)
- func (a *Auth) IssueJWT(ctx context.Context, h http.Header) (string, error)
- func (a *Auth) JWTSigningAlgorithm() string
- func (a *Auth) ListSessions(ctx context.Context, headers http.Header) ([]Session, error)
- func (a *Auth) ListUserAccounts(ctx context.Context, h http.Header) ([]LinkedAccount, error)
- func (a *Auth) Logger() *slog.Logger
- func (a *Auth) OAuthIssuer() string
- func (a *Auth) PublicJWKS(ctx context.Context) (jose.JSONWebKeySet, error)
- func (a *Auth) PublicJWKSURL() string
- func (a *Auth) PublicURL() string
- func (a *Auth) ReadEmailOTP(ctx context.Context, email string, purpose EmailOTPPurpose) (*string, error)
- func (a *Auth) RefreshToken(ctx context.Context, h http.Header, s AccountSelection) (RefreshTokenResult, error)
- func (a *Auth) RequestEmailChangeOTP(ctx context.Context, h http.Header, newEmail, currentOTP string) error
- func (a *Auth) RequestPasswordReset(ctx context.Context, email, redirectTo string) error
- func (a *Auth) RequestPhonePasswordReset(ctx context.Context, number string) error
- func (a *Auth) ResetPassword(ctx context.Context, token, newPassword string) error
- func (a *Auth) ResetPasswordEmailOTP(ctx context.Context, email, code, password string) error
- func (a *Auth) ResetPhonePassword(ctx context.Context, number, code, password string) error
- func (a *Auth) RevokeOtherSessions(ctx context.Context, h http.Header) error
- func (a *Auth) RevokeSession(ctx context.Context, h http.Header, token string) error
- func (a *Auth) RevokeSessions(ctx context.Context, h http.Header) error
- func (a *Auth) SendEmailOTP(ctx context.Context, email string, purpose EmailOTPPurpose) error
- func (a *Auth) SendPhoneNumberOTP(ctx context.Context, number string) error
- func (a *Auth) SendVerificationEmail(ctx context.Context, h http.Header, email, callback string) error
- func (a *Auth) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *Auth) SessionCookie(token string, persistent bool) *http.Cookie
- func (a *Auth) SetPassword(ctx context.Context, h http.Header, password string) error
- func (a *Auth) SignInEmail(ctx context.Context, in SignInInput, meta RequestMeta) (AuthResult, error)
- func (a *Auth) SignInEmailOTP(ctx context.Context, in EmailOTPSignInInput, meta RequestMeta) (AuthResult, error)
- func (a *Auth) SignInPhoneNumber(ctx context.Context, number, password string, meta RequestMeta) (AuthResult, error)
- func (a *Auth) SignInUsername(ctx context.Context, in UsernameSignInInput, meta RequestMeta) (AuthResult, error)
- func (a *Auth) SignJWT(ctx context.Context, subject string, settings JWTSignOptions) (string, error)
- func (a *Auth) SignOAuthConsentQuery(fields url.Values, expires time.Time, clearedSessionID string) string
- func (a *Auth) SignOAuthQuery(fields url.Values, expires time.Time) string
- func (a *Auth) SignOut(ctx context.Context, headers http.Header) error
- func (a *Auth) SignUpEmail(ctx context.Context, in SignUpInput, meta RequestMeta) (AuthResult, error)
- func (a *Auth) TrustedDeviceCookieName() string
- func (a *Auth) TwoFactorChallengeCookie(challenge LoginChallenge) *http.Cookie
- func (a *Auth) UnlinkAccount(ctx context.Context, h http.Header, recordID string) error
- func (a *Auth) UpdateSession(ctx context.Context, h http.Header, patch map[string]any) (Session, error)
- func (a *Auth) UpdateTrustedUserFields(ctx context.Context, userID string, changes map[string]any) error
- func (a *Auth) UpdateUser(ctx context.Context, h http.Header, update ProfileUpdate) error
- func (a *Auth) ValidateNewPassword(ctx context.Context, path, password string) error
- func (a *Auth) VerifyEmail(ctx context.Context, raw string) error
- func (a *Auth) VerifyEmailOTP(ctx context.Context, email, code string) (User, error)
- func (a *Auth) VerifyJWT(ctx context.Context, token string, settings JWTVerifyOptions) (map[string]any, error)
- func (a *Auth) VerifyOAuthPageQuery(raw string) (url.Values, error)
- func (a *Auth) VerifyOAuthQuery(raw string) (url.Values, error)
- func (a *Auth) VerifyOneTimeToken(ctx context.Context, token string) (*SessionResult, error)
- func (a *Auth) VerifyPassword(ctx context.Context, h http.Header, password string) error
- func (a *Auth) VerifyPhoneNumber(ctx context.Context, h http.Header, in PhoneVerificationInput, ...) (PhoneVerificationResult, error)
- func (a *Auth) VerifySignedSessionToken(signed string) string
- func (a *Auth) ViewBackupCodes(ctx context.Context, userID string) ([]string, error)
- func (a *Auth) WellKnownJSON(path string) (json.RawMessage, bool)
- func (a *Auth) WellKnownPaths() []string
- func (a *Auth) WithTrustedSessionFields(row StoredSession, overrides map[string]any) (StoredSession, error)
- type AuthResult
- type ChangePasswordInput
- type ClientIPOptions
- type CredentialSession
- type CredentialSessionResolver
- type CredentialVerifier
- type CrossSubDomainCookiesOptions
- type DeleteUserInput
- type DeviceAuthorizationOptions
- type DeviceAuthorizationStore
- type DeviceGrant
- type DeviceReview
- type DeviceSessionStore
- type DisplayUsernameFields
- type EmailOTPAction
- type EmailOTPChangeOptions
- type EmailOTPMessage
- type EmailOTPObservation
- type EmailOTPOptions
- type EmailOTPPurpose
- type EmailOTPRecord
- type EmailOTPRegistrationFields
- type EmailOTPRegistrationStore
- type EmailOTPRequest
- type EmailOTPResetHookStore
- type EmailOTPSignInInput
- type EmailOTPSource
- type EmailOTPStore
- type EmailOTPTransform
- type EmailOTPVerificationObserverStore
- type EmailVerificationAttempt
- type EmailVerificationHook
- type EmailVerificationObserverStore
- type EmailVerificationReceipt
- type EmailVerificationSessionStore
- type EmptyResponse
- type Endpoint
- type EndpointContext
- func (c EndpointContext) BeginEnterpriseFlow(provider, reference, redirectURI string, signup bool) (OAuthFlow, error)
- func (c EndpointContext) BeginEnterprisePostFlow(provider, reference, redirectURI string, signup bool) (OAuthFlow, error)
- func (c EndpointContext) CheckOAuthJWTRevocation(token string, resourceKnown func(context.Context, string) (bool, error)) (bool, error)
- func (c EndpointContext) CompleteEnterpriseFlow(f OAuthFlow, p OAuthProfile, tokens OAuthTokens, disableSignup bool, ...) (any, error)
- func (c *EndpointContext) ConsumeEnterpriseFlow() (OAuthFlow, error)
- func (c *EndpointContext) ConsumeEnterprisePostFlow(state string) (OAuthFlow, error)
- func (c EndpointContext) DirectBrowserSession(token string) bool
- func (c EndpointContext) IssueSession(userID string, commit func(context.Context, StoredSession) (User, error)) (*SessionResult, error)
- func (c EndpointContext) IssueSessionWithFields(userID string, fields map[string]any, ...) (*SessionResult, error)
- func (c EndpointContext) OAuthJWTPayload(token string) (claims map[string]any, recognized bool, err error)
- func (c EndpointContext) PopulateUserProfile(user *User) error
- func (c EndpointContext) Redirect(callback string) (any, error)
- func (c EndpointContext) RegisteredOAuthRedirect(target string) any
- func (c EndpointContext) ReissueSessionCookie(session Session)
- func (c EndpointContext) RequestMetadata() *http.Request
- func (c EndpointContext) RequireFreshSession() (*SessionResult, error)
- func (c EndpointContext) ResumeOAuthAuthorization(r *http.Request) (any, error)
- func (c EndpointContext) SAMLIDPLogoutCompleted(target, token string, revoked bool) any
- func (c EndpointContext) SAMLLogoutBrowserToken() string
- func (c EndpointContext) SAMLLogoutCompleted()
- func (c EndpointContext) SAMLLogoutCookie() string
- func (c EndpointContext) SAMLLogoutStarted(token, target, binding string, ttl time.Duration) any
- func (c EndpointContext) SignUpAllowed() bool
- func (c EndpointContext) Store() Store
- func (c EndpointContext) TrustedUserFields() map[string]UserField
- func (c EndpointContext) TryReissueSessionCookie(session Session) error
- type ErrorContext
- type FactorBackupOptions
- type FactorChange
- type FactorDelivery
- type FactorLockoutOptions
- type FactorOTPMessage
- type FactorOTPOptions
- type FactorRecord
- type FactorState
- type FactorSubject
- type FactorTOTPOptions
- type HTMLPage
- type HTTPDescription
- type HTTPField
- type HTTPRoute
- type HTTPSessionField
- type JWTKeyLookup
- type JWTOptions
- type JWTSignOptions
- type JWTStore
- type JWTVerifyOptions
- type LinkedAccount
- type LinkedAccountStore
- type LocalizedError
- type LoginChallenge
- type MagicLinkChallenge
- type MagicLinkMessage
- type MagicLinkOptions
- type MagicLinkStore
- type MagicLinkUserFieldStore
- type MailLink
- type MailSender
- type MappedAccountFields
- type MissingPermissionsError
- type MultiSessionOptions
- type OAuthAccountFieldInput
- type OAuthCompletion
- type OAuthError
- type OAuthFlow
- type OAuthLinkRefreshStore
- type OAuthLoginContinuation
- type OAuthLoginOptions
- type OAuthPopupOptions
- type OAuthProfile
- type OAuthProfileFields
- type OAuthProfileSyncStore
- type OAuthProvider
- type OAuthProxyOptions
- type OAuthRegistrationFields
- type OAuthRegistrationStore
- type OAuthStore
- type OAuthTokens
- type OAuthVerifiedEmailStore
- type OneTapOptions
- type OneTimeTokenOptions
- type OneTimeTokenStore
- type Options
- type PasswordResetToken
- type PhoneAccountAction
- type PhoneAccountResult
- type PhoneAccountStore
- type PhoneLoginBinding
- type PhoneNumberFields
- type PhoneNumberOptions
- type PhoneNumberStore
- type PhoneOTPDecision
- type PhoneOTPMessage
- type PhoneOTPPurpose
- type PhoneOTPRecord
- type PhoneOTPUse
- type PhoneRegistrationStore
- type PhoneSignUpOptions
- type PhoneVerificationInput
- type PhoneVerificationResult
- type Plugin
- func NewAdmin(options AdminOptions) (Plugin, error)
- func NewAnonymous(o AnonymousOptions) (Plugin, error)
- func NewDeviceAuthorization(o DeviceAuthorizationOptions) (Plugin, error)
- func NewEmailOTP(o EmailOTPOptions) (Plugin, error)
- func NewJWT(opts JWTOptions) (Plugin, error)
- func NewMagicLink(options MagicLinkOptions) (Plugin, error)
- func NewMultiSession(options MultiSessionOptions) (Plugin, error)
- func NewOAuthPopup() Plugin
- func NewOAuthPopupWithOptions(options OAuthPopupOptions) (Plugin, error)
- func NewOAuthProxy(o OAuthProxyOptions) (Plugin, error)
- func NewOneTap(o OneTapOptions, fallback OAuthProvider) Plugin
- func NewOneTimeToken(opts OneTimeTokenOptions) (Plugin, error)
- func NewPhoneNumber(o PhoneNumberOptions) (Plugin, error)
- func NewTwoFactor(opts TwoFactorOptions) Plugin
- func NewUsername(options UsernameOptions) (Plugin, error)
- type ProfileUpdate
- type ProviderAccountCredential
- type ProviderCredentialStore
- type ProviderLogoutResult
- type PublicJWTKey
- type RateLimitRule
- type RateLimitStorage
- type RefreshTokenResult
- type RegistrationUserFields
- type RequestContext
- type RequestMeta
- type Session
- func (s Session) AdditionalField(name string) (any, bool)
- func (s Session) AllowsCredentialAction(resource, action string) bool
- func (s Session) IsApplicationCredential() bool
- func (s Session) MarshalJSON() ([]byte, error)
- func (s Session) RequireOwner() error
- func (s *Session) UnmarshalJSON(data []byte) error
- type SessionCacheStore
- type SessionCookieCacheOptions
- type SessionCookieCacheStrategy
- type SessionCookieEvent
- type SessionField
- type SessionFieldStore
- type SessionFieldType
- type SessionRefreshStore
- type SessionResponseFunc
- type SessionResult
- type SignInInput
- type SignUpInput
- type StatusOnlyError
- type Store
- type StoredJWTKey
- type StoredSession
- type TwoFactorOptions
- type TwoFactorStore
- type User
- type UserField
- type UserFieldStore
- type UserFieldValues
- type UsernameFields
- type UsernameOptions
- type UsernameSignInInput
- type UsernameStore
- type VerifiedEmailChange
- type VersionedSecret
- type WellKnownDocument
- type XMLDocument
Constants ¶
const ( FieldString = sessionfields.String FieldNumber = sessionfields.Number FieldBoolean = sessionfields.Boolean FieldDate = sessionfields.Date )
const DeviceGrantType = "urn:ietf:params:oauth:grant-type:device_code"
Variables ¶
var ( ErrTransferSessionExpired = errors.New("one-time token session expired") ErrTransferSessionMissing = errors.New("one-time token session absent") )
var ( ErrNotFound = errors.New("authn: record not found") ErrEmailTaken = errors.New("authn: email already registered") )
var ErrAdminExists = errors.New("an administrative account already exists")
ErrAdminExists indicates that the target database already has an admin role holder.
var ErrIDTokenUsed = errors.New("ID token has already been used")
var ErrInvalidJWT = errors.New("jwt: invalid service token")
var ErrLastAccount = errors.New("auth: cannot unlink last account")
var ErrMagicLinkSignUpDisabled = errors.New("magic link registration disabled")
var ErrNotAnonymous = errors.New("user is not anonymous")
var ErrOAuthAccountAlreadyLinked = errors.New("social identity belongs to another account")
var ErrOAuthEmailUnverified = errors.New("OAuth account requires email verification")
var ErrOAuthLinkRequired = errors.New("account must be linked by its existing owner")
var ErrOAuthLinkingDisabled = errors.New("account linking is disabled")
var ErrOAuthProfileConflict = errors.New("provider profile conflicts with an existing profile")
var ErrOAuthSignupDisabled = errors.New("OAuth account creation disabled")
var ErrPasswordAlreadySet = errors.New("authn: password already set")
var ErrPhoneNumberExists = &APIError{400, "PHONE_NUMBER_EXIST", "Phone number already exists"}
var ErrUsernameImmutable = errors.New("plainauth: username is immutable")
var ErrUsernameTaken = errors.New("plainauth: username already taken")
Functions ¶
func HashPassword ¶
HashPassword uses the built-in salted scrypt credential format. Hosts can delegate to it when adapting an existing password database.
func OAuthPopupAdditionalData ¶
OAuthPopupAdditionalData returns application data from the initiating browser to the provider's exchange and profile callbacks. Values are untrusted input.
Types ¶
type APIError ¶
type APIError struct {
Status int `json:"-"`
Code string `json:"code,omitempty"`
Message string `json:"message"`
}
APIError exposes a public status and error code shared by Go and HTTP callers.
type AccessTokenResult ¶
type AccountField ¶
type AccountField = sessionfields.Field
AccountField declares an attribute of a provider or credential account.
type AccountFieldRule ¶
type AccountFieldRule struct {
ValidateInput func(any) error
TransformInput func(any) (any, error)
}
AccountFieldRule customizes one declared account field. ValidateInput checks mapped provider values. TransformInput runs when a value is saved, including creation defaults. Both receive the normalized scalar and should be pure.
type AccountFieldStore ¶
type AccountFieldStore interface {
WithAccountFields(map[string]AccountField, map[string]AccountFieldRule) (Store, error)
}
AccountFieldStore binds validated account declarations to one auth instance. Its returned store supplies defaults on account creation and lists only public fields.
type AccountInfoResult ¶
type AccountInfoResult struct {
User struct {
Name string `json:"name"`
Email string `json:"email"`
EmailVerified bool `json:"emailVerified"`
Image *string `json:"image,omitempty"`
} `json:"user"`
Account struct {
ID string `json:"id"`
ProviderID string `json:"providerId"`
AccountID string `json:"accountId"`
} `json:"account"`
Data any `json:"data"`
}
type AccountLifecycleStore ¶
type AccountLifecycleStore interface {
SetInitialPassword(ctx context.Context, userID, sessionToken, newHash string, now time.Time) error
SaveDeletionToken(ctx context.Context, t PasswordResetToken) error
DeleteAccount(ctx context.Context, userID, sessionToken, expectedHash, deleteToken string, now time.Time) error
ChangeAccountEmail(ctx context.Context, userID, currentEmail, newEmail string, verified bool, now time.Time) (User, error)
}
AccountLifecycleStore provides owner-bound account writes. Session-based mutations check the current session and user in the same transaction.
type AccountSelection ¶
AccountSelection identifies a local linked-account record. UserID is only used by trusted server calls with nil session headers.
type AccountStore ¶
type AccountStore interface {
UpdateProfile(context.Context, string, ProfileUpdate, time.Time) error
CreateCredentialSession(ctx context.Context, expectedHash string, session StoredSession) error
ChangeCredential(ctx context.Context, userID, oldHash, newHash string, replacement *StoredSession) error
FindAccountUser(ctx context.Context, email string) (User, error)
SavePasswordResetToken(context.Context, PasswordResetToken) error
FindPasswordResetToken(ctx context.Context, token string, now time.Time) (PasswordResetToken, error)
FinishPasswordReset(ctx context.Context, token, newHash string, now time.Time, revokeSessions bool) error
VerifyAccountEmail(ctx context.Context, userID, email string, now time.Time) error
}
AccountStore extends a credential store with atomic profile, credential and verification operations. Its password methods serialize credential changes with creation of sessions for the old password. Expired or spent tokens, changed passwords, and mismatched account bindings return ErrNotFound.
type AdminBootstrapStore ¶
type AdminCreateUserRequest ¶
type AdminCreateUserRequest struct {
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password,omitempty"`
Role []string `json:"role,omitempty"`
Data map[string]any `json:"data,omitempty"`
}
AdminCreateUserRequest contains a trusted or session-authorized administrative request.
type AdminHostCreateStore ¶
type AdminHostCreateStore interface {
AdminCreateTransaction(context.Context, time.Time, func(AdminUserCreator) error) error
}
AdminHostCreateStore runs the explicitly trusted, in-process create operation.
type AdminOptions ¶
type AdminOptions struct {
DefaultRole string
AdminRoles, AdminUserIDs []string
Roles map[string]AdminPermissions
DefaultBanReason, BannedUserMessage string
DefaultBanDuration, ImpersonationSessionDuration time.Duration
AllowImpersonatingAdmins bool
}
func (AdminOptions) HasPermission ¶
func (o AdminOptions) HasPermission(id, role string, want AdminPermissions) bool
HasPermission evaluates one complete grant against each assigned role. Resource/action grants from different roles remain independent.
type AdminPermissions ¶
type AdminQuery ¶
type AdminQuery struct {
Limit, Offset int
SearchField, SearchOperator, SearchValue, FilterField, FilterOperator, SortBy, SortDirection string
FilterValues []string
}
AdminQuery configures a paginated search. Field and operator names are validated by the SQL adapter.
type AdminRequest ¶
type AdminRequest struct {
Operation, UserID, Name, Email, Password, SessionToken, BanReason string
Role []string
BanDuration time.Duration
Data map[string]any
Query AdminQuery
Permissions AdminPermissions
}
AdminRequest invokes an administrative operation using an authenticated caller. Operation is the endpoint name without "/admin/". Data contains approved public profile fields.
type AdminResult ¶
type AdminResult struct {
User *User
Session *SessionResult
Sessions []Session
Page *AdminPage
Allowed bool
// contains filtered or unexported fields
}
type AdminStore ¶
type AdminStore interface {
Store
WithAdminConfig(defaultRole, denialMessage string) (AdminStore, error)
// AdminTransaction locks and validates the authoritative actor session and
// account, serializing target mutations with account deletion and sign-in.
AdminTransaction(ctx context.Context, actorToken, targetID string, now time.Time, fn func(AdminTransaction, SessionResult) error) error
}
type AdminTransaction ¶
type AdminTransaction interface {
User(string) (User, error)
Users(AdminQuery) (AdminPage, error)
CreateUser(User, string) error
UpdateUser(User) error
SetPassword(string, string) error
UserSessions(string) ([]Session, error)
RevokeSession(string) error
RevokeListedSession(userID, sessionID string) error
RevokeUserSessions(string) error
DeleteUser(string) error
Impersonate(StoredSession, Session) error
RestoreSession(current Session, originalToken string, now time.Time) (SessionResult, error)
}
type AdminUserCreator ¶
AdminUserCreator writes a profile and its optional password in one transaction.
type AdminUserFieldTransaction ¶
type AdminUserFieldTransaction interface {
CreateAdminUserWithFields(User, string, UserFieldValues) error
User(string) (User, error)
SelectAdminUserFields(map[string]UserField, func(*User, map[string]any) error) error
}
AdminUserFieldTransaction persists validated columns during creation and projects the public columns from the same row as the ordinary User fields.
type AdminUserFields ¶
type AdminUserFields struct {
Role string `json:"role"`
Banned bool `json:"banned"`
BanReason *string `json:"banReason"`
BanExpires *time.Time `json:"banExpires"`
}
AdminUserFields is present on profiles managed by the administration plugin.
type AnonymousLink ¶
type AnonymousLink struct {
AnonymousUser, NewUser SessionResult
Request *http.Request
Tx *sql.Tx
}
AnonymousLink is delivered when a live guest session becomes a verified permanent session. SQL callbacks can transfer application records with Tx.
type AnonymousOptions ¶
type AnonymousStore ¶
type AnonymousStore interface {
CheckAnonymousSchema(context.Context) error
IsAnonymous(ctx context.Context, userID string) (bool, error)
CreateAnonymous(ctx context.Context, user User, session StoredSession) error
DeleteAnonymous(ctx context.Context, userID, token string, now time.Time) error
LinkAnonymous(ctx context.Context, sourceToken, targetToken string, now time.Time, retain bool, callback func(context.Context, AnonymousLink) error) error
}
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
Auth is safe for concurrent use by application handlers.
func (*Auth) AccountInfo ¶
func (a *Auth) AccountInfo(ctx context.Context, h http.Header, s AccountSelection) (AccountInfoResult, error)
func (*Auth) Admin ¶
func (a *Auth) Admin(ctx context.Context, headers http.Header, req AdminRequest) (AdminResult, error)
Admin runs the same transaction and permission checks as the administrative HTTP endpoints. For impersonation and restoration, use the HTTP handler to receive the browser credentials.
func (*Auth) AdminCreateUser ¶
AdminCreateUser lets trusted application code provision an account, including server-owned fields. Do not expose this method directly as an HTTP handler.
func (*Auth) BindOneTapNonce ¶
func (a *Auth) BindOneTapNonce(w http.ResponseWriter, origin, audience, nonce string) error
BindOneTapNonce records a five-minute browser challenge generated by host server code. Pass a fresh, cryptographically random nonce generated for this browser, the configured Google audience and the trusted page origin. Expose the nonce through the page or a host session, never as user input.
func (*Auth) BootstrapAdmin ¶
BootstrapAdmin provisions the first administrator using the instance's password policy and credential hasher, with the same minimum as authctl.
func (*Auth) CallbackURL ¶
CallbackURL resolves an application callback using this instance's trusted origins.
func (*Auth) ChangeEmail ¶
ChangeEmail requests confirmation for a new address. The token is bound to both the current owner and their current address.
func (*Auth) ChangeEmailOTP ¶
ChangeEmailOTP consumes the new mailbox's proof for the authenticated account.
func (*Auth) ChangePassword ¶
func (a *Auth) ChangePassword(ctx context.Context, h http.Header, in ChangePasswordInput, meta RequestMeta) (AuthResult, error)
ChangePassword optionally revokes all prior sessions and issues a replacement for the caller in the same transaction as the password update.
func (*Auth) CheckEmailOTP ¶
func (a *Auth) CheckEmailOTP(ctx context.Context, email, code string, purpose EmailOTPPurpose) error
CheckEmailOTP preserves a successful proof for a subsequent action.
func (*Auth) CompleteEmailVerificationOTP ¶
func (a *Auth) CompleteEmailVerificationOTP(ctx context.Context, email, code string, meta RequestMeta) (AuthResult, error)
CompleteEmailVerificationOTP optionally issues a session according to the plugin's policy.
func (*Auth) ConsumePhoneNumberOTP ¶
ConsumePhoneNumberOTP spends a verification code without changing the user or creating a session. This method has no HTTP endpoint.
func (*Auth) CreateEmailOTP ¶
func (a *Auth) CreateEmailOTP(ctx context.Context, email string, purpose EmailOTPPurpose) (string, error)
CreateEmailOTP creates a fresh code without sending mail. Only trusted Go application code can call this method, including for an unregistered address.
func (*Auth) DeleteUser ¶
DeleteUser either requests confirmation or deletes the authenticated account. The return value is true when deletion is complete.
func (*Auth) DescribeHTTP ¶
func (a *Auth) DescribeHTTP() HTTPDescription
DescribeHTTP lists the effective routes, including option-dependent core and plugin routes. The server URL is derived from configuration and never trusts an incoming Host header.
func (*Auth) ErrorPageURL ¶
ErrorPageURL is the host-controlled destination for browser protocol errors.
func (*Auth) ExplicitlyTrustedOrigin ¶
ExplicitlyTrustedOrigin permits server-side discovery only at an exact configured origin. Browser wildcard rules do not grant network access.
func (*Auth) GenerateOneTimeToken ¶
GenerateOneTimeToken creates a short-lived transfer credential for the caller's active session.
func (*Auth) GenerateTOTP ¶
GenerateTOTP computes the current code for a raw provisioning secret in trusted application code.
func (*Auth) GetAccessToken ¶
func (a *Auth) GetAccessToken(ctx context.Context, h http.Header, s AccountSelection) (AccessTokenResult, error)
func (*Auth) GetSession ¶
GetSession returns nil for an unauthenticated request.
func (*Auth) HTTPPathDisabled ¶
HTTPPathDisabled reports whether the request selects an HTTP path disabled on this mount. Auth and the bundled SCIM wrapper check this before authentication. Host handlers that extend the same mount can apply the same policy.
func (*Auth) HasOAuthProvider ¶
HasOAuthProvider reports whether an account provider ID belongs to a startup-configured OAuth integration. SQL collations may fold provider IDs.
func (*Auth) ImportTOTP ¶
ImportTOTP enrolls an existing account with an externally provisioned SHA-1 authenticator secret. The caller must authorize the import and obtain the seed through a trusted channel. An existing or pending factor is preserved.
func (*Auth) IsUsernameAvailable ¶
func (*Auth) IssueJWT ¶
IssueJWT creates an audience-bound assertion from an active authenticated session.
func (*Auth) JWTSigningAlgorithm ¶
JWTSigningAlgorithm returns the configured primary algorithm, or an empty string when the JWT plugin is disabled.
func (*Auth) ListSessions ¶
func (*Auth) ListUserAccounts ¶
func (*Auth) OAuthIssuer ¶
OAuthIssuer returns the authorization-server issuer advertised by OAuth discovery. An explicit JWT issuer takes precedence over the public auth URL.
func (*Auth) PublicJWKS ¶
PublicJWKS returns public verification material. Private key data is excluded from the store query used to publish the set.
func (*Auth) PublicJWKSURL ¶
PublicJWKSURL returns the configured key-set endpoint when it is served.
func (*Auth) ReadEmailOTP ¶
func (a *Auth) ReadEmailOTP(ctx context.Context, email string, purpose EmailOTPPurpose) (*string, error)
ReadEmailOTP returns a recoverable stored proof, or nil when absent or expired. This trusted Go operation has no HTTP route. Hashed proofs cannot be recovered.
func (*Auth) RefreshToken ¶
func (a *Auth) RefreshToken(ctx context.Context, h http.Header, s AccountSelection) (RefreshTokenResult, error)
func (*Auth) RequestEmailChangeOTP ¶
func (a *Auth) RequestEmailChangeOTP(ctx context.Context, h http.Header, newEmail, currentOTP string) error
RequestEmailChangeOTP delivers a proof to the new address, bound to the authenticated account.
func (*Auth) RequestPasswordReset ¶
RequestPasswordReset privately delivers a one-time link for a registered email.
func (*Auth) RequestPhonePasswordReset ¶
RequestPhonePasswordReset delivers a separate code only to eligible registered numbers.
func (*Auth) ResetPassword ¶
ResetPassword consumes an unexpired recovery token atomically with the credential update.
func (*Auth) ResetPasswordEmailOTP ¶
ResetPasswordEmailOTP consumes the recovery proof under the configured password policy.
func (*Auth) ResetPhonePassword ¶
ResetPhonePassword changes the bound account's credential atomically with proof consumption.
func (*Auth) RevokeOtherSessions ¶
func (*Auth) RevokeSession ¶
func (*Auth) RevokeSessions ¶
func (*Auth) SendEmailOTP ¶
SendEmailOTP requests delivery to Email under the supplied purpose.
func (*Auth) SendPhoneNumberOTP ¶
SendPhoneNumberOTP stores a fresh verification code and passes the raw value only to SendOTP.
func (*Auth) SendVerificationEmail ¶
func (a *Auth) SendVerificationEmail(ctx context.Context, h http.Header, email, callback string) error
SendVerificationEmail delivers a verification link bound to the email's current owner.
func (*Auth) ServeHTTP ¶
func (a *Auth) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves the auth endpoints beneath the configured base path.
func (*Auth) SessionCookie ¶
SessionCookie returns the HTTP-only cookie for a token obtained through SignUpEmail or SignInEmail. The caller owns the response writer.
func (*Auth) SetPassword ¶
SetPassword is a server-only operation for adding a first credential to an existing account. An existing password requires ChangePassword instead.
func (*Auth) SignInEmail ¶
func (a *Auth) SignInEmail(ctx context.Context, in SignInInput, meta RequestMeta) (AuthResult, error)
SignInEmail verifies credentials and returns a new session or a pending second-factor challenge.
func (*Auth) SignInEmailOTP ¶
func (a *Auth) SignInEmailOTP(ctx context.Context, in EmailOTPSignInInput, meta RequestMeta) (AuthResult, error)
SignInEmailOTP consumes a sign-in code and creates a session.
func (*Auth) SignInPhoneNumber ¶
func (a *Auth) SignInPhoneNumber(ctx context.Context, number, password string, meta RequestMeta) (AuthResult, error)
SignInPhoneNumber authenticates a stored credential and uses the same MFA and ban policy as email sign-in.
func (*Auth) SignInUsername ¶
func (a *Auth) SignInUsername(ctx context.Context, in UsernameSignInInput, meta RequestMeta) (AuthResult, error)
func (*Auth) SignJWT ¶
func (a *Auth) SignJWT(ctx context.Context, subject string, settings JWTSignOptions) (string, error)
SignJWT signs an assertion for a server-chosen subject. Only trusted host code should decide who can obtain an assertion and which claims to include.
func (*Auth) SignOAuthConsentQuery ¶
func (a *Auth) SignOAuthConsentQuery(fields url.Values, expires time.Time, clearedSessionID string) string
SignOAuthConsentQuery signs a consent page after the issuer has verified its post-login step for clearedSessionID. An empty ID omits that attestation.
func (*Auth) SignOAuthQuery ¶
SignOAuthQuery signs the fields for a validated, issuer-controlled interaction. The returned form includes the expiry and the names of all covered fields.
func (*Auth) SignUpEmail ¶
func (a *Auth) SignUpEmail(ctx context.Context, in SignUpInput, meta RequestMeta) (AuthResult, error)
SignUpEmail creates a credential account and its first session atomically.
func (*Auth) TrustedDeviceCookieName ¶
TrustedDeviceCookieName returns the incoming cookie name for this instance. Native callers can pass its opaque value through RequestMeta.TrustedDeviceCookie.
func (*Auth) TwoFactorChallengeCookie ¶
func (a *Auth) TwoFactorChallengeCookie(challenge LoginChallenge) *http.Cookie
TwoFactorChallengeCookie serializes a pending native sign-in result for the browser to carry to the verification endpoint. It cannot authenticate GetSession.
func (*Auth) UnlinkAccount ¶
func (*Auth) UpdateSession ¶
func (a *Auth) UpdateSession(ctx context.Context, h http.Header, patch map[string]any) (Session, error)
UpdateSession changes configured, browser-writable fields of the direct session. Built-in authority fields never participate in this operation.
func (*Auth) UpdateTrustedUserFields ¶
func (a *Auth) UpdateTrustedUserFields(ctx context.Context, userID string, changes map[string]any) error
UpdateTrustedUserFields patches explicitly configured fields, including hidden and server-owned attributes. Call it only after the host authorizes userID.
func (*Auth) UpdateUser ¶
UpdateUser applies the permitted profile fields to the current account.
func (*Auth) ValidateNewPassword ¶
ValidateNewPassword runs configured plugin checks for a credential-setting operation. Custom server endpoints pass their stable path under the auth mount.
func (*Auth) VerifyEmail ¶
VerifyEmail validates a plain address verification link, including its original owner. Existing accounts remain verified when a link is revisited.
func (*Auth) VerifyEmailOTP ¶
VerifyEmailOTP confirms an address without creating a session.
func (*Auth) VerifyJWT ¶
func (a *Auth) VerifyJWT(ctx context.Context, token string, settings JWTVerifyOptions) (map[string]any, error)
VerifyJWT verifies a compact assertion using the configured algorithms and published keys. The caller receives claims only after signature, identity, audience, expiry and activation checks have succeeded.
func (*Auth) VerifyOAuthPageQuery ¶
VerifyOAuthPageQuery extracts verified fields from a host interaction page. Page-local query parameters outside the signed manifest are omitted.
func (*Auth) VerifyOAuthQuery ¶
VerifyOAuthQuery authenticates the exact form submitted to the issuer.
func (*Auth) VerifyOneTimeToken ¶
VerifyOneTimeToken consumes one transfer credential and resolves its original active session.
func (*Auth) VerifyPassword ¶
VerifyPassword reauthenticates a signed-in user with their current password.
func (*Auth) VerifyPhoneNumber ¶
func (a *Auth) VerifyPhoneNumber(ctx context.Context, h http.Header, in PhoneVerificationInput, meta RequestMeta) (PhoneVerificationResult, error)
VerifyPhoneNumber consumes a verification proof and links, creates or signs in the account.
func (*Auth) VerifySignedSessionToken ¶
VerifySignedSessionToken verifies a signed wire credential. Session lookup still checks revocation and expiry in the store.
func (*Auth) ViewBackupCodes ¶
ViewBackupCodes reads the remaining codes for a trusted, server-supplied user ID. Applications must authorize the administrator or owner before calling this method.
func (*Auth) WellKnownJSON ¶
func (a *Auth) WellKnownJSON(path string) (json.RawMessage, bool)
WellKnownJSON returns a private copy of a discovery document at its exact path.
func (*Auth) WellKnownPaths ¶
WellKnownPaths returns the absolute, escaped paths to mount on the public router. Some protocols locate discovery outside the auth handler's base path.
func (*Auth) WithTrustedSessionFields ¶
func (a *Auth) WithTrustedSessionFields(row StoredSession, overrides map[string]any) (StoredSession, error)
WithTrustedSessionFields prepares an unpersisted row using configured defaults and trusted overrides, including ServerOnly fields. It never writes to storage.
type AuthResult ¶
type AuthResult struct {
// TrustedDeviceCookie contains the rotated or expired cookie after a credential login.
TrustedDeviceCookie *http.Cookie `json:"-"`
Challenge *LoginChallenge `json:"-"`
TwoFactorRedirect bool `json:"twoFactorRedirect,omitempty"`
TwoFactorMethods []string `json:"twoFactorMethods,omitempty"`
Token string `json:"token"`
User User `json:"user"`
}
AuthResult contains a newly issued token or a pending second-factor challenge.
type ChangePasswordInput ¶
type ClientIPOptions ¶
type ClientIPOptions struct {
// TrustedProxies contains the CIDR ranges of reverse proxies which
// overwrite or append the actual connection address to ForwardedHeader.
TrustedProxies []netip.Prefix
// ForwardedHeader defaults to X-Forwarded-For. Comma-separated hops are
// processed from the application toward the client.
ForwardedHeader string
// IPv6Subnet is the per-rate-limit prefix length (0–128, default 64).
IPv6Subnet *int
// DisableTracking omits the IP address from sessions and disables IP-based limits.
DisableTracking bool
}
ClientIPOptions controls how the application identifies the connection peer.
type CredentialSession ¶
type CredentialSessionResolver ¶
type CredentialSessionResolver struct {
// SelectRequest is an alternative to Matches and Resolve. Return nil for an
// absent credential. A selected verifier runs only after checking for a
// conflicting browser credential, so probing must not consume quota.
SelectRequest func(*http.Request) (CredentialVerifier, error)
Matches func(http.Header) bool
Resolve func(context.Context, http.Header, RequestMeta, time.Duration) (*CredentialSession, error)
}
CredentialSessionResolver authenticates an application credential for the request. Resolve must validate the credential before returning its principal.
type CredentialVerifier ¶
type CredentialVerifier func(context.Context, RequestMeta, time.Duration) (*CredentialSession, error)
type CrossSubDomainCookiesOptions ¶
type CrossSubDomainCookiesOptions struct {
Domain string
}
CrossSubDomainCookiesOptions selects the host and descendants that receive shared cookies. Use a parent domain to share cookies with sibling hosts.
type DeleteUserInput ¶
type DeleteUserInput struct{ Password, Token, CallbackURL string }
type DeviceAuthorizationOptions ¶
type DeviceAuthorizationOptions struct {
ExpiresIn, Interval time.Duration
DeviceCodeLength, UserCodeLength int
VerificationURI string
GenerateDeviceCode, GenerateUserCode func(context.Context) (string, error)
ValidateClient func(context.Context, string) (bool, error)
OnDeviceAuthRequest func(ctx context.Context, clientID, scope string) error
}
type DeviceAuthorizationStore ¶
type DeviceAuthorizationStore interface {
CheckDeviceSchema(context.Context) error
CreateDeviceGrant(context.Context, DeviceGrant) (created bool, err error)
ReviewDeviceGrant(context.Context, DeviceReview) (grant DeviceGrant, outcome string, err error)
// PollDeviceGrant binds the session to the approving owner and consumes an
// approved grant in the same transaction. Pending polls update lastPolledAt.
PollDeviceGrant(ctx context.Context, code, clientID string, session StoredSession) (scope, outcome string, err error)
}
type DeviceGrant ¶
type DeviceGrant struct {
ID, DeviceCode, UserCode, UserID, ClientID, Scope, Status string
ExpiresAt time.Time
Interval time.Duration
}
DeviceGrant is persisted in the device-authorization schema profile.
type DeviceReview ¶
type DeviceReview struct {
Code, NormalizedCode, UserID, SessionToken, Action string
Now time.Time
}
DeviceReview identifies an optional live browser session and a decision. Action is one of review, approve or deny.
type DeviceSessionStore ¶
type DeviceSessionStore interface {
DeviceSessions(context.Context, []string, time.Time) (map[string]SessionResult, error)
DeleteDeviceSessions(context.Context, []string) error
RevokeDeviceSession(ctx context.Context, activeToken, targetToken string, now time.Time) error
}
DeviceSessionStore operates on sessions proven by signed device cookies. The map keys are exact, case-sensitive tokens. RevokeDeviceSession checks the active session in the same transaction as the deletion and returns ErrNotFound if the active login has expired or was revoked.
type DisplayUsernameFields ¶
type DisplayUsernameFields struct {
DisplayUsername *string `json:"displayUsername"`
}
type EmailOTPAction ¶
type EmailOTPAction struct {
EmailOTPRequest
// CheckOnly preserves a valid proof. Every other successful action consumes it.
CheckOnly, AllowSignUp, RevokeSessions bool
MaxAttempts int
NewUser User
Session StoredSession
PasswordHash string
}
type EmailOTPChangeOptions ¶
EmailOTPChangeOptions controls confirmation at the current and new mailboxes.
type EmailOTPMessage ¶
type EmailOTPMessage struct {
Email, OTP string
Type EmailOTPPurpose
}
EmailOTPMessage carries the raw code exclusively for delivery to Email.
type EmailOTPObservation ¶
type EmailOTPObservation struct {
ID, ExistingToken string
ExpiresAt time.Time
NewSession *StoredSession
}
EmailOTPObservation carries the single-use continuation for a spent code.
type EmailOTPOptions ¶
type EmailOTPOptions struct {
// A custom hash is one-way. A custom cipher supplies both reversible transforms.
Hash, Encrypt, Decrypt EmailOTPTransform
ChangeEmail EmailOTPChangeOptions
AutoSignInAfterVerification bool
Send func(context.Context, EmailOTPMessage) error
GenerateOTP func(context.Context, string, EmailOTPPurpose) (string, error)
Length, AllowedAttempts int
ExpiresIn time.Duration
// StoreOTP accepts plain (default), encrypted, or hashed.
StoreOTP string
// ResendStrategy accepts rotate (default) or reuse.
ResendStrategy string
DisableSignUp bool
SendVerificationOnSignUp bool
OverrideDefaultEmailVerification bool
RateLimit *RateLimitRule
}
EmailOTPOptions configures code generation, delivery, storage and registration policy.
type EmailOTPPurpose ¶
type EmailOTPPurpose string
EmailOTPPurpose binds a delivered proof to one operation.
const ( OTPVerifyEmail EmailOTPPurpose = "email-verification" OTPSignIn EmailOTPPurpose = "sign-in" OTPResetPassword EmailOTPPurpose = "forget-password" OTPChangeEmail EmailOTPPurpose = "change-email" )
type EmailOTPRegistrationFields ¶
type EmailOTPRegistrationFields func() (UserFieldValues, error)
EmailOTPRegistrationFields prepares configured attributes for a new mailbox owner. It has no storage or delivery side effects and can be retried.
type EmailOTPRegistrationStore ¶
type EmailOTPRegistrationStore interface {
UseEmailOTPRegistration(context.Context, EmailOTPAction, func(string) (bool, error), EmailOTPRegistrationFields) (User, error)
}
EmailOTPRegistrationStore consumes a valid proof before applying the new-account field policy. A rejected field set spends the proof without creating a user or session. Existing mailbox owners sign in without evaluating registration data.
type EmailOTPRequest ¶
type EmailOTPRequest struct {
// Observation is present only while completing host-observed verification.
Observation *EmailOTPObservation
// Source binds email changes to the authenticated original account.
Source *EmailOTPSource
CurrentMatches func(string) (bool, error)
MaxAttempts int
Email string
Purpose EmailOTPPurpose
Now time.Time
}
func (EmailOTPRequest) ObservationAttempt ¶
func (req EmailOTPRequest) ObservationAttempt(owner User) EmailVerificationAttempt
func (EmailOTPRequest) ObservationReceipt ¶
func (req EmailOTPRequest) ObservationReceipt(owner User) EmailVerificationReceipt
type EmailOTPResetHookStore ¶
type EmailOTPResetHookStore interface {
UseEmailOTPBeforeVerification(context.Context, EmailOTPAction, func(string) (bool, error)) (User, error)
VerifyAccountEmail(ctx context.Context, userID, email string, now time.Time) error
}
EmailOTPResetHookStore separates a successful credential reset from promotion of the same mailbox. The latter runs only after the host callback succeeds.
type EmailOTPSignInInput ¶
type EmailOTPSource ¶
type EmailOTPSource struct {
UserID, Email, SessionToken string
}
type EmailOTPStore ¶
type EmailOTPStore interface {
ReadEmailOTP(context.Context, EmailOTPRequest) (*EmailOTPRecord, error)
// SaveEmailOTP serializes replacement or reuse for the same purpose and mailbox.
// Returns an empty code when delivery would disclose account existence.
SaveEmailOTP(ctx context.Context, req EmailOTPRequest, allowNew bool, expires time.Time, prepare func(previous *EmailOTPRecord) (raw, stored string, attempts int, err error)) (string, error)
// UseEmailOTP commits the retry count or consumes the proof atomically with the requested mutation.
UseEmailOTP(ctx context.Context, action EmailOTPAction, matches func(stored string) (bool, error)) (User, error)
}
type EmailOTPTransform ¶
EmailOTPTransform is an application-provided hash, encrypt or decrypt operation.
type EmailOTPVerificationObserverStore ¶
type EmailOTPVerificationObserverStore interface {
ConsumeObservedEmailOTP(context.Context, EmailOTPRequest, func(string) (bool, error)) (User, error)
FinishObservedEmailOTP(context.Context, EmailOTPRequest, User) (User, error)
}
EmailOTPVerificationObserverStore consumes an email verification or change proof before calling the host. Finish must reauthorize the exact original account, address and (for changes) direct session when committing the update.
type EmailVerificationAttempt ¶
type EmailVerificationAttempt struct {
ProfileUpdatedAtMillis *int64
OwnerID, Email, ProofID, ExistingToken string
Now, IssuedAt, ExpiresAt time.Time
NewSession *StoredSession
// The explicit OTP sign-in route issues a new session even for its current owner.
AlwaysCreateSession bool
}
EmailVerificationAttempt is a validated ordinary address proof. A nil NewSession requests verification only. ExistingToken, when present, came from a signed browser cookie. ProofID is a digest of the signed proof, never the raw link.
func (EmailVerificationAttempt) MatchesProfileRevision ¶
func (v EmailVerificationAttempt) MatchesProfileRevision(created, updated time.Time) bool
MatchesProfileRevision checks the signed profile revision before issuing a browser session. Older proofs have only a whole-second issue time. Within that second, only an account whose original profile is unchanged qualifies.
func (EmailVerificationAttempt) SessionReceipt ¶
func (v EmailVerificationAttempt) SessionReceipt(owner User) EmailVerificationReceipt
SessionReceipt binds a session handoff to the proved account and exact candidate. A replacement token or a second finish cannot claim the receipt.
type EmailVerificationHook ¶
EmailVerificationHook receives the account before or after the verified mailbox transition. The request is a metadata-only copy for HTTP calls.
type EmailVerificationObserverStore ¶
type EmailVerificationObserverStore interface {
InspectEmailVerification(context.Context, EmailVerificationAttempt) (User, error)
CompleteObservedEmailVerification(context.Context, EmailVerificationAttempt) (VerifiedEmailChange, error)
FinishObservedEmailSession(context.Context, EmailVerificationAttempt, User) (string, error)
DiscardEmailVerificationReceipt(context.Context, EmailVerificationReceipt) error
}
EmailVerificationObserverStore splits the verified mailbox commit from optional session issuance. Finish rechecks the committed user and current session restrictions after the host's callback, before granting a session.
type EmailVerificationReceipt ¶
EmailVerificationReceipt is an expiring, single-use continuation between an accepted proof and its next storage transaction. Value contains a digest.
func (EmailVerificationReceipt) ValidScope ¶
func (r EmailVerificationReceipt) ValidScope() bool
ValidScope limits cleanup operations to this feature's canonical namespace.
type EmailVerificationSessionStore ¶
type EmailVerificationSessionStore interface {
CompleteEmailVerification(context.Context, EmailVerificationAttempt) (string, error)
}
EmailVerificationSessionStore atomically verifies the exact owner and address and spends the proof until expiry. A first eligible browser verification may return a direct existing token for that owner or insert the requested session. Replays, active bans, MFA enrollment and restricted sessions return no token. A missing or reassigned owner/address returns ErrNotFound.
type EmptyResponse ¶
type EmptyResponse struct{}
EmptyResponse sends a successful endpoint response with its declared status and no body.
type Endpoint ¶
type Endpoint struct {
// OpenAPI is optional JSON operation metadata for this endpoint. It is copied at registration.
OpenAPI json.RawMessage
RateLimit *RateLimitRule
// SuccessStatus defaults to 200. A 204 response omits the body.
SuccessStatus int
Method string
Path string
RawBody bool
Handler func(EndpointContext) (any, error)
// contains filtered or unexported fields
}
Endpoint declares the HTTP operation and its optional IP-based limit.
type EndpointContext ¶
type EndpointContext struct {
Auth *Auth
Request *http.Request
Body map[string]any
ResponseHeader http.Header
}
EndpointContext gives a plugin access to the host auth instance, incoming request, decoded JSON fields, and headers for its JSON response. Body is nil for GET and raw-body endpoints.
func (EndpointContext) BeginEnterpriseFlow ¶
func (c EndpointContext) BeginEnterpriseFlow(provider, reference, redirectURI string, signup bool) (OAuthFlow, error)
BeginEnterpriseFlow persists the provider reference and browser return destinations. Only the random browser binding is placed in a cookie.
func (EndpointContext) BeginEnterprisePostFlow ¶
func (c EndpointContext) BeginEnterprisePostFlow(provider, reference, redirectURI string, signup bool) (OAuthFlow, error)
BeginEnterprisePostFlow binds a cross-site form return to an independent Secure, SameSite=None cookie. The ordinary session cookie may be absent on POST.
func (EndpointContext) CheckOAuthJWTRevocation ¶
func (c EndpointContext) CheckOAuthJWTRevocation(token string, resourceKnown func(context.Context, string) (bool, error)) (bool, error)
CheckOAuthJWTRevocation recognizes self-contained tokens during revocation. A recognized inactive token needs no further action. A live access token returns unsupported_token_type. Unknown signatures and issuers fall through to stored-token lookup. This check never authorizes access to a resource.
func (EndpointContext) CompleteEnterpriseFlow ¶
func (c EndpointContext) CompleteEnterpriseFlow(f OAuthFlow, p OAuthProfile, tokens OAuthTokens, disableSignup bool, complete OAuthCompletion) (any, error)
CompleteEnterpriseFlow applies the host's account and token policy and emits the usual session cookies only after the store's transaction has committed.
func (*EndpointContext) ConsumeEnterpriseFlow ¶
func (c *EndpointContext) ConsumeEnterpriseFlow() (OAuthFlow, error)
ConsumeEnterpriseFlow accepts only a single use of the browser-bound state at the auth host and callback path originally selected during sign-in.
func (*EndpointContext) ConsumeEnterprisePostFlow ¶
func (c *EndpointContext) ConsumeEnterprisePostFlow(state string) (OAuthFlow, error)
ConsumeEnterprisePostFlow consumes the RelayState received in the form body.
func (EndpointContext) DirectBrowserSession ¶
func (c EndpointContext) DirectBrowserSession(token string) bool
DirectBrowserSession reports whether the current browser supplied the signed cookie for this session. Provider logout cannot be initiated with a bearer credential.
func (EndpointContext) IssueSession ¶
func (c EndpointContext) IssueSession(userID string, commit func(context.Context, StoredSession) (User, error)) (*SessionResult, error)
IssueSession lets an authentication plugin persist its verified proof and the resulting session in one transaction. The callback must verify the current proof owner and commit the provided session before returning its user.
func (EndpointContext) IssueSessionWithFields ¶
func (c EndpointContext) IssueSessionWithFields(userID string, fields map[string]any, commit func(context.Context, StoredSession) (User, error)) (*SessionResult, error)
IssueSessionWithFields applies trusted overrides before evaluating defaults, then publishes the session only after commit persists it.
func (EndpointContext) OAuthJWTPayload ¶
func (c EndpointContext) OAuthJWTPayload(token string) (claims map[string]any, recognized bool, err error)
OAuthJWTPayload checks a compact token against this server's configured signing keys, OAuth issuer and time claims. A recognized token with nil claims is inactive. An unrecognized value can still identify a stored opaque token. Callers must check the authorized party, audiences and session before using any claims to authorize a request.
func (EndpointContext) PopulateUserProfile ¶
func (c EndpointContext) PopulateUserProfile(user *User) error
PopulateUserProfile loads the user's public fields from enabled plugins and the host's profile schema for a plugin that has authenticated this account.
func (EndpointContext) Redirect ¶
func (c EndpointContext) Redirect(callback string) (any, error)
Redirect returns a 302 endpoint result for a callback allowed by this Auth instance.
func (EndpointContext) RegisteredOAuthRedirect ¶
func (c EndpointContext) RegisteredOAuthRedirect(target string) any
RegisteredOAuthRedirect delivers the result of an authorization request to a URI the issuer has already validated against the client's registration, or to an issuer-controlled page. Fetch clients consume the URL as JSON.
func (EndpointContext) ReissueSessionCookie ¶
func (c EndpointContext) ReissueSessionCookie(session Session)
ReissueSessionCookie emits the current session cookie and its normal response hooks after a plugin changes that session's active context. It preserves the browser's persistence choice and leaves the stored session lifetime intact.
func (EndpointContext) RequestMetadata ¶
func (c EndpointContext) RequestMetadata() *http.Request
RequestMetadata returns a detached copy of the HTTP request headers and URL for a host callback. The body and parsed form data are excluded.
func (EndpointContext) RequireFreshSession ¶
func (c EndpointContext) RequireFreshSession() (*SessionResult, error)
RequireFreshSession checks the authoritative session and the configured age for a sensitive operation such as enrolling an additional credential.
func (EndpointContext) ResumeOAuthAuthorization ¶
func (c EndpointContext) ResumeOAuthAuthorization(r *http.Request) (any, error)
ResumeOAuthAuthorization re-enters the mounted GET authorization endpoint. Route hooks, disabled paths and rate limits run on the resumed request.
func (EndpointContext) SAMLIDPLogoutCompleted ¶
func (c EndpointContext) SAMLIDPLogoutCompleted(target, token string, revoked bool) any
SAMLIDPLogoutCompleted returns the signed response to the registered IdP.
func (EndpointContext) SAMLLogoutBrowserToken ¶
func (c EndpointContext) SAMLLogoutBrowserToken() string
SAMLLogoutBrowserToken identifies the one signed local browser cookie so an IdP logout can clear it only when its underlying session was revoked.
func (EndpointContext) SAMLLogoutCompleted ¶
func (c EndpointContext) SAMLLogoutCompleted()
SAMLLogoutCompleted expires the logout binding. A new login that happened while the identity provider processed the request keeps its own session.
func (EndpointContext) SAMLLogoutCookie ¶
func (c EndpointContext) SAMLLogoutCookie() string
SAMLLogoutCookie returns the independent browser proof for a logout round trip.
func (EndpointContext) SAMLLogoutStarted ¶
func (c EndpointContext) SAMLLogoutStarted(token, target, binding string, ttl time.Duration) any
SAMLLogoutStarted clears the just-revoked session's browser credentials and redirects to the already validated identity provider's signed protocol URL.
func (EndpointContext) SignUpAllowed ¶
func (c EndpointContext) SignUpAllowed() bool
SignUpAllowed reports whether a plugin may create a new account.
func (EndpointContext) Store ¶
func (c EndpointContext) Store() Store
Store returns the current instance's configured identity store.
func (EndpointContext) TrustedUserFields ¶
func (c EndpointContext) TrustedUserFields() map[string]UserField
TrustedUserFields returns the installed profile schema for in-process readers. It includes configured private attributes and the active plugins' stored columns.
func (EndpointContext) TryReissueSessionCookie ¶
func (c EndpointContext) TryReissueSessionCookie(session Session) error
TryReissueSessionCookie reissues the cookie and reports host configuration errors to plugins that need to fail the response when publication fails.
type ErrorContext ¶
ErrorContext contains the request and the user authenticated for this request, when available. Reporting an error never triggers authentication.
type FactorBackupOptions ¶
type FactorChange ¶
type FactorChange struct {
SaveDelivery *FactorDelivery
RemoveDelivery bool
CreateTrustedGrant string
TrustedUntil time.Time
SaveRecord *FactorRecord
DeleteRecord bool
Enabled *bool
CreateChallenge string
ChallengeExpires time.Time
IncrementAttempts, ConsumeChallenge bool
UsedTOTPStep *int64
UsedTOTPPeriod time.Duration
RevokeSessions bool
Session *StoredSession
}
FactorChange is committed under the same owner lock used to load FactorState. SaveRecord and DeleteRecord are mutually exclusive. Sessions are persisted only after the corresponding authentication decision succeeds.
type FactorDelivery ¶
type FactorDelivery struct {
ID string
Pending bool
Stored string
Attempts int
CreatedAt, ExpiresAt time.Time
}
FactorDelivery is a single-use out-of-band code scoped to an existing login challenge or session.
type FactorLockoutOptions ¶
type FactorOTPMessage ¶
type FactorOTPOptions ¶
type FactorOTPOptions struct {
Send func(context.Context, FactorOTPMessage) error
Period time.Duration
Digits, AllowedAttempts int
Store string
Hash, Encrypt, Decrypt EmailOTPTransform
}
type FactorRecord ¶
type FactorState ¶
type FactorSubject ¶
type FactorSubject struct {
ApplicationKeyID, ApplicationOperation string
ReadDelivery bool
TrustedGrant string
UserID, SessionToken, Challenge string
Now time.Time
}
FactorSubject identifies an existing signed-in session, a login after a password check, or a short-lived first-factor challenge.
type FactorTOTPOptions ¶
type FactorTOTPOptions struct {
Digits int
Period time.Duration
Disabled bool
AllowPasswordless *bool
}
FactorTOTPOptions configures authenticator apps. Digits accepts 6 or 8. Period must be a whole number of seconds.
type HTMLPage ¶
type HTMLPage string
HTMLPage is trusted HTML returned by an endpoint. Escape all dynamic text before constructing it.
type HTTPDescription ¶
type HTTPDescription struct {
SessionFields map[string]HTTPSessionField
UserFields map[string]HTTPField
OrganizationRoleFields map[string]HTTPField
RoleFieldsRequiredOnCreate bool
// RequiredUserInputs lists writable fields that have no registration default.
RequiredUserInputs []string
EmailOTPRegistration, PhoneRegistration bool
// OAuthLoginContinuation indicates that a host can resume a signed issuer login.
OAuthLoginContinuation bool
// OAuthSelectionContinuation indicates that organization and team selection can resume a signed post-login request.
OAuthSelectionContinuation bool
ServerURL, SessionCookie string
// OAuthProxyStateCookie binds a preview return to the initiating browser.
OAuthProxyStateCookie string
// SSOStateCookie is the browser binding cookie for installed enterprise OIDC callbacks.
SSOStateCookie string
// SAMLStateCookie is set when the SP-initiated SAML form handler is installed.
SAMLStateCookie string
SAMLLogoutCookie string
Routes []HTTPRoute
Providers []string
MinPassword, MaxPassword int
DisplayUsername bool
CustomSession bool
}
HTTPDescription describes public settings used to document the handler.
type HTTPField ¶
type HTTPField struct {
Type SessionFieldType
Required, Writable, Returned bool
}
HTTPField describes the public input and output permissions of a configured scalar.
type HTTPRoute ¶
type HTTPRoute struct {
Method, Path, Plugin string
RawBody bool
// SuccessStatus is the endpoint's declared success status. Zero defaults to 200.
SuccessStatus int
OpenAPI json.RawMessage
}
HTTPRoute describes one registered, enabled HTTP operation. OpenAPI is a private copy for the caller.
type HTTPSessionField ¶
type HTTPSessionField = HTTPField
HTTPSessionField describes a configured session field.
type JWTKeyLookup ¶
type JWTKeyLookup interface {
JWTKeyByID(context.Context, string) (StoredJWTKey, error)
}
type JWTOptions ¶
type JWTSignOptions ¶
type JWTSignOptions struct {
Claims map[string]any
Algorithm, KeyID string
Type, ContentType string
Issuer string
Audience []string
IssuedAt, ExpiresAt, NotBefore time.Time
}
JWTSignOptions applies to a single trusted server-side issuance. Reserved claims come from the typed fields. Algorithm and KeyID may select a provisioned key.
type JWTStore ¶
type JWTStore interface {
ActiveJWTKey(ctx context.Context, algorithm string, now time.Time, generate func() (StoredJWTKey, error)) (StoredJWTKey, error)
PublicJWTKeys(ctx context.Context, cutoff time.Time) ([]PublicJWTKey, error)
}
type JWTVerifyOptions ¶
type JWTVerifyOptions struct {
Issuer, Audience, Subject string
}
JWTVerifyOptions allows a service to require its own issuer, audience and subject.
type LinkedAccount ¶
type LinkedAccount struct {
AdditionalFields map[string]any `json:"-"`
ID string `json:"id"`
AccountID string `json:"accountId"`
ProviderID string `json:"providerId"`
UserID string `json:"userId"`
Scopes []string `json:"scopes"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
LinkedAccount contains fields safe to return to the signed-in account owner.
func (LinkedAccount) MarshalJSON ¶
func (a LinkedAccount) MarshalJSON() ([]byte, error)
func (*LinkedAccount) UnmarshalJSON ¶
func (a *LinkedAccount) UnmarshalJSON(data []byte) error
type LinkedAccountStore ¶
type LocalizedError ¶
LocalizedError exposes the translated APIError and its original server message.
func (*LocalizedError) Unwrap ¶
func (e *LocalizedError) Unwrap() error
type LoginChallenge ¶
type LoginChallenge struct{ Identifier string }
type MagicLinkChallenge ¶
MagicLinkChallenge describes a mailbox proof under a purpose-specific key. Key is the stored token representation, without its database namespace.
type MagicLinkMessage ¶
type MagicLinkMessage struct {
Email, URL, Token string
Metadata map[string]any
// Request contains independent HTTP request metadata for the delivery callback.
// It is excluded when serializing the message for an email queue.
Request *http.Request `json:"-"`
}
MagicLinkMessage contains private authentication material for delivery to Email.
type MagicLinkOptions ¶
type MagicLinkOptions struct {
Send func(context.Context, MagicLinkMessage) error
ExpiresIn time.Duration
DisableSignUp bool
HashTokens bool
HashToken func(context.Context, string) (string, error)
GenerateToken func(ctx context.Context, email string) (string, error)
RateLimit *RateLimitRule
}
MagicLinkOptions configures delivery, token storage and registration.
type MagicLinkStore ¶
type MagicLinkStore interface {
SaveMagicLink(context.Context, MagicLinkChallenge) error
CompleteMagicLink(ctx context.Context, key, newUserID string, session StoredSession, allowSignUp bool) (User, bool, error)
}
MagicLinkStore consumes a mailbox proof atomically with user promotion and session creation.
type MagicLinkUserFieldStore ¶
type MagicLinkUserFieldStore interface {
CompleteMagicLinkWithUserFields(ctx context.Context, key, newUserID string, session StoredSession, defaults RegistrationUserFields) (User, bool, error)
}
MagicLinkUserFieldStore writes registration defaults in the transaction that proves mailbox ownership and creates the first session. Existing users keep their stored values, including when a required field has no default.
type MailLink ¶
MailLink is delivered to the application's configured mail sender. Its Token and URL are sensitive and should only be delivered to User.Email.
type MappedAccountFields ¶
type MappedAccountFields struct {
// contains filtered or unexported fields
}
MappedAccountFields carries the declared provider values for an account write.
type MissingPermissionsError ¶
type MissingPermissionsError struct {
*APIError
MissingPermissions []string `json:"missingPermissions"`
OriginalMessage string `json:"originalMessage,omitempty"`
}
MissingPermissionsError identifies individual grants that an actor may not delegate.
func (*MissingPermissionsError) Unwrap ¶
func (e *MissingPermissionsError) Unwrap() error
type MultiSessionOptions ¶
type MultiSessionOptions struct {
// MaximumSessions defaults to five. An explicit zero disables remembering new accounts.
MaximumSessions *int
}
type OAuthAccountFieldInput ¶
type OAuthAccountFieldInput struct {
// ExchangedToken exposes TokenType and provider-specific Extra values for code exchanges.
ExchangedToken *oauth2.Token
Profile OAuthProfile
Tokens OAuthTokens
ClientAccessToken, ClientRefreshToken string
}
OAuthAccountFieldInput distinguishes credentials verified by the provider flow from optional, unverified strings submitted by a native client.
type OAuthCompletion ¶
type OAuthCompletion func(context.Context, string, string, OAuthTokens, User, StoredSession, OAuthLoginOptions) (User, bool, error)
OAuthCompletion persists the verified identity, account credentials and session in one transaction after checking any plugin-owned identity binding.
type OAuthError ¶
type OAuthError struct {
Status int `json:"-"`
Code string `json:"error,omitempty"`
Description string `json:"error_description"`
}
OAuthError represents the public error fields of an OAuth protocol response.
func (*OAuthError) Error ¶
func (e *OAuthError) Error() string
type OAuthFlow ¶
type OAuthFlow struct {
// IssuerLoginQuery is the host's verified login request, retained only in
// the local flow store while the browser visits the identity provider.
IssuerLoginQuery string `json:",omitempty"`
// ProxyOrigin is the preview that owns the browser state and final session.
ProxyOrigin string `json:",omitempty"`
PopupAdditionalData map[string]any `json:",omitempty"`
ProviderReference string `json:",omitempty"`
RedirectURI string `json:",omitempty"`
RequestSignUp bool `json:",omitempty"`
AnonymousSessionProof string `json:",omitempty"`
State, Binding, Provider, Verifier, Nonce string
CallbackURL, ErrorCallbackURL, NewUserCallbackURL string
LinkUserID string
ExpiresAt time.Time
}
OAuthFlow is the temporary state of a browser authorization. Binding ties a request to the initiating browser, provider and existing session.
type OAuthLinkRefreshStore ¶
type OAuthLinkRefreshStore interface {
RefreshOwnedOAuthLink(context.Context, string, string, OAuthTokens, User, StoredSession, OAuthLoginOptions) (User, bool, error)
}
OAuthLinkRefreshStore updates an already-owned provider identity after verifying the live owner session and the provider subject in the same transaction. Implement it to permit redundant mobile link requests when linking is disabled.
type OAuthLoginContinuation ¶
OAuthLoginContinuation builds the issuer authorization request after a login endpoint actually issues a new browser session. The host installs its signed cookie and dispatches the request through the normal authorization route.
type OAuthLoginOptions ¶
type OAuthLoginOptions struct {
// AccountFields holds validated provider values keyed by logical account field name.
AccountFields *MappedAccountFields
DisableSignUp bool
// RequireEmailVerification commits an unverified identity without issuing a session.
RequireEmailVerification bool
// DisableAccountUpdateOnSignIn skips the existing account row update during
// login. Adapters still claim single-use grants and apply the session policy.
DisableAccountUpdateOnSignIn bool
// DisableImplicitLinking also takes precedence over directory-based trust in custom stores.
DisableImplicitLinking bool
OneTapNonce string
OneTapExpires time.Time
AllowVerifiedEmailLink bool
LinkUserID, LinkSessionToken string
IDTokenValidUntil time.Time
// IDTokenHash binds single-use grants independently of randomized storage encryption.
IDTokenHash [32]byte
}
OAuthLoginOptions binds an explicit link to a live session or a direct ID-token grant to the verified token's expiry.
type OAuthPopupOptions ¶
type OAuthPopupOptions struct {
// MessageType defaults to plainauth:oauth-popup. A custom value is namespace:event.
MessageType string
}
OAuthPopupOptions configures the fixed browser message protocol for a deployment.
type OAuthProfile ¶
type OAuthProfile struct {
// AdditionalFields is an explicit mapping from the authenticated provider
// profile to writable user attributes at registration and optional sign-in updates.
AdditionalFields map[string]any `json:"-"`
// Data is the authenticated provider profile returned by the account-info endpoint.
Data any `json:"-"`
Subject, Email, Name string
Image *string
EmailVerified bool
}
OAuthProfile identifies a person by their stable provider subject.
type OAuthProfileFields ¶
type OAuthProfileFields struct {
Create OAuthRegistrationFields
Update func() (UserFieldValues, error)
}
OAuthProfileFields supplies the creation defaults or the mapped update for the selected owner. Call only the matching resolver inside the transaction.
type OAuthProfileSyncStore ¶
type OAuthProfileSyncStore interface {
CompleteOAuthProfile(ctx context.Context, provider, subject string, tokens OAuthTokens, candidate User, session StoredSession, options OAuthLoginOptions, fields OAuthProfileFields) (User, bool, error)
}
OAuthProfileSyncStore applies an authenticated provider profile to the owner selected by the ordinary sign-in and linking rules. Profile, credentials, token consumption and session creation must commit together.
type OAuthProvider ¶
type OAuthProvider struct {
// GetAccountFields maps a verified social grant to declared writable account attributes.
GetAccountFields func(context.Context, OAuthAccountFieldInput) (map[string]any, error)
Config oauth2.Config
// EndSessionEndpoint is the provider's registered OIDC logout endpoint.
EndSessionEndpoint string
// PostLogoutRedirectURI is the default application return URI after provider logout.
PostLogoutRedirectURI string
DisableProviderLogout bool
// CustomizeAuthorization adapts fixed provider-specific parameter names.
CustomizeAuthorization func(*url.URL)
// ExchangeCode handles providers with a nonstandard token endpoint protocol.
ExchangeCode func(context.Context, oauth2.Config, string, string, url.Values) (*oauth2.Token, error)
Resolve func(context.Context, *oauth2.Token, string) (OAuthProfile, error)
VerifyIDToken func(ctx context.Context, raw, nonce string) (OAuthProfile, time.Time, error)
// DisableIDTokenSignIn closes the direct token grant on social sign-in and
// linking. Browser code exchanges and the One Tap plugin verify independently.
DisableIDTokenSignIn bool
// Refresh overrides the standard OAuth 2.0 refresh request.
Refresh func(context.Context, oauth2.Config, string) (*oauth2.Token, error)
DisableRefresh bool
HTTPClient *http.Client
AllowVerifiedEmailLink bool
// DisableSignUp prevents this provider from creating new accounts.
DisableSignUp bool
// DisableImplicitSignUp requires requestSignUp for new browser and direct ID-token accounts.
DisableImplicitSignUp bool
// OverrideUserInfoOnSignIn updates the local profile from this provider on
// successful sign-in. Explicit account linking preserves the owner's profile.
OverrideUserInfoOnSignIn bool
// RequireEmailVerification withholds a session until the local mailbox is verified.
RequireEmailVerification bool
// GoogleHostedDomain restricts the verified Google Workspace hd claim. Use * for any Workspace.
GoogleHostedDomain string
AuthorizationParams url.Values
DisablePKCE bool
OmitNonce bool
FormPostName bool
}
OAuthProvider configures an authorization-code provider. Resolve must obtain identity from an authenticated provider endpoint or a verified ID token. For OpenID Connect it must verify the supplied nonce.
type OAuthProxyOptions ¶
type OAuthProxyOptions struct {
ProductionURL, CurrentURL string
MaxAge time.Duration
Secret string
Secrets []VersionedSecret
// contains filtered or unexported fields
}
OAuthProxyOptions configures an OAuth callback shared by production and previews. ProductionURL is the origin registered with the identity provider. CurrentURL overrides current-origin discovery. MaxAge controls the lifetime of a returned profile. All participating hosts must have the same dedicated secret or key ring.
type OAuthRegistrationFields ¶
type OAuthRegistrationFields func() (UserFieldValues, error)
OAuthRegistrationFields resolves configured columns for a new account.
type OAuthRegistrationStore ¶
type OAuthRegistrationStore interface {
CompleteOAuthRegistration(ctx context.Context, provider, subject string, tokens OAuthTokens, candidate User, session StoredSession, options OAuthLoginOptions, fields OAuthRegistrationFields) (User, bool, error)
}
OAuthRegistrationStore resolves fields only for new users after selecting the exact identity. It commits them with the user, account link and initial session.
type OAuthStore ¶
type OAuthStore interface {
SaveOAuthFlow(context.Context, OAuthFlow, time.Time) error
ConsumeOAuthFlow(ctx context.Context, state, binding string, now time.Time) (OAuthFlow, error)
CompleteOAuth(ctx context.Context, provider, subject string, tokens OAuthTokens, candidate User, session StoredSession, options OAuthLoginOptions) (User, bool, error)
}
OAuthStore supports shared, single-use flow state and atomic identity login. CompleteOAuth returns the actual account owner and whether it created a user.
type OAuthTokens ¶
type OAuthTokens struct {
AccessToken, RefreshToken, IDToken, Scope string
ExpiresAt, RefreshExpiresAt time.Time
}
OAuthTokens are the provider-issued account credentials kept by the adapter.
type OAuthVerifiedEmailStore ¶
type OAuthVerifiedEmailStore interface {
CompleteOAuthVerifiedEmail(ctx context.Context, provider, subject string, tokens OAuthTokens, candidate User, session StoredSession, options OAuthLoginOptions, fields OAuthProfileFields) (User, bool, error)
}
OAuthVerifiedEmailStore checks the locked owner's email before inserting a session. For an unverified owner it commits the user, provider credential and single-use proof, then returns the owner, creation flag and ErrOAuthEmailUnverified. A nil fields.Update preserves the existing profile on returning sign-ins.
type OneTapOptions ¶
OneTapOptions configures Google's first-party browser credential prompt.
type OneTimeTokenOptions ¶
type OneTimeTokenOptions struct {
ExpiresIn time.Duration
// ExpireImmediately explicitly selects a zero lifetime. An unset ExpiresIn uses three minutes.
ExpireImmediately bool
DisableClientRequest, DisableSetSessionCookie, SetHeaderOnNewSession bool
HashTokens bool
HashToken func(context.Context, string) (string, error)
GenerateToken func(context.Context, SessionResult) (string, error)
// GenerateTokenWithRequest receives request metadata for HTTP issuance and nil for native calls.
GenerateTokenWithRequest func(context.Context, SessionResult, *http.Request) (string, error)
}
type OneTimeTokenStore ¶
type Options ¶
type Options struct {
UserAdditionalFields map[string]UserField
SessionAdditionalFields map[string]SessionField
AccountAdditionalFields map[string]AccountField
AccountFieldRules map[string]AccountFieldRule
// Logger receives diagnostics for this instance. A nil logger uses slog.Default().
Logger *slog.Logger
// OnAPIError observes an HTTP endpoint error before its response is written.
// It runs synchronously and may use the request's context for cancellation.
OnAPIError func(ErrorContext, error) error
// SessionCookieCache enables authenticated snapshots for public browser session reads.
SessionCookieCache *SessionCookieCacheOptions
// Store persists identities and sessions. Configure one store per auth instance.
Store Store
// BaseURL is the public HTTP(S) address. BasePath defaults to /api/auth.
BaseURL string
BasePath string
// DisabledPaths hides exact HTTP paths relative to this instance’s mount.
DisabledPaths []string
// TrustedOrigins allows exact HTTP(S) origins and hostname or port wildcard patterns for browser requests and callbacks.
TrustedOrigins []string
CookiePrefix string
// CrossSubDomainCookies selects the Domain attribute for shared browser cookies.
// A nil value keeps cookies host-only. An empty Domain uses the BaseURL hostname.
CrossSubDomainCookies *CrossSubDomainCookiesOptions
// UseSecureCookies overrides the HTTPS-based default for session cookies.
UseSecureCookies *bool
ErrorRedirectURL string
// Secret signs credentials. Secrets configures ordered keys for rotation.
Secret string
Secrets []VersionedSecret
// PasswordHash derives a stored credential from a plaintext password.
// PasswordVerify checks a stored credential against a plaintext password.
// A nil callback uses the built-in scrypt implementation for that operation.
PasswordHash func(ctx context.Context, password string) (string, error)
PasswordVerify func(ctx context.Context, encoded, password string) (bool, error)
// OnExistingUserSignUp receives the persisted mailbox owner on a protected duplicate
// sign-up. An HTTP call supplies request metadata; direct calls supply nil.
OnExistingUserSignUp func(context.Context, User, *http.Request) error
EmailAndPassword bool
MinPasswordLength int
MaxPasswordLength int
DisableSignUp bool
DisableAutoSignIn bool
RequireEmailVerification bool
// AutoSignInAfterVerification issues or reuses a browser session on first email-link verification.
AutoSignInAfterVerification bool
SendVerificationOnSignUp *bool
SendVerificationOnSignIn bool
SendVerificationEmail MailSender
EmailVerificationTokenTTL time.Duration
SendResetPassword MailSender
PasswordResetTokenTTL time.Duration
RevokeSessionsOnPasswordReset bool
// BeforeEmailVerification and AfterEmailVerification run outside store locks.
BeforeEmailVerification, AfterEmailVerification EmailVerificationHook
// OnPasswordReset runs after a recovery proof is consumed, the password is
// replaced, and any requested session revocation commits. Mounted endpoints
// pass the HTTP request. Direct Go calls pass nil.
OnPasswordReset func(context.Context, User, *http.Request) error
// Account lifecycle operations with destructive or identity-changing effects are opt-in.
DeleteUserEnabled bool
SendDeleteAccountVerification MailSender
DeleteTokenTTL time.Duration
ChangeEmailEnabled bool
UpdateEmailWithoutVerification bool
SendChangeEmailConfirmation MailSender
// DisableAccountLinking prevents attaching another provider to an existing account.
DisableAccountLinking bool
// DisableImplicitAccountLinking requires an authenticated owner to link an additional provider.
DisableImplicitAccountLinking bool
// DisableAccountUpdateOnSignIn preserves credentials on existing provider
// accounts during sign-in. New links and explicit reauthorization still store grants.
DisableAccountUpdateOnSignIn bool
AllowUnlinkingAll bool
SessionTTL time.Duration
FreshAge time.Duration
// SessionUpdateAge controls sliding expiration. A pointer to zero refreshes on every eligible read.
SessionUpdateAge *time.Duration
DisableSessionRefresh bool
DeferSessionRefresh bool
// RateLimit overrides the environment's enablement policy. By default
// counters live on the auth instance. Supply RateLimitStorage to share them.
RateLimit *bool
RateLimitStorage RateLimitStorage
// RateLimitDefault applies to routes without their own rule. RateLimitRules
// overrides built-in and plugin rules by exact route or trailing /* prefix.
// A nil map value exempts the matching route from the limiter.
RateLimitDefault *RateLimitRule
RateLimitRules map[string]*RateLimitRule
ClientIP ClientIPOptions
SocialProviders map[string]OAuthProvider
// EncryptOAuthTokens encrypts linked provider credentials at rest using the configured key ring.
EncryptOAuthTokens bool
Plugins []Plugin
}
Options configures one isolated authentication instance.
type PasswordResetToken ¶
PasswordResetToken records a reset link and its owner in verification storage.
type PhoneAccountAction ¶
type PhoneAccountAction struct {
Use PhoneOTPUse
SourceID, SourceToken string
// Create is optional and is used only if no account exists for this number.
Create *User
Session *StoredSession
PasswordHash string
RevokeSessions, RequireVerification bool
}
type PhoneAccountResult ¶
type PhoneAccountStore ¶
type PhoneAccountStore interface {
PhoneNumberStore
ReadPhoneOTP(ctx context.Context, number string, purpose PhoneOTPPurpose) (*PhoneOTPRecord, error)
ReadPhoneNumber(ctx context.Context, userID string) (*PhoneNumberFields, error)
PhoneCredential(ctx context.Context, number string) (User, string, error)
SavePhoneReset(ctx context.Context, r PhoneOTPRecord, requireVerified bool) (bool, error)
// A successful password reset returns the account selected by the consumed proof.
ApplyPhoneOTP(context.Context, PhoneAccountAction) (PhoneAccountResult, error)
ClearPhoneProfile(ctx context.Context, userID, token string, p ProfileUpdate, now time.Time) error
}
type PhoneLoginBinding ¶
PhoneLoginBinding identifies the number a password or pending factor login proved.
func PhoneLoginFrom ¶
func PhoneLoginFrom(ctx context.Context) (PhoneLoginBinding, bool)
PhoneLoginFrom is used by stores to recheck a phone login under the session owner's lock.
func (PhoneLoginBinding) Matches ¶
func (b PhoneLoginBinding) Matches(f *PhoneNumberFields) bool
type PhoneNumberFields ¶
type PhoneNumberFields struct {
PhoneNumber *string `json:"phoneNumber"`
PhoneNumberVerified *bool `json:"phoneNumberVerified"`
}
PhoneNumberFields is present when the phone plugin is enabled. A user may have no number.
type PhoneNumberOptions ¶
type PhoneNumberOptions struct {
SendPasswordResetOTP func(context.Context, PhoneOTPMessage) error
VerifyOTP func(context.Context, PhoneOTPMessage) (bool, error)
OnVerification func(context.Context, string, User) error
SignUpOnVerification *PhoneSignUpOptions
RequireVerification bool
SendOTP func(context.Context, PhoneOTPMessage) error
Validate func(context.Context, string) (bool, error)
OTPLength int
// AllowedAttempts defaults to three. An explicit zero rejects every proof.
AllowedAttempts *int
ExpiresIn time.Duration
}
type PhoneNumberStore ¶
type PhoneOTPDecision ¶
type PhoneOTPDecision uint8
const ( PhoneKeepProof PhoneOTPDecision = iota PhoneCountAttempt PhoneRemoveProof )
type PhoneOTPMessage ¶
type PhoneOTPMessage struct {
PhoneNumber, Code string
Purpose PhoneOTPPurpose
}
type PhoneOTPPurpose ¶
type PhoneOTPPurpose string
PhoneOTPPurpose keeps number verification and password recovery proofs separate.
const ( PhoneVerify PhoneOTPPurpose = "verification" PhonePasswordReset PhoneOTPPurpose = "password-reset" )
type PhoneOTPRecord ¶
type PhoneOTPRecord struct {
BoundOwner string
OwnerBound bool
ID, PhoneNumber, Code string
Purpose PhoneOTPPurpose
Attempts int
CreatedAt, ExpiresAt time.Time
}
PhoneOTPRecord is one generation of a proof. The value is for server-side delivery only.
type PhoneOTPUse ¶
type PhoneOTPUse struct {
// ProviderProof binds an external verifier's answer to the exact local issuance.
ProviderProof string
ProviderAccepted bool
PhoneNumber, Code string
Purpose PhoneOTPPurpose
AllowedAttempts int
Now time.Time
}
func (PhoneOTPUse) Check ¶
func (u PhoneOTPUse) Check(r *PhoneOTPRecord) (PhoneOTPDecision, error)
Check returns the storage mutation to commit together with any verification result.
type PhoneRegistrationStore ¶
type PhoneRegistrationStore interface {
ApplyPhoneRegistration(context.Context, PhoneAccountAction, RegistrationUserFields) (PhoneAccountResult, error)
}
PhoneRegistrationStore consumes the exact verified proof and atomically writes the user, profile columns and optional first session. A profile validation error spends the proof only on first registration. Existing users and links keep their fields.
type PhoneSignUpOptions ¶
type PhoneVerificationInput ¶
type PhoneVerificationInput struct {
// AdditionalFields supplies writable user attributes only for first-time registration.
AdditionalFields map[string]any `json:"-"`
PhoneNumber string `json:"phoneNumber"`
Code string `json:"code"`
UpdatePhoneNumber bool `json:"updatePhoneNumber,omitempty"`
DisableSession bool `json:"disableSession,omitempty"`
}
func (PhoneVerificationInput) CheckProfileKeys ¶
func (in PhoneVerificationInput) CheckProfileKeys() error
CheckProfileKeys prevents a caller from placing a verification input in the profile.
type PhoneVerificationResult ¶
type PhoneVerificationResult struct {
Factor *AuthResult `json:"-"`
Status bool `json:"status"`
Token *string `json:"token"`
User User `json:"user"`
}
type Plugin ¶
type Plugin struct {
// StoredUserFields declares this plugin's scalar user columns for trusted
// profile readers. The keys are logical names and may map to different columns.
StoredUserFields map[string]UserField
// OrganizationRoleFields describes fields on the installed role endpoints.
OrganizationRoleFields map[string]SessionField
// TranslateError returns a localized HTTP error message for the request.
// An empty result preserves the original error response.
TranslateError func(ErrorContext, APIError) string
CredentialSessions *CredentialSessionResolver
// OnRequest can reject an HTTP request before endpoint dispatch. Path is
// relative to the auth mount. ClientIP follows the host's proxy policy.
OnRequest func(RequestContext) error
// PrepareOAuthLogin verifies a signed oauth_query before credential handling.
PrepareOAuthLogin func(EndpointContext, string) (OAuthLoginContinuation, error)
// PrepareOAuthSelection verifies a signed post-login query before an
// organization or team switch. It resumes only after a session cookie is issued.
PrepareOAuthSelection func(EndpointContext, string) (OAuthLoginContinuation, error)
// SessionResponse shapes the authenticated GET /get-session JSON response.
// One plugin per instance may supply it. An anonymous response stays null.
SessionResponse SessionResponseFunc
// ProjectDeviceSessions also applies SessionResponse to each remembered account.
ProjectDeviceSessions bool
ValidateStore func(Store) error
// OnValidateNewPassword checks a proposed credential before it is stored.
OnValidateNewPassword func(ctx context.Context, path, password string) error
// OnReadSession populates fields owned by an enabled plugin after session authentication.
OnReadSession func(context.Context, *SessionResult) error
ID string
Endpoints []Endpoint
// WellKnown publishes static JSON documents at issuer-relative discovery
// paths. It runs once per host after all plugins and stores are configured.
WellKnown func(*Auth, Store) (map[string]WellKnownDocument, error)
// SessionToken can supply an alternate credential for session lookups.
SessionToken func(*Auth, http.Header) string
// OnSessionCookie runs when a handler issues a session cookie.
OnSessionCookie func(SessionCookieEvent)
// contains filtered or unexported fields
}
Plugin contributes HTTP endpoints to an Auth instance.
func NewAdmin ¶
func NewAdmin(options AdminOptions) (Plugin, error)
func NewAnonymous ¶
func NewAnonymous(o AnonymousOptions) (Plugin, error)
func NewDeviceAuthorization ¶
func NewDeviceAuthorization(o DeviceAuthorizationOptions) (Plugin, error)
func NewEmailOTP ¶
func NewEmailOTP(o EmailOTPOptions) (Plugin, error)
NewEmailOTP enables single-use mailbox codes for registration, sign-in, verification and password recovery.
func NewJWT ¶
func NewJWT(opts JWTOptions) (Plugin, error)
func NewMagicLink ¶
func NewMagicLink(options MagicLinkOptions) (Plugin, error)
NewMagicLink registers mail delivery and one-time mailbox verification endpoints.
func NewMultiSession ¶
func NewMultiSession(options MultiSessionOptions) (Plugin, error)
func NewOAuthPopup ¶
func NewOAuthPopup() Plugin
NewOAuthPopup installs popup sign-in with the standard message type.
func NewOAuthPopupWithOptions ¶
func NewOAuthPopupWithOptions(options OAuthPopupOptions) (Plugin, error)
NewOAuthPopupWithOptions installs a client-specific message type selected by the host.
func NewOAuthProxy ¶
func NewOAuthProxy(o OAuthProxyOptions) (Plugin, error)
NewOAuthProxy enables provider code exchange on production followed by a browser-bound sign-in or account link on the originating preview.
func NewOneTap ¶
func NewOneTap(o OneTapOptions, fallback OAuthProvider) Plugin
NewOneTap constructs the server plugin. The Google provider configured on the auth instance supplies the verifier unless the plugin has a distinct client ID.
func NewOneTimeToken ¶
func NewOneTimeToken(opts OneTimeTokenOptions) (Plugin, error)
func NewPhoneNumber ¶
func NewPhoneNumber(o PhoneNumberOptions) (Plugin, error)
NewPhoneNumber enables phone-number proofs with an application-provided SMS sender.
func NewTwoFactor ¶
func NewTwoFactor(opts TwoFactorOptions) Plugin
NewTwoFactor implements credential login with authenticator codes or backup codes.
func NewUsername ¶
func NewUsername(options UsernameOptions) (Plugin, error)
type ProfileUpdate ¶
type ProfileUpdate struct {
AdditionalFields map[string]any
ClearPhoneNumber bool
Username, DisplayUsername *string
Name, Image *string
ClearImage, ClearUsername, ClearDisplayUsername bool
// contains filtered or unexported fields
}
ProfileUpdate changes the supplied fields. A Clear flag removes its field and takes precedence over a supplied value.
func (ProfileUpdate) PhysicalUserFields ¶
func (p ProfileUpdate) PhysicalUserFields() map[string]any
PhysicalUserFields provides only the columns previously validated by Auth.
type ProviderAccountCredential ¶
type ProviderAccountCredential struct {
ID, UserID, ProviderID, Subject string
OAuthTokens `json:"-"`
}
ProviderAccountCredential is internal adapter data. Credential values stay out of the serialized representation.
type ProviderCredentialStore ¶
type ProviderCredentialStore interface {
ProviderCredential(ctx context.Context, userID, id string) (ProviderAccountCredential, error)
UpdateProviderCredential(ctx context.Context, userID, id string, update func(ProviderAccountCredential) (ProviderAccountCredential, bool, error)) (ProviderAccountCredential, error)
}
ProviderCredentialStore locks a single owned account during rotation so concurrent refreshes cannot spend the same rotating refresh token twice.
type ProviderLogoutResult ¶
type ProviderLogoutResult struct {
Success bool `json:"success"`
URL string `json:"url"`
Redirect bool `json:"redirect"`
}
ProviderLogoutResult is returned after local sign-out when a linked provider has an end-session endpoint. Redirect reports whether the client should follow URL.
type PublicJWTKey ¶
type RateLimitRule ¶
RateLimitRule configures the maximum number of requests per peer and route during Window.
type RateLimitStorage ¶
type RateLimitStorage interface {
ConsumeRateLimit(ctx context.Context, key string, maximum int, window time.Duration, now time.Time) (time.Duration, error)
}
RateLimitStorage atomically admits one request, or returns how long the caller must wait. An error prevents the request from reaching its handler.
type RefreshTokenResult ¶
type RefreshTokenResult struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
AccessTokenExpiresAt *time.Time `json:"accessTokenExpiresAt,omitempty"`
RefreshTokenExpiresAt *time.Time `json:"refreshTokenExpiresAt"`
Scope *string `json:"scope"`
IDToken *string `json:"idToken"`
ProviderID string `json:"providerId"`
AccountID string `json:"accountId"`
}
type RegistrationUserFields ¶
type RegistrationUserFields struct {
// contains filtered or unexported fields
}
RegistrationUserFields holds the prepared values or validation error for a new profile. Adapters inspect it only after determining that the verified identity is new.
type RequestContext ¶
type RequestMeta ¶
type RequestMeta struct {
// TrustedDeviceCookie is the incoming signed browser cookie value, if any.
TrustedDeviceCookie string
CallbackURL string
IPAddress, UserAgent string
RememberMe *bool
}
RequestMeta records the originating client information for a login.
type Session ¶
type Session struct {
CredentialType string `json:"credentialType,omitempty"`
ImpersonatedBy *string `json:"impersonatedBy,omitempty"`
ActiveTeamID *string `json:"activeTeamId,omitempty"`
ActiveOrganizationID *string `json:"activeOrganizationId,omitempty"`
ID string `json:"id"`
UserID string `json:"userId"`
Token string `json:"token"`
IPAddress string `json:"ipAddress"`
UserAgent string `json:"userAgent"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
ExpiresAt time.Time `json:"expiresAt"`
// contains filtered or unexported fields
}
Session identifies one authenticated login.
func (Session) AdditionalField ¶
AdditionalField reads a public field returned by the configured instance. Numbers use int64. A present null is distinct from an absent field.
func (Session) AllowsCredentialAction ¶
AllowsCredentialAction reports whether this verified credential can exercise a specific application operation. Regular sessions use the route’s own authorization.
func (Session) IsApplicationCredential ¶
IsApplicationCredential identifies a per-request application-key session.
func (Session) MarshalJSON ¶
func (Session) RequireOwner ¶
RequireOwner requires a direct sign-in for operations that reveal credentials or change an account's authentication or permissions.
func (*Session) UnmarshalJSON ¶
type SessionCacheStore ¶
SessionCacheStore opts a store into browser snapshots. Return false when changes in storage require live validation even for a public session view.
type SessionCookieCacheOptions ¶
type SessionCookieCacheOptions struct {
// Strategy defaults to compact. JWT signs the snapshot with HS256.
// JWE encrypts it using a symmetric key derived for this cookie.
Strategy SessionCookieCacheStrategy
// MaxAge defaults to five minutes for persistent logins. A browser-session
// cookie holds a one-minute compact snapshot or a five-minute JWT or JWE.
MaxAge time.Duration
// Version defaults to "1". Change it across replicas to invalidate older snapshots.
Version string
// VersionFor derives the version from the session and user being issued or read.
// It may perform I/O with ctx and must be safe for concurrent requests.
// Choose either Version or VersionFor.
VersionFor func(ctx context.Context, session Session, user User) (string, error)
}
SessionCookieCacheOptions configures authenticated snapshots for browser session views. GetSession and authenticated operations continue to read the backing store.
type SessionCookieCacheStrategy ¶
type SessionCookieCacheStrategy string
SessionCookieCacheStrategy selects the wire format of a browser session snapshot.
const ( SessionCacheCompact SessionCookieCacheStrategy = "compact" SessionCacheJWT SessionCookieCacheStrategy = "jwt" SessionCacheJWE SessionCookieCacheStrategy = "jwe" )
type SessionCookieEvent ¶
type SessionCookieEvent struct {
Auth *Auth
Cookie http.Cookie
Route string
Request *http.Request
Header http.Header
}
SessionCookieEvent lets an extension add response headers when a session is issued.
type SessionField ¶
type SessionField = sessionfields.Field
SessionField declares a scalar session attribute. Column defaults to the public name. ServerOnly disables browser writes; Hidden omits the output.
type SessionFieldStore ¶
type SessionFieldStore interface {
ValidateSessionFields(map[string]SessionField) error
ReadSessionFields(context.Context, []Session, map[string]SessionField) (map[string]map[string]any, error)
UpdateSessionFields(context.Context, Session, map[string]SessionField, map[string]any, time.Time) error
}
SessionFieldStore persists configured physical columns. Reads must return only rows with the requested token, session ID and owner. Update must reauthorize that exact direct session and apply its patch atomically.
type SessionFieldType ¶
type SessionFieldType = sessionfields.Type
type SessionRefreshStore ¶
type SessionRefreshStore interface {
RefreshSession(ctx context.Context, token string, previousExpiry, now, nextExpiry time.Time) (bool, error)
DeleteExpiredSession(ctx context.Context, token string, now time.Time) error
}
SessionRefreshStore supports sliding expiration without reviving an expired or revoked session. Implementations compare the previously read expiry atomically with the update. A lost comparison returns false.
type SessionResponseFunc ¶
type SessionResponseFunc func(EndpointContext, SessionResult) (any, error)
SessionResponseFunc projects a validated HTTP session into a JSON response.
type SessionResult ¶
type SessionResult struct {
// NeedsRefresh is present for eligible deferred HTTP reads.
NeedsRefresh *bool `json:"needsRefresh,omitempty"`
Session Session `json:"session"`
User User `json:"user"`
}
SessionResult pairs the current session with its authenticated user.
type SignInInput ¶
SignInInput authenticates an existing email credential.
type SignUpInput ¶
type SignUpInput struct {
AdditionalFields map[string]any
Username, DisplayUsername *string
Name, Email, Password string
Image *string
}
SignUpInput describes a new email credential and public profile.
type StatusOnlyError ¶
type StatusOnlyError int
StatusOnlyError writes an HTTP status without a response body. Native callers can also retrieve its status and standard text with errors.As and *APIError.
func (StatusOnlyError) Error ¶
func (e StatusOnlyError) Error() string
func (StatusOnlyError) Unwrap ¶
func (e StatusOnlyError) Unwrap() error
type Store ¶
type Store interface {
CreateUser(context.Context, User, string, *StoredSession) error
Credential(context.Context, string) (User, string, error)
CreateSession(context.Context, StoredSession) error
Session(context.Context, string) (StoredSession, User, error)
DeleteSession(context.Context, string) error
ListSessions(context.Context, string) ([]StoredSession, error)
DeleteOtherSessions(context.Context, string, string) error
DeleteUserSession(context.Context, string, string) error
}
Store persists users, credentials, and sessions. CreateUser commits its three writes atomically. Deletions are idempotent. An empty keep token revokes all sessions for that user. Implementations must support concurrent requests.
type StoredJWTKey ¶
type StoredJWTKey struct {
PublicJWTKey
EncryptedPrivateKey string
}
type StoredSession ¶
type StoredSession struct {
Session
// contains filtered or unexported fields
}
StoredSession is the record passed to the storage adapter.
func (StoredSession) PhysicalSessionFields ¶
func (s StoredSession) PhysicalSessionFields() (map[string]any, error)
PhysicalSessionFields supplies an adapter with validated column names and their scalar values for the same transaction that inserts a session.
func (StoredSession) WithStoredSessionPatch ¶
func (s StoredSession) WithStoredSessionPatch(fields map[string]SessionField, patch map[string]any) (StoredSession, error)
WithStoredSessionPatch is for memory-backed adapters applying a validated patch while holding their session lock. It preserves fields from other nodes.
type TwoFactorOptions ¶
type TwoFactorOptions struct {
TOTP FactorTOTPOptions
Backup FactorBackupOptions
Lockout FactorLockoutOptions
OTP FactorOTPOptions
AllowPasswordless, SkipVerificationOnEnable bool
Issuer string
ChallengeLifetime time.Duration
TrustDeviceMaxAge time.Duration
}
type TwoFactorStore ¶
type TwoFactorStore interface {
FactorEnabled(context.Context, string) (bool, error)
WithTwoFactor(ctx context.Context, subject FactorSubject, decide func(FactorState) (FactorChange, error)) error
}
type User ¶
type User struct {
*PhoneNumberFields
*UsernameFields
LastLoginMethod *string `json:"lastLoginMethod,omitempty"`
IsAnonymous *bool `json:"isAnonymous,omitempty"`
*AdminUserFields
TwoFactorEnabled *bool `json:"twoFactorEnabled,omitempty"`
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
EmailVerified bool `json:"emailVerified"`
Image *string `json:"image"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
// contains filtered or unexported fields
}
User is the public account profile shared by all authentication methods.
func BootstrapAdmin ¶
func BootstrapAdmin(ctx context.Context, s AdminBootstrapStore, name, email, password string) (User, error)
BootstrapAdmin provisions the first default administrator through a trusted database connection. Applications should use the authenticated admin service for subsequent grants. This operation is available only through Go and authctl.
func (User) AdditionalField ¶
AdditionalField returns a public profile value, with int64 for numbers and a separate presence flag for nullable fields.
func (User) MarshalJSON ¶
func (*User) UnmarshalJSON ¶
type UserField ¶
type UserField = sessionfields.Field
UserField configures a scalar profile attribute. Column names its storage column. ServerOnly reserves writes for the host. Hidden excludes the field from responses.
type UserFieldStore ¶
type UserFieldStore interface {
ValidateUserFields(map[string]UserField) error
CreateUserWithFields(context.Context, User, string, *StoredSession, UserFieldValues) error
ReadUserFields(context.Context, string, map[string]UserField) (map[string]any, error)
UpdateUserFields(context.Context, string, *Session, ProfileUpdate, time.Time) error
}
UserFieldStore commits configured fields with their user/credential/session or profile writes. ReadUserFields returns public columns only, keyed by physical name. UpdateUserFields must lock the exact user and revalidate any supplied direct session.
type UserFieldValues ¶
type UserFieldValues struct {
// contains filtered or unexported fields
}
UserFieldValues carries validated physical values into the account creation transaction.
func (UserFieldValues) Columns ¶
func (v UserFieldValues) Columns() map[string]any
Columns returns a copy keyed by physical column name.
func (UserFieldValues) Present ¶
func (v UserFieldValues) Present() bool
Present reports whether any configured columns participate in this write.
type UsernameFields ¶
type UsernameFields struct {
Username *string `json:"username"`
*DisplayUsernameFields
}
UsernameFields preserves the distinction between an optional public name and a disabled plugin.
type UsernameOptions ¶
type UsernameOptions struct {
MinLength, MaxLength int
Validate, ValidateDisplay func(context.Context, string) bool
Normalize, NormalizeDisplay func(string) string
DisableNormalization, DisableDisplay, Immutable, DisableAvailability bool
ValidateAfterNormalization, ValidateDisplayAfterNormalization bool
}
type UsernameSignInInput ¶
type UsernameStore ¶
type UsernameStore interface {
CheckUsernameSchema(context.Context, bool) error
UpdateUsernameProfile(context.Context, string, string, ProfileUpdate, time.Time, bool) error
UsernameExists(context.Context, string) (bool, error)
UsernameCredential(context.Context, string) (User, string, error)
ReadUsername(context.Context, string, bool) (*UsernameFields, error)
}
type VerifiedEmailChange ¶
VerifiedEmailChange is returned only for the transaction that changed the verified state. A zero User indicates an already-verified link replay.
type VersionedSecret ¶
VersionedSecret identifies a signing key. The first entry issues credentials. Keep previous entries only for as long as credentials they signed should work.
type WellKnownDocument ¶
type WellKnownDocument struct {
Body json.RawMessage
Headers http.Header
}
WellKnownDocument is a JSON discovery response, captured at host initialization. Headers may customize caching and cross-origin access.
func (WellKnownDocument) ServeHTTP ¶
func (d WellKnownDocument) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves GET and HEAD when the document is mounted directly by the host.
type XMLDocument ¶
type XMLDocument []byte
XMLDocument is an XML representation encoded by a trusted plugin.
Source Files
¶
- account.go
- account_fields.go
- account_http.go
- account_lifecycle.go
- admin.go
- admin_bootstrap.go
- admin_http.go
- admin_user_fields.go
- anonymous.go
- auth.go
- cookie_scope.go
- cookies.go
- credential_session.go
- deviceauthorization.go
- disabled_paths.go
- email_token.go
- email_verification_observers.go
- email_verification_receipts.go
- email_verification_session.go
- emailotp.go
- emailotp_management.go
- env.go
- error_page.go
- error_translation.go
- existing_signup.go
- factor_encryption.go
- http.go
- http_description.go
- identity.go
- ip.go
- jwt_signing.go
- magiclink.go
- multisession.go
- oauth.go
- oauth_authorization.go
- oauth_http.go
- oauth_login_continuation.go
- oauth_logout.go
- oauth_popup.go
- oauth_proxy.go
- oauth_signed_query.go
- oauth_signed_token.go
- oauth_user_fields.go
- onetap.go
- onetimetoken.go
- password.go
- phone.go
- phone_accounts.go
- phone_admin.go
- phone_http.go
- phone_registration_fields.go
- plugin_oauth_flow.go
- plugin_provider.go
- plugin_redirect.go
- plugin_saml_logout.go
- plugin_session.go
- plugins.go
- provider_credentials.go
- provider_encryption.go
- rate_rules.go
- ratelimit.go
- service_jwt.go
- session_additional_fields.go
- session_cache_compact.go
- session_cache_cookies.go
- session_cache_jose.go
- session_cache_version.go
- session_refresh.go
- trusted_origins.go
- twofactor.go
- twofactor_delivery.go
- twofactor_import.go
- twofactor_settings.go
- twofactor_trust.go
- types.go
- user_additional_fields.go
- username.go
- well_known.go
Directories
¶
| Path | Synopsis |
|---|---|
|
adapters
|
|
|
memory
Package memory provides process-local storage for development and tests.
|
Package memory provides process-local storage for development and tests. |
|
mysql
Package mysql implements authentication storage using MySQL.
|
Package mysql implements authentication storage using MySQL. |
|
postgres
Package postgres implements authentication storage using PostgreSQL.
|
Package postgres implements authentication storage using PostgreSQL. |
|
sqlite
Package sqlite implements durable authentication storage using SQLite.
|
Package sqlite implements durable authentication storage using SQLite. |
|
sqlstore
Package sqlstore persists authentication data in SQLite, PostgreSQL, and MySQL.
|
Package sqlstore persists authentication data in SQLite, PostgreSQL, and MySQL. |
|
Package authtest provides in-process fixtures for applications testing their Plain Auth integration.
|
Package authtest provides in-process fixtures for applications testing their Plain Auth integration. |
|
Account management through the mounted authentication API.
|
Account management through the mounted authentication API. |
|
stripe
Package stripe calls the hosted Checkout and subscription endpoints with an existing Plain Auth client.
|
Package stripe calls the hosted Checkout and subscription endpoints with an existing Plain Auth client. |
|
cmd
|
|
|
authctl
command
Command authctl manages a host application's auth schema and secrets.
|
Command authctl manages a host application's auth schema and secrets. |
|
conformance
|
|
|
fixture
command
Command fixture serves a disposable instance to the differential client tests.
|
Command fixture serves a disposable instance to the differential client tests. |
|
fixture/env
command
Command env reports only public configuration and the signature of a fixed test value.
|
Command env reports only public configuration and the signature of a fixed test value. |
|
schemafixture
command
Command schemafixture batches independent differential tests over a JSON-lines stream.
|
Command schemafixture batches independent differential tests over a JSON-lines stream. |
|
scimfixture
command
Command scimfixture exercises server-only catalog methods from a test process.
|
Command scimfixture exercises server-only catalog methods from a test process. |
|
examples
|
|
|
basic
command
The application owns the listener, routes and database lifetime.
|
The application owns the listener, routes and database lifetime. |
|
internal
|
|
|
configenv
Package configenv validates server and CLI configuration.
|
Package configenv validates server and CLI configuration. |
|
emailaddress
Package emailaddress implements mailbox validation for wallet contact claims.
|
Package emailaddress implements mailbox validation for wallet contact claims. |
|
jsjson
Package jsjson encodes Go values using JSON.stringify string escaping.
|
Package jsjson encodes Go values using JSON.stringify string escaping. |
|
polarledger
Package polarledger describes the tables shared by the migration CLI and the optional Polar checkout module.
|
Package polarledger describes the tables shared by the migration CLI and the optional Polar checkout module. |
|
popupwire
Package popupwire defines the popup protocol shared by the handler and browser clients.
|
Package popupwire defines the popup protocol shared by the handler and browser clients. |
|
publicnet
Package publicnet classifies network addresses used in identity metadata.
|
Package publicnet classifies network addresses used in identity metadata. |
|
sessionfields
Package sessionfields validates the common configuration used by session issuance, public updates and the three relational schema generators.
|
Package sessionfields validates the common configuration used by session issuance, public updates and the three relational schema generators. |
|
walletschema
Package walletschema describes physical names in the wallet association model.
|
Package walletschema describes physical names in the wallet association model. |
|
plugins
|
|
|
access
Package access evaluates resource and action permissions for application roles.
|
Package access evaluates resource and action permissions for application roles. |
|
admin
Package admin provides role-checked user and session administration.
|
Package admin provides role-checked user and session administration. |
|
anonymous
Package anonymous creates guest sessions and transfers application data on sign-in.
|
Package anonymous creates guest sessions and transfers application data on sign-in. |
|
apikey
Package apikey provides user- and organization-owned credentials with independent expiration, scoped permissions, usage budgets and per-key rate limits.
|
Package apikey provides user- and organization-owned credentials with independent expiration, scoped permissions, usage budgets and per-key rate limits. |
|
bearer
Package bearer adds session authentication through the Authorization header.
|
Package bearer adds session authentication through the Authorization header. |
|
captcha
Package captcha verifies challenge tokens on selected authentication HTTP routes.
|
Package captcha verifies challenge tokens on selected authentication HTTP routes. |
|
customsession
Package customsession lets an application return its own authenticated session view.
|
Package customsession lets an application return its own authenticated session view. |
|
deviceauthorization
Package deviceauthorization adds RFC 8628 first-party device sign-in.
|
Package deviceauthorization adds RFC 8628 first-party device sign-in. |
|
emailotp
Package emailotp adds single-use email verification, login and recovery codes.
|
Package emailotp adds single-use email verification, login and recovery codes. |
|
i18n
Package i18n translates coded authentication errors for each request.
|
Package i18n translates coded authentication errors for each request. |
|
jwt
Package jwt signs short-lived service assertions and publishes public verification keys.
|
Package jwt signs short-lived service assertions and publishes public verification keys. |
|
lastlogin
Package lastlogin remembers the last login method in a browser-readable cookie.
|
Package lastlogin remembers the last login method in a browser-readable cookie. |
|
magiclink
Package magiclink adds single-use mailbox sign-in links.
|
Package magiclink adds single-use mailbox sign-in links. |
|
multisession
Package multisession lets one browser remember and switch among signed-in accounts.
|
Package multisession lets one browser remember and switch among signed-in accounts. |
|
oauthpopup
Package oauthpopup supports OAuth sign-in in a first-party popup window.
|
Package oauthpopup supports OAuth sign-in in a first-party popup window. |
|
oauthprovider
Package oauthprovider provides OAuth authorization-server and protected-resource integrations.
|
Package oauthprovider provides OAuth authorization-server and protected-resource integrations. |
|
oauthproxy
Package oauthproxy exchanges social sign-in codes at a registered production callback and completes the browser session on its originating preview.
|
Package oauthproxy exchanges social sign-in codes at a registered production callback and completes the browser session on its originating preview. |
|
onetap
Package onetap adds Google Identity Services browser sign-in.
|
Package onetap adds Google Identity Services browser sign-in. |
|
onetimetoken
Package onetimetoken transfers an active login between clients using a short-lived credential.
|
Package onetimetoken transfers an active login between clients using a short-lived credential. |
|
openapi
Package openapi publishes an OpenAPI 3.1 description of an auth handler.
|
Package openapi publishes an OpenAPI 3.1 description of an auth handler. |
|
organization
Package organization provides member-scoped groups, active selections and invitations.
|
Package organization provides member-scoped groups, active selections and invitations. |
|
passkey
Package passkey authenticates users with WebAuthn public-key credentials.
|
Package passkey authenticates users with WebAuthn public-key credentials. |
|
phonenumber
Package phonenumber provides SMS verification of phone numbers.
|
Package phonenumber provides SMS verification of phone numbers. |
|
pwnedpassword
Package pwnedpassword checks proposed credentials against the Pwned Passwords range API.
|
Package pwnedpassword checks proposed credentials against the Pwned Passwords range API. |
|
scim
Package scim provisions directory-owned Users and Groups through the SCIM 2.0 protocol.
|
Package scim provisions directory-owned Users and Groups through the SCIM 2.0 protocol. |
|
siwe
Package siwe authenticates externally owned Ethereum accounts using signed EIP-4361 messages and one-use server challenges.
|
Package siwe authenticates externally owned Ethereum accounts using signed EIP-4361 messages and one-use server challenges. |
|
sso
Package sso administers persisted enterprise OpenID Connect providers.
|
Package sso administers persisted enterprise OpenID Connect providers. |
|
stripe
Package stripe authenticates Stripe webhook deliveries and dispatches their events.
|
Package stripe authenticates Stripe webhook deliveries and dispatches their events. |
|
twofactor
Package twofactor adds authenticator codes and single-use backup codes to credential sign-in.
|
Package twofactor adds authenticator codes and single-use backup codes to credential sign-in. |
|
username
Package username adds optional public usernames and credential sign-in.
|
Package username adds optional public usernames and credential sign-in. |
|
Package providers configures supported social sign-in providers.
|
Package providers configures supported social sign-in providers. |
|
Package schema generates fresh-database DDL for authentication and plugin tables.
|
Package schema generates fresh-database DDL for authentication and plugin tables. |