models

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OAuthServerClientTypePublic       = "public"
	OAuthServerClientTypeConfidential = "confidential"
)

OAuth client type constants

View Source
const (
	TokenEndpointAuthMethodNone              = "none"
	TokenEndpointAuthMethodClientSecretBasic = "client_secret_basic"
	TokenEndpointAuthMethodClientSecretPost  = "client_secret_post"
)

OAuth token endpoint authentication method constants

View Source
const (
	ScopeOpenID  = "openid"
	ScopeEmail   = "email"
	ScopeProfile = "profile"
	ScopePhone   = "phone"
)

OAuth/OIDC scope constants

View Source
const (
	SessionValid        SessionValidityReason = iota
	SessionPastNotAfter                       = iota
	SessionPastTimebox                        = iota
	SessionTimedOut                           = iota
	SessionLowAAL                             = iota
)
View Source
const (
	WebAuthnChallengeTypeSignup         = "signup"
	WebAuthnChallengeTypeRegistration   = "registration"
	WebAuthnChallengeTypeAuthentication = "authentication"
)
View Source
const CreatedAt = "created_at"
View Source
const OAuthClientStateTimeout = 5 * time.Minute
View Source
const Phone = "phone"
View Source
const TOTP = "totp"
View Source
const Web3Grant = "web3"
View Source
const Web3Provider = "web3"
View Source
const WebAuthn = "webauthn"

Variables

View Source
var SupportedOAuthScopes = []string{
	ScopeOpenID,
	ScopeProfile,
	ScopeEmail,
	ScopePhone,
}

SupportedOAuthScopes defines all OAuth/OIDC scopes supported by the server

Functions

func AddClaimToSession

func AddClaimToSession(tx *storage.Connection, sessionId uuid.UUID, authenticationMethod AuthenticationMethod) error

func CleanupExpiredOAuthServerAuthorizations

func CleanupExpiredOAuthServerAuthorizations(tx *storage.Connection) error

CleanupExpiredOAuthServerAuthorizations marks expired authorizations as expired

func ClearAllOneTimeTokensForUser

func ClearAllOneTimeTokensForUser(tx *storage.Connection, userID uuid.UUID) error

func ClearOneTimeTokenForUser

func ClearOneTimeTokenForUser(tx *storage.Connection, userID uuid.UUID, tokenType OneTimeTokenType) error

func CompareAAL

func CompareAAL(a, b AuthenticatorAssuranceLevel) int

CompareAAL returns 0 if both AAL levels are equal, > 0 if A is a higher level than B or < 0 if A is a lower level than B.

func CountCustomOAuthProviders

func CountCustomOAuthProviders(tx *storage.Connection) (int, error)

CountCustomOAuthProviders counts all custom OAuth providers

func CountOtherUsers

func CountOtherUsers(tx *storage.Connection, id uuid.UUID) (int, error)

CountOtherUsers counts how many other users exist besides the one provided

func CountWebAuthnCredentialsByUserID

func CountWebAuthnCredentialsByUserID(conn *storage.Connection, userID uuid.UUID) (int, error)

func CreateCustomOAuthProvider

func CreateCustomOAuthProvider(tx *storage.Connection, provider *CustomOAuthProvider) error

CreateCustomOAuthProvider creates a new custom OAuth provider

func CreateOAuthServerAuthorization

func CreateOAuthServerAuthorization(tx *storage.Connection, auth *OAuthServerAuthorization) error

CreateOAuthServerAuthorization creates a new OAuth authorization in the database

func CreateOAuthServerClient

func CreateOAuthServerClient(tx *storage.Connection, client *OAuthServerClient) error

CreateOAuthServerClient creates a new OAuth client in the database

func CreateOneTimeToken

func CreateOneTimeToken(tx *storage.Connection, userID uuid.UUID, relatesTo, tokenHash string, tokenType OneTimeTokenType) error

func DeleteCustomOAuthProvider

func DeleteCustomOAuthProvider(tx *storage.Connection, id uuid.UUID) error

DeleteCustomOAuthProvider deletes a custom OAuth provider

func DeleteExpiredFactors

func DeleteExpiredFactors(tx *storage.Connection, validityDuration time.Duration) error

func DeleteFactorsByUserId

func DeleteFactorsByUserId(tx *storage.Connection, userId uuid.UUID) error

func DeleteUnverifiedFactors

func DeleteUnverifiedFactors(tx *storage.Connection, user *User, factorType string) error

func DeleteWebAuthnCredentialsByUserID

func DeleteWebAuthnCredentialsByUserID(tx *storage.Connection, userID uuid.UUID) error

func FindProvidersByUser

func FindProvidersByUser(tx *storage.Connection, user *User) ([]string, error)

FindProvidersByUser returns all providers associated to a user

func FindUserWithRefreshToken

func FindUserWithRefreshToken(tx *storage.Connection, dbEncryption conf.DatabaseEncryptionConfiguration, token string, forUpdate bool) (*User, any, *Session, error)

FindUserWithRefreshToken finds a user from the provided refresh token. If forUpdate is set to true, then the SELECT statement used by the query has the form SELECT ... FOR UPDATE SKIP LOCKED. This means that a FOR UPDATE lock will only be acquired if there's no other lock. In case there is a lock, a IsNotFound(err) error will be returned.

Second value returned is either *models.RefreshToken or *crypto.RefreshToken.

func GetAccountLinkingDomain

func GetAccountLinkingDomain(provider string, ownLinkingDomains []string) string

GetAccountLinkingDomain returns a string that describes the account linking domain. An account linking domain describes a set of Identity entities that _should_ generally fall under the same User entity. It's just a runtime string, and is not typically persisted in the database. This value can vary across time.

func HasAllScopes

func HasAllScopes(grantedScopes, requestedScopes []string) bool

HasAllScopes checks if the granted scopes include all of the requested scopes

func HasScope

func HasScope(scopes []string, scope string) bool

HasScope checks if the given scope list includes a specific scope

func InvalidateSessionsWithAALLessThan

func InvalidateSessionsWithAALLessThan(tx *storage.Connection, userID uuid.UUID, level string) error

func IsDuplicatedPhone

func IsDuplicatedPhone(tx *storage.Connection, phone, aud string) (bool, error)

IsDuplicatedPhone checks if the phone number already exists in the users table

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError returns whether an error represents a "not found" error.

func IsSupportedScope

func IsSupportedScope(scope string) bool

IsSupportedScope checks if a scope is in the supported scopes list

func IsUniqueConstraintViolatedError

func IsUniqueConstraintViolatedError(err error) bool

func Logout

func Logout(tx *storage.Connection, userId uuid.UUID) error

Logout deletes all sessions for a user.

func LogoutAllExceptMe

func LogoutAllExceptMe(tx *storage.Connection, sessionId uuid.UUID, userID uuid.UUID) error

LogoutAllExceptMe deletes all sessions for a user except the current one

func LogoutSession

func LogoutSession(tx *storage.Connection, sessionId uuid.UUID) error

LogoutSession deletes the current session for a user

func NewAuditLogEntry

func NewAuditLogEntry(config conf.AuditLogConfiguration, r *http.Request, tx *storage.Connection, actor *User, action AuditAction, ipAddress string, traits map[string]interface{}) error

func ParseScopeString

func ParseScopeString(scopeString string) []string

ParseScopeString parses a space-separated scope string into a slice

func RevokeOAuthServerConsentsByClient

func RevokeOAuthServerConsentsByClient(tx *storage.Connection, clientID uuid.UUID) error

RevokeOAuthServerConsentsByClient revokes all consents for a specific client

func RevokeOAuthServerConsentsByUser

func RevokeOAuthServerConsentsByUser(tx *storage.Connection, userID uuid.UUID) error

RevokeOAuthServerConsentsByUser revokes all consents for a specific user

func RevokeOAuthSessions

func RevokeOAuthSessions(tx *storage.Connection, userID uuid.UUID, oauthClientID uuid.UUID) error

RevokeOAuthSessions deletes all sessions associated with a specific OAuth client for a user

func RevokeTokenFamily

func RevokeTokenFamily(tx *storage.Connection, token *RefreshToken) error

RevokeTokenFamily revokes all refresh tokens that descended from the provided token.

func TruncateAll

func TruncateAll(conn *storage.Connection) error

TruncateAll deletes all data from the database, as managed by GoTrue. Not intended for use outside of tests.

func UpdateCustomOAuthProvider

func UpdateCustomOAuthProvider(tx *storage.Connection, provider *CustomOAuthProvider) error

UpdateCustomOAuthProvider updates an existing custom OAuth provider

func UpdateOAuthServerClient

func UpdateOAuthServerClient(tx *storage.Connection, client *OAuthServerClient) error

UpdateOAuthServerClient updates an existing OAuth client in the database

func UpsertOAuthServerConsent

func UpsertOAuthServerConsent(tx *storage.Connection, consent *OAuthServerConsent) error

UpsertOAuthServerConsent creates or updates an OAuth consent

Types

type AMRClaim

type AMRClaim struct {
	ID                   uuid.UUID `json:"id" db:"id"`
	SessionID            uuid.UUID `json:"session_id" db:"session_id"`
	CreatedAt            time.Time `json:"created_at" db:"created_at"`
	UpdatedAt            time.Time `json:"updated_at" db:"updated_at"`
	AuthenticationMethod *string   `json:"authentication_method" db:"authentication_method"`
}

func (*AMRClaim) GetAuthenticationMethod

func (a *AMRClaim) GetAuthenticationMethod() string

func (*AMRClaim) IsAAL2Claim

func (cl *AMRClaim) IsAAL2Claim() bool

func (AMRClaim) TableName

func (AMRClaim) TableName() string

type AMREntry

type AMREntry struct {
	Method    string `json:"method"`
	Timestamp int64  `json:"timestamp"`
	Provider  string `json:"provider,omitempty"`
}

AMREntry represents a method that a user has logged in together with the corresponding time

type AccountLinkingDecision

type AccountLinkingDecision = int
const (
	AccountExists AccountLinkingDecision = iota
	CreateAccount
	LinkAccount
	MultipleAccounts
)

type AccountLinkingResult

type AccountLinkingResult struct {
	Decision       AccountLinkingDecision
	User           *User
	Identities     []*Identity
	LinkingDomain  string
	CandidateEmail provider.Email
}

func DetermineAccountLinking

func DetermineAccountLinking(tx *storage.Connection, config *conf.GlobalConfiguration, emails []provider.Email, aud, providerName, sub string) (AccountLinkingResult, error)

DetermineAccountLinking uses the provided data and database state to compute a decision on whether: - A new User should be created (CreateAccount) - A new Identity should be created (LinkAccount) with a UserID pointing to an existing user account - Nothing should be done (AccountExists) - It's not possible to decide due to data inconsistency (MultipleAccounts) and the caller should decide

Errors signal failure in processing only, like database access errors.

type AuditAction

type AuditAction string
const (
	LoginAction                     AuditAction = "login"
	LogoutAction                    AuditAction = "logout"
	InviteAcceptedAction            AuditAction = "invite_accepted"
	UserSignedUpAction              AuditAction = "user_signedup"
	UserInvitedAction               AuditAction = "user_invited"
	UserDeletedAction               AuditAction = "user_deleted"
	UserModifiedAction              AuditAction = "user_modified"
	UserRecoveryRequestedAction     AuditAction = "user_recovery_requested"
	UserReauthenticateAction        AuditAction = "user_reauthenticate_requested"
	UserConfirmationRequestedAction AuditAction = "user_confirmation_requested"
	UserRepeatedSignUpAction        AuditAction = "user_repeated_signup"
	UserUpdatePasswordAction        AuditAction = "user_updated_password"
	TokenRevokedAction              AuditAction = "token_revoked"
	TokenRefreshedAction            AuditAction = "token_refreshed"
	GenerateRecoveryCodesAction     AuditAction = "generate_recovery_codes"
	EnrollFactorAction              AuditAction = "factor_in_progress"
	UnenrollFactorAction            AuditAction = "factor_unenrolled"
	CreateChallengeAction           AuditAction = "challenge_created"
	VerifyFactorAction              AuditAction = "verification_attempted"
	DeleteFactorAction              AuditAction = "factor_deleted"
	DeleteRecoveryCodesAction       AuditAction = "recovery_codes_deleted"
	UpdateFactorAction              AuditAction = "factor_updated"
	MFACodeLoginAction              AuditAction = "mfa_code_login"
	IdentityUnlinkAction            AuditAction = "identity_unlinked"
	PasskeyCreatedAction            AuditAction = "passkey_created"
	PasskeyUpdatedAction            AuditAction = "passkey_updated"
	PasskeyDeletedAction            AuditAction = "passkey_deleted"
)

type AuditLogEntry

type AuditLogEntry struct {
	ID        uuid.UUID `json:"id" db:"id"`
	Payload   JSONMap   `json:"payload" db:"payload"`
	CreatedAt time.Time `json:"created_at" db:"created_at"`
	IPAddress string    `json:"ip_address" db:"ip_address"`

	DONTUSEINSTANCEID uuid.UUID `json:"-" db:"instance_id"`
}

AuditLogEntry is the database model for audit log entries.

func FindAuditLogEntries

func FindAuditLogEntries(tx *storage.Connection, filterColumns []string, filterValue string, pageParams *Pagination) ([]*AuditLogEntry, error)

func (AuditLogEntry) TableName

func (AuditLogEntry) TableName() string

type AuthenticationMethod

type AuthenticationMethod int
const (
	OAuth AuthenticationMethod = iota
	PasswordGrant
	OTP
	TOTPSignIn
	MFAPhone
	MFAWebAuthn
	SSOSAML
	Recovery
	Invite
	MagicLink
	EmailSignup
	EmailChange
	TokenRefresh
	Anonymous
	Web3
	OAuthProviderAuthorizationCode
	PasskeyLogin
)

func ParseAuthenticationMethod

func ParseAuthenticationMethod(authMethod string) (AuthenticationMethod, error)

func (AuthenticationMethod) String

func (authMethod AuthenticationMethod) String() string

type AuthenticatorAssuranceLevel

type AuthenticatorAssuranceLevel int
const (
	AAL1 AuthenticatorAssuranceLevel = iota
	AAL2
	AAL3
)

func ParseAAL

func ParseAAL(value *string) AuthenticatorAssuranceLevel

func (AuthenticatorAssuranceLevel) PointerString

func (aal AuthenticatorAssuranceLevel) PointerString() *string

func (AuthenticatorAssuranceLevel) String

func (aal AuthenticatorAssuranceLevel) String() string

type Challenge

type Challenge struct {
	ID                  uuid.UUID            `json:"challenge_id" db:"id"`
	FactorID            uuid.UUID            `json:"factor_id" db:"factor_id"`
	CreatedAt           time.Time            `json:"created_at" db:"created_at"`
	VerifiedAt          *time.Time           `json:"verified_at,omitempty" db:"verified_at"`
	IPAddress           string               `json:"ip_address" db:"ip_address"`
	Factor              *Factor              `json:"factor,omitempty" belongs_to:"factor"`
	OtpCode             string               `json:"otp_code,omitempty" db:"otp_code"`
	WebAuthnSessionData *WebAuthnSessionData `json:"web_authn_session_data,omitempty" db:"web_authn_session_data"`
}

func (*Challenge) GetExpiryTime

func (c *Challenge) GetExpiryTime(expiryDuration float64) time.Time

func (*Challenge) GetOtpCode

func (c *Challenge) GetOtpCode(decryptionKeys map[string]string, encrypt bool, encryptionKeyID string) (string, bool, error)

func (*Challenge) HasExpired

func (c *Challenge) HasExpired(expiryDuration float64) bool

func (*Challenge) SetOtpCode

func (c *Challenge) SetOtpCode(otpCode string, encrypt bool, encryptionKeyID, encryptionKey string) error

func (Challenge) TableName

func (Challenge) TableName() string

func (*Challenge) Verify

func (c *Challenge) Verify(tx *storage.Connection) error

Update the verification timestamp

type ChallengeNotFoundError

type ChallengeNotFoundError struct{}

ChallengeNotFoundError represents when a user is not found.

func (ChallengeNotFoundError) Error

func (e ChallengeNotFoundError) Error() string

func (ChallengeNotFoundError) Is

func (e ChallengeNotFoundError) Is(target error) bool

type Cleaner

type Cleaner interface {
	Clean(*storage.Connection) (int, error)
}

type Cleanup

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

func NewCleanup

func NewCleanup(config *conf.GlobalConfiguration) *Cleanup

func (*Cleanup) Clean

func (c *Cleanup) Clean(db *storage.Connection) (int, error)

Cleanup removes stale entities in the database. You can call it on each request or as a periodic background job. It does quick lockless updates or deletes, has an execution timeout and acquire timeout so that cleanups do not affect performance of other database jobs. Note that calling this does not clean up the whole database, but does a small piecemeal clean up each time when called.

type CodeChallengeMethod

type CodeChallengeMethod int
const (
	SHA256 CodeChallengeMethod = iota
	Plain
)

func ParseCodeChallengeMethod

func ParseCodeChallengeMethod(codeChallengeMethod string) (CodeChallengeMethod, error)

func (CodeChallengeMethod) String

func (codeChallengeMethod CodeChallengeMethod) String() string

type ConfirmationOrRecoveryTokenNotFoundError

type ConfirmationOrRecoveryTokenNotFoundError struct{}

ConfirmationOrRecoveryTokenNotFoundError represents when a confirmation or recovery token is not found.

func (ConfirmationOrRecoveryTokenNotFoundError) Error

func (ConfirmationOrRecoveryTokenNotFoundError) Is

type ConfirmationTokenNotFoundError

type ConfirmationTokenNotFoundError struct{}

ConfirmationTokenNotFoundError represents when a confirmation token is not found.

func (ConfirmationTokenNotFoundError) Error

func (ConfirmationTokenNotFoundError) Is

type CustomOAuthProvider

type CustomOAuthProvider struct {
	ID           uuid.UUID    `db:"id" json:"id"`
	ProviderType ProviderType `db:"provider_type" json:"provider_type"`

	// Common fields for both OAuth2 and OIDC
	Identifier          string        `db:"identifier" json:"identifier"`
	Name                string        `db:"name" json:"name"`
	ClientID            string        `db:"client_id" json:"client_id"`
	ClientSecret        string        `db:"client_secret" json:"-"` // Encrypted via EncryptedString, never expose in JSON
	AcceptableClientIDs slices.String `db:"acceptable_client_ids" json:"acceptable_client_ids"`
	Scopes              slices.String `db:"scopes" json:"scopes"`
	PKCEEnabled         bool          `db:"pkce_enabled" json:"pkce_enabled"`
	AttributeMapping    slices.Map    `db:"attribute_mapping" json:"attribute_mapping"`
	AuthorizationParams slices.Map    `db:"authorization_params" json:"authorization_params"`
	Enabled             bool          `db:"enabled" json:"enabled"`
	EmailOptional       bool          `db:"email_optional" json:"email_optional"`

	// OIDC-specific fields (null for OAuth2 providers)
	Issuer            *string        `db:"issuer" json:"issuer,omitempty"`
	DiscoveryURL      *string        `db:"discovery_url" json:"discovery_url,omitempty"`
	SkipNonceCheck    bool           `db:"skip_nonce_check" json:"skip_nonce_check"`
	CachedDiscovery   *OIDCDiscovery `db:"cached_discovery" json:"discovery_document,omitempty"`
	DiscoveryCachedAt *time.Time     `db:"discovery_cached_at" json:"-"` // Internal caching, not exposed in API

	// OAuth2-specific fields (null for OIDC providers)
	AuthorizationURL *string `db:"authorization_url" json:"authorization_url,omitempty"`
	TokenURL         *string `db:"token_url" json:"token_url,omitempty"`
	UserinfoURL      *string `db:"userinfo_url" json:"userinfo_url,omitempty"`
	JwksURI          *string `db:"jwks_uri" json:"jwks_uri,omitempty"`

	// Timestamps
	CreatedAt time.Time `db:"created_at" json:"created_at"`
	UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}

CustomOAuthProvider represents a custom OAuth2 or OIDC provider configuration

func FindAllCustomOAuthProviders

func FindAllCustomOAuthProviders(tx *storage.Connection) ([]*CustomOAuthProvider, error)

FindAllCustomOAuthProviders finds all custom OAuth providers

func FindAllCustomOAuthProvidersByType

func FindAllCustomOAuthProvidersByType(tx *storage.Connection, providerType ProviderType) ([]*CustomOAuthProvider, error)

FindAllCustomOAuthProvidersByType finds all custom OAuth providers of a specific type

func FindCustomOAuthProviderByID

func FindCustomOAuthProviderByID(tx *storage.Connection, id uuid.UUID) (*CustomOAuthProvider, error)

FindCustomOAuthProviderByID finds a custom OAuth provider by ID

func FindCustomOAuthProviderByIdentifier

func FindCustomOAuthProviderByIdentifier(tx *storage.Connection, identifier string) (*CustomOAuthProvider, error)

FindCustomOAuthProviderByIdentifier finds a custom OAuth provider by identifier

func (*CustomOAuthProvider) ClearDiscoveryCache

func (p *CustomOAuthProvider) ClearDiscoveryCache()

ClearDiscoveryCache removes the cached discovery document.

func (*CustomOAuthProvider) GetClientSecret

func (p *CustomOAuthProvider) GetClientSecret(dbEncryption conf.DatabaseEncryptionConfiguration) (string, error)

GetClientSecret decrypts and returns the client secret using the configured database decryption keys. It expects the client secret to be stored in encrypted form when encryption is enabled, but will also handle plaintext secrets (for deployments where encryption is not yet configured).

func (*CustomOAuthProvider) GetDiscoveryURL

func (p *CustomOAuthProvider) GetDiscoveryURL() string

GetDiscoveryURL returns the discovery URL for OIDC providers If discovery_url is set, use that; otherwise construct from issuer

func (*CustomOAuthProvider) GetProviderName

func (p *CustomOAuthProvider) GetProviderName() string

GetProviderName returns the provider identifier (which already includes "custom:" prefix)

func (*CustomOAuthProvider) IsOAuth2

func (p *CustomOAuthProvider) IsOAuth2() bool

IsOAuth2 returns true if this is an OAuth2 provider

func (*CustomOAuthProvider) IsOIDC

func (p *CustomOAuthProvider) IsOIDC() bool

IsOIDC returns true if this is an OIDC provider

func (*CustomOAuthProvider) SetClientSecret

func (p *CustomOAuthProvider) SetClientSecret(secret string, dbEncryption conf.DatabaseEncryptionConfiguration) error

SetClientSecret encrypts and stores the client secret using the configured database encryption settings. If encryption is disabled, the secret is stored in plaintext (temporary fallback for now)

func (*CustomOAuthProvider) SetDiscoveryCache

func (p *CustomOAuthProvider) SetDiscoveryCache(discovery *OIDCDiscovery)

SetDiscoveryCache stores a validated OIDC discovery document and records the cache time.

func (CustomOAuthProvider) TableName

func (p CustomOAuthProvider) TableName() string

type CustomOAuthProviderNotFoundError

type CustomOAuthProviderNotFoundError struct{}

CustomOAuthProviderNotFoundError represents an error when a custom OAuth/OIDC provider can't be found

func (CustomOAuthProviderNotFoundError) Error

func (CustomOAuthProviderNotFoundError) Is

type Factor

type Factor struct {
	ID uuid.UUID `json:"id" db:"id"`
	// TODO: Consider removing this nested user field. We don't use it.
	User                      User                       `json:"-" belongs_to:"user"`
	UserID                    uuid.UUID                  `json:"-" db:"user_id"`
	CreatedAt                 time.Time                  `json:"created_at" db:"created_at"`
	UpdatedAt                 time.Time                  `json:"updated_at" db:"updated_at"`
	Status                    string                     `json:"status" db:"status"`
	FriendlyName              string                     `json:"friendly_name,omitempty" db:"friendly_name"`
	Secret                    string                     `json:"-" db:"secret"`
	FactorType                string                     `json:"factor_type" db:"factor_type"`
	Challenge                 []Challenge                `json:"-" has_many:"challenges"`
	Phone                     storage.NullString         `json:"phone" db:"phone"`
	LastChallengedAt          *time.Time                 `json:"last_challenged_at" db:"last_challenged_at"`
	WebAuthnCredential        *MFAWebAuthnCredential     `json:"-" db:"web_authn_credential"`
	WebAuthnAAGUID            *uuid.UUID                 `json:"web_authn_aaguid,omitempty" db:"web_authn_aaguid"`
	LastWebAuthnChallengeData *LastWebAuthnChallengeData `json:"last_webauthn_challenge_data,omitempty" db:"last_webauthn_challenge_data"`
}

func FindFactorByFactorID

func FindFactorByFactorID(conn *storage.Connection, factorID uuid.UUID) (*Factor, error)

func NewFactor

func NewFactor(user *User, friendlyName string, factorType string, state FactorState) *Factor

func NewPhoneFactor

func NewPhoneFactor(user *User, phone, friendlyName string) *Factor

func NewTOTPFactor

func NewTOTPFactor(user *User, friendlyName string) *Factor

func NewWebAuthnFactor

func NewWebAuthnFactor(user *User, friendlyName string) *Factor

func (*Factor) CreateChallenge

func (f *Factor) CreateChallenge(ipAddress string) *Challenge

func (*Factor) CreatePhoneChallenge

func (f *Factor) CreatePhoneChallenge(ipAddress string, otpCode string, encrypt bool, encryptionKeyID, encryptionKey string) (*Challenge, error)

func (*Factor) DowngradeSessionsToAAL1

func (f *Factor) DowngradeSessionsToAAL1(tx *storage.Connection) error

func (*Factor) FindChallengeByID

func (f *Factor) FindChallengeByID(conn *storage.Connection, challengeID uuid.UUID) (*Challenge, error)

func (*Factor) FindLatestUnexpiredChallenge

func (f *Factor) FindLatestUnexpiredChallenge(tx *storage.Connection, expiryDuration float64) (*Challenge, error)

func (*Factor) GetSecret

func (f *Factor) GetSecret(decryptionKeys map[string]string, encrypt bool, encryptionKeyID string) (string, bool, error)

func (*Factor) IsPhoneFactor

func (f *Factor) IsPhoneFactor() bool

func (*Factor) IsUnverified

func (f *Factor) IsUnverified() bool

func (*Factor) IsVerified

func (f *Factor) IsVerified() bool

func (*Factor) SaveWebAuthnCredential

func (f *Factor) SaveWebAuthnCredential(tx *storage.Connection, credential *webauthn.Credential) error

func (*Factor) SetSecret

func (f *Factor) SetSecret(secret string, encrypt bool, encryptionKeyID, encryptionKey string) error

func (Factor) TableName

func (Factor) TableName() string

func (*Factor) UpdateFriendlyName

func (f *Factor) UpdateFriendlyName(tx *storage.Connection, friendlyName string) error

UpdateFriendlyName changes the friendly name

func (*Factor) UpdateLastWebAuthnChallenge

func (f *Factor) UpdateLastWebAuthnChallenge(tx *storage.Connection, challenge *Challenge, challengeType string, credentialResponse interface{}) error

func (*Factor) UpdatePhone

func (f *Factor) UpdatePhone(tx *storage.Connection, phone string) error

func (*Factor) UpdateStatus

func (f *Factor) UpdateStatus(tx *storage.Connection, state FactorState) error

UpdateStatus modifies the factor status

func (*Factor) WriteChallengeToDatabase

func (f *Factor) WriteChallengeToDatabase(tx *storage.Connection, challenge *Challenge) error

type FactorNotFoundError

type FactorNotFoundError struct{}

FactorNotFoundError represents when a user is not found.

func (FactorNotFoundError) Error

func (e FactorNotFoundError) Error() string

func (FactorNotFoundError) Is

func (e FactorNotFoundError) Is(target error) bool

type FactorState

type FactorState int
const (
	FactorStateUnverified FactorState = iota
	FactorStateVerified
)

func (FactorState) String

func (factorState FactorState) String() string

type FlowState

type FlowState struct {
	ID                   uuid.UUID  `json:"id" db:"id"`
	UserID               *uuid.UUID `json:"user_id,omitempty" db:"user_id"`
	AuthCode             *string    `json:"auth_code,omitempty" db:"auth_code"`
	AuthenticationMethod string     `json:"authentication_method" db:"authentication_method"`
	CodeChallenge        *string    `json:"code_challenge,omitempty" db:"code_challenge"`
	CodeChallengeMethod  *string    `json:"code_challenge_method,omitempty" db:"code_challenge_method"`
	ProviderType         string     `json:"provider_type" db:"provider_type"`
	ProviderAccessToken  string     `json:"provider_access_token" db:"provider_access_token"`
	ProviderRefreshToken string     `json:"provider_refresh_token" db:"provider_refresh_token"`
	AuthCodeIssuedAt     *time.Time `json:"auth_code_issued_at" db:"auth_code_issued_at"`
	CreatedAt            time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt            time.Time  `json:"updated_at" db:"updated_at"`

	// OAuth context fields (previously stored in JWT state parameter)
	InviteToken        *string    `json:"invite_token,omitempty" db:"invite_token"`
	Referrer           *string    `json:"referrer,omitempty" db:"referrer"`
	OAuthClientStateID *uuid.UUID `json:"oauth_client_state_id,omitempty" db:"oauth_client_state_id"`
	LinkingTargetID    *uuid.UUID `json:"linking_target_id,omitempty" db:"linking_target_id"`
	EmailOptional      bool       `json:"email_optional" db:"email_optional"`
}

func FindFlowStateByAuthCode

func FindFlowStateByAuthCode(tx *storage.Connection, authCode string) (*FlowState, error)

func FindFlowStateByID

func FindFlowStateByID(tx *storage.Connection, id string) (*FlowState, error)

func FindFlowStateByUserID

func FindFlowStateByUserID(tx *storage.Connection, id string, authenticationMethod AuthenticationMethod) (*FlowState, error)

func NewFlowState

func NewFlowState(params FlowStateParams) (*FlowState, error)

NewFlowState creates a flow state for both PKCE and implicit flows. PKCE fields (AuthCode, CodeChallenge, CodeChallengeMethod) are only set if CodeChallenge is provided in params. Returns an error if CodeChallenge is provided but CodeChallengeMethod is invalid.

func (*FlowState) IsExpired

func (f *FlowState) IsExpired(expiryDuration time.Duration) bool

func (*FlowState) IsPKCE

func (f *FlowState) IsPKCE() bool

IsPKCE returns true if this flow state represents a PKCE flow

func (*FlowState) RecordAuthCodeIssuedAtTime

func (f *FlowState) RecordAuthCodeIssuedAtTime(tx *storage.Connection) error

func (FlowState) TableName

func (FlowState) TableName() string

func (*FlowState) VerifyPKCE

func (f *FlowState) VerifyPKCE(codeVerifier string) error

type FlowStateNotFoundError

type FlowStateNotFoundError struct{}

FlowStateNotFoundError represents an error when an FlowState can't be found.

func (FlowStateNotFoundError) Error

func (e FlowStateNotFoundError) Error() string

func (FlowStateNotFoundError) Is

func (e FlowStateNotFoundError) Is(target error) bool

type FlowStateParams

type FlowStateParams struct {
	ProviderType         string
	AuthenticationMethod AuthenticationMethod
	CodeChallenge        string // empty for implicit flow
	CodeChallengeMethod  string // empty for implicit flow
	UserID               *uuid.UUID
	InviteToken          string
	Referrer             string
	OAuthClientStateID   *uuid.UUID
	LinkingTargetID      *uuid.UUID
	EmailOptional        bool
}

FlowStateParams contains all parameters for creating a flow state

type FlowType

type FlowType int
const (
	PKCEFlow FlowType = iota
	ImplicitFlow
)

func (FlowType) String

func (flowType FlowType) String() string

type GrantParams

type GrantParams struct {
	FactorID *uuid.UUID

	SessionNotAfter *time.Time
	SessionTag      *string

	OAuthClientID *uuid.UUID
	Scopes        *string

	UserAgent string
	IP        string
}

GrantParams is used to pass session-specific parameters when issuing a new refresh token to authenticated users.

func (*GrantParams) FillGrantParams

func (g *GrantParams) FillGrantParams(r *http.Request)

type Identity

type Identity struct {
	// returned as identity_id in JSON for backward compatibility with the interface exposed by the client library
	// see https://github.com/supabase/gotrue-js/blob/c9296bbc27a2f036af55c1f33fca5930704bd021/src/lib/types.ts#L230-L240
	ID uuid.UUID `json:"identity_id" db:"id"`
	// returned as id in JSON for backward compatibility with the interface exposed by the client library
	// see https://github.com/supabase/gotrue-js/blob/c9296bbc27a2f036af55c1f33fca5930704bd021/src/lib/types.ts#L230-L240
	ProviderID   string             `json:"id" db:"provider_id"`
	UserID       uuid.UUID          `json:"user_id" db:"user_id"`
	IdentityData JSONMap            `json:"identity_data,omitempty" db:"identity_data"`
	Provider     string             `json:"provider" db:"provider"`
	LastSignInAt *time.Time         `json:"last_sign_in_at,omitempty" db:"last_sign_in_at"`
	CreatedAt    time.Time          `json:"created_at" db:"created_at"`
	UpdatedAt    time.Time          `json:"updated_at" db:"updated_at"`
	Email        storage.NullString `json:"email,omitempty" db:"email" rw:"r"`
}

func FindIdentitiesByUserID

func FindIdentitiesByUserID(tx *storage.Connection, userID uuid.UUID) ([]*Identity, error)

FindIdentitiesByUserID returns all identities associated to a user ID.

func FindIdentityByIdAndProvider

func FindIdentityByIdAndProvider(tx *storage.Connection, providerId, provider string) (*Identity, error)

FindIdentityById searches for an identity with the matching id and provider given.

func NewIdentity

func NewIdentity(user *User, provider string, identityData map[string]interface{}) (*Identity, error)

NewIdentity returns an identity associated to the user's id.

func (*Identity) BeforeCreate

func (i *Identity) BeforeCreate(tx *pop.Connection) error

func (*Identity) BeforeUpdate

func (i *Identity) BeforeUpdate(tx *pop.Connection) error

func (*Identity) GetEmail

func (i *Identity) GetEmail() string

GetEmail returns the user's email as a string

func (*Identity) IsForSSOProvider

func (i *Identity) IsForSSOProvider() bool

func (Identity) TableName

func (Identity) TableName() string

func (*Identity) UpdateIdentityData

func (i *Identity) UpdateIdentityData(tx *storage.Connection, updates map[string]interface{}) error

UpdateIdentityData sets all identity_data from a map of updates, ensuring that it doesn't override attributes that are not in the provided map.

type IdentityNotFoundError

type IdentityNotFoundError struct{}

IdentityNotFoundError represents when an identity is not found.

func (IdentityNotFoundError) Error

func (e IdentityNotFoundError) Error() string

func (IdentityNotFoundError) Is

func (e IdentityNotFoundError) Is(target error) bool

type InvalidRedirectURIError

type InvalidRedirectURIError struct {
	URI string
}

func (InvalidRedirectURIError) Error

func (e InvalidRedirectURIError) Error() string

type JSONMap

type JSONMap map[string]interface{}

func (JSONMap) Scan

func (j JSONMap) Scan(src interface{}) error

func (JSONMap) Value

func (j JSONMap) Value() (driver.Value, error)

type LastWebAuthnChallengeData

type LastWebAuthnChallengeData struct {
	Challenge          Challenge       `json:"challenge"`
	Type               string          `json:"type"`
	CredentialResponse json.RawMessage `json:"credential_response"`
}

func (*LastWebAuthnChallengeData) Scan

func (lwcd *LastWebAuthnChallengeData) Scan(value interface{}) error

func (*LastWebAuthnChallengeData) Value

func (lwcd *LastWebAuthnChallengeData) Value() (driver.Value, error)

type MFAWebAuthnCredential

type MFAWebAuthnCredential struct {
	webauthn.Credential
}

func (*MFAWebAuthnCredential) Scan

func (wc *MFAWebAuthnCredential) Scan(value interface{}) error

func (*MFAWebAuthnCredential) Value

func (wc *MFAWebAuthnCredential) Value() (driver.Value, error)

type NewOAuthServerAuthorizationParams

type NewOAuthServerAuthorizationParams struct {
	ClientID            uuid.UUID
	RedirectURI         string
	Scope               string
	State               string
	Resource            string
	CodeChallenge       string
	CodeChallengeMethod string
	TTL                 time.Duration
	Nonce               string
}

NewOAuthServerAuthorizationParams contains parameters for creating a new OAuth server authorization

type OAuthClientState

type OAuthClientState struct {
	ID           uuid.UUID `json:"id" db:"id"`
	ProviderType string    `json:"provider_type" db:"provider_type"`
	CodeVerifier *string   `json:"code_verifier,omitempty" db:"code_verifier"`
	CreatedAt    time.Time `json:"created_at" db:"created_at"`
}

func FindAndDeleteOAuthClientStateByID

func FindAndDeleteOAuthClientStateByID(tx *storage.Connection, id uuid.UUID) (*OAuthClientState, error)

func NewOAuthClientState

func NewOAuthClientState(providerType string, codeVerifier *string) *OAuthClientState

func (*OAuthClientState) IsExpired

func (s *OAuthClientState) IsExpired() bool

func (OAuthClientState) TableName

func (OAuthClientState) TableName() string

type OAuthClientStateNotFoundError

type OAuthClientStateNotFoundError struct{}

func (OAuthClientStateNotFoundError) Error

func (OAuthClientStateNotFoundError) Is

type OAuthServerAuthorization

type OAuthServerAuthorization struct {
	ID                  uuid.UUID                      `json:"-" db:"id"`
	AuthorizationID     string                         `json:"authorization_id" db:"authorization_id"`
	ClientID            uuid.UUID                      `json:"-" db:"client_id"`
	UserID              *uuid.UUID                     `json:"user_id" db:"user_id"`
	RedirectURI         string                         `json:"redirect_uri" db:"redirect_uri"`
	Scope               string                         `json:"scope" db:"scope"`
	State               *string                        `json:"state,omitempty" db:"state"`
	Resource            *string                        `json:"resource,omitempty" db:"resource"`
	CodeChallenge       *string                        `json:"code_challenge,omitempty" db:"code_challenge"`
	CodeChallengeMethod *string                        `json:"code_challenge_method,omitempty" db:"code_challenge_method"`
	Nonce               *string                        `json:"nonce,omitempty" db:"nonce"` // OIDC nonce parameter
	ResponseType        OAuthServerResponseType        `json:"response_type" db:"response_type"`
	Status              OAuthServerAuthorizationStatus `json:"status" db:"status"`
	AuthorizationCode   *string                        `json:"-" db:"authorization_code"`
	CreatedAt           time.Time                      `json:"created_at" db:"created_at"`
	ExpiresAt           time.Time                      `json:"expires_at" db:"expires_at"`
	ApprovedAt          *time.Time                     `json:"approved_at" db:"approved_at"`

	// Relations with OAuth clients
	Client *OAuthServerClient `json:"client,omitempty" db:"-"`
}

OAuthServerAuthorization represents an OAuth 2.1 server authorization request

func FindOAuthServerAuthorizationByCode

func FindOAuthServerAuthorizationByCode(tx *storage.Connection, code string) (*OAuthServerAuthorization, error)

FindOAuthServerAuthorizationByCode finds an OAuth authorization by authorization code

func FindOAuthServerAuthorizationByID

func FindOAuthServerAuthorizationByID(tx *storage.Connection, authorizationID string) (*OAuthServerAuthorization, error)

FindOAuthServerAuthorizationByID finds an OAuth authorization by authorization_id

func NewOAuthServerAuthorization

func NewOAuthServerAuthorization(params NewOAuthServerAuthorizationParams) *OAuthServerAuthorization

NewOAuthServerAuthorization creates a new OAuth server authorization request without user (for initial flow)

func (*OAuthServerAuthorization) Approve

func (auth *OAuthServerAuthorization) Approve(tx *storage.Connection) error

Approve approves the authorization request and generates an authorization code

func (*OAuthServerAuthorization) Deny

Deny denies the authorization request

func (*OAuthServerAuthorization) GenerateAuthorizationCode

func (auth *OAuthServerAuthorization) GenerateAuthorizationCode() string

GenerateAuthorizationCode generates a new authorization code if not already set

func (*OAuthServerAuthorization) GetScopeList

func (auth *OAuthServerAuthorization) GetScopeList() []string

GetScopeList returns the scopes as a slice

func (*OAuthServerAuthorization) IsExpired

func (auth *OAuthServerAuthorization) IsExpired() bool

IsExpired checks if the authorization request has expired

func (*OAuthServerAuthorization) MarkExpired

func (auth *OAuthServerAuthorization) MarkExpired(tx *storage.Connection) error

MarkExpired marks the authorization request as expired

func (*OAuthServerAuthorization) SetUser

func (auth *OAuthServerAuthorization) SetUser(tx *storage.Connection, userID uuid.UUID) error

SetUser sets the user ID for the authorization request (after login)

func (OAuthServerAuthorization) TableName

func (OAuthServerAuthorization) TableName() string

TableName returns the table name for the OAuthServerAuthorization model

func (*OAuthServerAuthorization) Validate

func (auth *OAuthServerAuthorization) Validate() error

Validate performs basic validation on the OAuth authorization

func (*OAuthServerAuthorization) VerifyPKCE

func (auth *OAuthServerAuthorization) VerifyPKCE(codeVerifier string) error

VerifyPKCE verifies the PKCE code verifier against the stored challenge

type OAuthServerAuthorizationNotFoundError

type OAuthServerAuthorizationNotFoundError struct{}

func (OAuthServerAuthorizationNotFoundError) Error

func (OAuthServerAuthorizationNotFoundError) Is

type OAuthServerAuthorizationStatus

type OAuthServerAuthorizationStatus string

OAuthServerAuthorizationStatus represents the status of an OAuth server authorization request

const (
	OAuthServerAuthorizationPending  OAuthServerAuthorizationStatus = "pending"
	OAuthServerAuthorizationApproved OAuthServerAuthorizationStatus = "approved"
	OAuthServerAuthorizationDenied   OAuthServerAuthorizationStatus = "denied"
	OAuthServerAuthorizationExpired  OAuthServerAuthorizationStatus = "expired"
)

func (OAuthServerAuthorizationStatus) String

type OAuthServerClient

type OAuthServerClient struct {
	ID                      uuid.UUID `json:"client_id" db:"id"`
	ClientSecretHash        string    `json:"-" db:"client_secret_hash"`
	RegistrationType        string    `json:"registration_type" db:"registration_type"`
	ClientType              string    `json:"client_type" db:"client_type"`
	TokenEndpointAuthMethod string    `json:"token_endpoint_auth_method" db:"token_endpoint_auth_method"`

	RedirectURIs string     `json:"-" db:"redirect_uris"`
	GrantTypes   string     `json:"grant_types" db:"grant_types"`
	ClientName   *string    `json:"client_name,omitempty" db:"client_name"`
	ClientURI    *string    `json:"client_uri,omitempty" db:"client_uri"`
	LogoURI      *string    `json:"logo_uri,omitempty" db:"logo_uri"`
	CreatedAt    time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at" db:"updated_at"`
	DeletedAt    *time.Time `json:"deleted_at,omitempty" db:"deleted_at"`
}

OAuthServerClient represents an OAuth client application registered with this OAuth server

func FindOAuthServerClientByID

func FindOAuthServerClientByID(tx *storage.Connection, id uuid.UUID) (*OAuthServerClient, error)

FindOAuthServerClientByID finds an OAuth client by ID

func (*OAuthServerClient) BeforeSave

func (c *OAuthServerClient) BeforeSave(tx *pop.Connection) error

BeforeSave is invoked before the OAuth client is saved to the database

func (*OAuthServerClient) GetGrantTypes

func (c *OAuthServerClient) GetGrantTypes() []string

GetGrantTypes returns the grant types as a slice

func (*OAuthServerClient) GetRedirectURIs

func (c *OAuthServerClient) GetRedirectURIs() []string

GetRedirectURIs returns the redirect URIs as a slice

func (*OAuthServerClient) GetTokenEndpointAuthMethod

func (c *OAuthServerClient) GetTokenEndpointAuthMethod() string

GetTokenEndpointAuthMethod returns the token endpoint auth method

func (*OAuthServerClient) IsConfidential

func (c *OAuthServerClient) IsConfidential() bool

IsConfidential returns true if the client is a confidential client

func (*OAuthServerClient) IsGrantTypeAllowed

func (c *OAuthServerClient) IsGrantTypeAllowed(grantType string) bool

IsGrantTypeAllowed returns true if the client is allowed to use the specified grant type

func (*OAuthServerClient) IsPublic

func (c *OAuthServerClient) IsPublic() bool

IsPublic returns true if the client is a public client

func (*OAuthServerClient) SetGrantTypes

func (c *OAuthServerClient) SetGrantTypes(types []string)

SetGrantTypes sets the grant types from a slice

func (*OAuthServerClient) SetRedirectURIs

func (c *OAuthServerClient) SetRedirectURIs(uris []string)

SetRedirectURIs sets the redirect URIs from a slice

func (OAuthServerClient) TableName

func (OAuthServerClient) TableName() string

TableName returns the table name for the OAuthServerClient model

func (*OAuthServerClient) Validate

func (c *OAuthServerClient) Validate() error

Validate performs basic validation on the OAuth client

type OAuthServerClientNotFoundError

type OAuthServerClientNotFoundError struct{}

Error types for OAuth client operations

func (OAuthServerClientNotFoundError) Error

func (OAuthServerClientNotFoundError) Is

type OAuthServerConsent

type OAuthServerConsent struct {
	ID        uuid.UUID  `json:"id" db:"id"`
	UserID    uuid.UUID  `json:"user_id" db:"user_id"`
	ClientID  uuid.UUID  `json:"-" db:"client_id"`
	Scopes    string     `json:"scopes" db:"scopes"`
	GrantedAt time.Time  `json:"granted_at" db:"granted_at"`
	RevokedAt *time.Time `json:"revoked_at" db:"revoked_at"`
}

OAuthServerConsent represents user consent for an OAuth server client's access to specific scopes

func FindActiveOAuthServerConsentByUserAndClient

func FindActiveOAuthServerConsentByUserAndClient(tx *storage.Connection, userID uuid.UUID, clientID uuid.UUID) (*OAuthServerConsent, error)

FindActiveOAuthServerConsentByUserAndClient finds an active (non-revoked) OAuth consent

func FindOAuthServerConsentByUserAndClient

func FindOAuthServerConsentByUserAndClient(tx *storage.Connection, userID uuid.UUID, clientID uuid.UUID) (*OAuthServerConsent, error)

FindOAuthServerConsentByUserAndClient finds an OAuth consent by user and client

func FindOAuthServerConsentsByUser

func FindOAuthServerConsentsByUser(tx *storage.Connection, userID uuid.UUID, includeRevoked bool) ([]*OAuthServerConsent, error)

FindOAuthServerConsentsByUser finds all OAuth consents for a user

func NewOAuthServerConsent

func NewOAuthServerConsent(userID uuid.UUID, clientID uuid.UUID, scopes []string) *OAuthServerConsent

NewOAuthConsent creates a new OAuth consent record

func (*OAuthServerConsent) GetScopeList

func (consent *OAuthServerConsent) GetScopeList() []string

GetScopeList returns the granted scopes as a slice

func (*OAuthServerConsent) HasAllScopes

func (consent *OAuthServerConsent) HasAllScopes(requestedScopes []string) bool

HasAllScopes checks if the consent includes all of the requested scopes

func (*OAuthServerConsent) HasScope

func (consent *OAuthServerConsent) HasScope(scope string) bool

HasScope checks if the consent includes a specific scope

func (*OAuthServerConsent) IsRevoked

func (consent *OAuthServerConsent) IsRevoked() bool

IsRevoked checks if the consent has been revoked

func (*OAuthServerConsent) Revoke

func (consent *OAuthServerConsent) Revoke(tx *storage.Connection) error

Revoke revokes the consent

func (OAuthServerConsent) TableName

func (OAuthServerConsent) TableName() string

TableName returns the table name for the OAuthConsent model

func (*OAuthServerConsent) UpdateScopes

func (consent *OAuthServerConsent) UpdateScopes(tx *storage.Connection, scopes []string) error

UpdateScopes updates the granted scopes for this consent

func (*OAuthServerConsent) Validate

func (consent *OAuthServerConsent) Validate() error

Validate performs basic validation on the OAuth consent

type OAuthServerResponseType

type OAuthServerResponseType string

OAuthServerResponseType represents the OAuth server response type

const (
	OAuthServerResponseTypeCode OAuthServerResponseType = "code"
)

func (OAuthServerResponseType) String

func (rt OAuthServerResponseType) String() string

type OIDCDiscovery

type OIDCDiscovery struct {
	Issuer                 string   `json:"issuer"`
	AuthorizationEndpoint  string   `json:"authorization_endpoint"`
	TokenEndpoint          string   `json:"token_endpoint"`
	UserinfoEndpoint       string   `json:"userinfo_endpoint,omitempty"`
	JwksURI                string   `json:"jwks_uri"`
	ScopesSupported        []string `json:"scopes_supported,omitempty"`
	ResponseTypesSupported []string `json:"response_types_supported,omitempty"`
	GrantTypesSupported    []string `json:"grant_types_supported,omitempty"`
	SubjectTypesSupported  []string `json:"subject_types_supported,omitempty"`
}

OIDCDiscovery represents cached OIDC discovery document

func (*OIDCDiscovery) Scan

func (d *OIDCDiscovery) Scan(src interface{}) error

func (*OIDCDiscovery) Value

func (d *OIDCDiscovery) Value() (driver.Value, error)

type OneTimeToken

type OneTimeToken struct {
	ID uuid.UUID `json:"id" db:"id"`

	UserID    uuid.UUID        `json:"user_id" db:"user_id"`
	TokenType OneTimeTokenType `json:"token_type" db:"token_type"`

	TokenHash string `json:"token_hash" db:"token_hash"`
	RelatesTo string `json:"relates_to" db:"relates_to"`

	CreatedAt time.Time `json:"created_at" db:"created_at"`
	UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}

func FindOneTimeToken

func FindOneTimeToken(tx *storage.Connection, tokenHash string, tokenTypes ...OneTimeTokenType) (*OneTimeToken, error)

func (OneTimeToken) TableName

func (OneTimeToken) TableName() string

type OneTimeTokenNotFoundError

type OneTimeTokenNotFoundError struct {
}

func (OneTimeTokenNotFoundError) Error

func (OneTimeTokenNotFoundError) Is

func (e OneTimeTokenNotFoundError) Is(target error) bool

type OneTimeTokenType

type OneTimeTokenType int
const (
	ConfirmationToken OneTimeTokenType = iota
	ReauthenticationToken
	RecoveryToken
	EmailChangeTokenNew
	EmailChangeTokenCurrent
	PhoneChangeToken
)

func ParseOneTimeTokenType

func ParseOneTimeTokenType(s string) (OneTimeTokenType, error)

func (*OneTimeTokenType) Scan

func (t *OneTimeTokenType) Scan(src interface{}) error

func (OneTimeTokenType) String

func (t OneTimeTokenType) String() string

func (OneTimeTokenType) Value

func (t OneTimeTokenType) Value() (driver.Value, error)

type Pagination

type Pagination struct {
	Page    uint64
	PerPage uint64
	Count   uint64
}

func (*Pagination) Offset

func (p *Pagination) Offset() uint64

type ProviderType

type ProviderType string

ProviderType represents the type of OAuth provider

const (
	ProviderTypeOAuth2 ProviderType = "oauth2"
	ProviderTypeOIDC   ProviderType = "oidc"
)

type RefreshToken

type RefreshToken struct {
	ID int64 `db:"id"`

	Token string `db:"token"`

	UserID uuid.UUID `db:"user_id"`

	Parent    storage.NullString `db:"parent"`
	SessionId *uuid.UUID         `db:"session_id"`

	Revoked   bool      `db:"revoked"`
	CreatedAt time.Time `db:"created_at"`
	UpdatedAt time.Time `db:"updated_at"`

	DONTUSEINSTANCEID uuid.UUID `json:"-" db:"instance_id"`
}

RefreshToken is the database model for refresh tokens.

func FindTokenBySessionID

func FindTokenBySessionID(tx *storage.Connection, sessionId *uuid.UUID) (*RefreshToken, error)

func GrantAuthenticatedUser

func GrantAuthenticatedUser(tx *storage.Connection, user *User, params GrantParams) (*RefreshToken, error)

GrantAuthenticatedUser creates a refresh token for the provided user.

func GrantRefreshTokenSwap

func GrantRefreshTokenSwap(config conf.AuditLogConfiguration, r *http.Request, tx *storage.Connection, user *User, token *RefreshToken) (*RefreshToken, error)

GrantRefreshTokenSwap swaps a refresh token for a new one, revoking the provided token.

func (RefreshToken) TableName

func (RefreshToken) TableName() string

type RefreshTokenNotFoundError

type RefreshTokenNotFoundError struct{}

RefreshTokenNotFoundError represents when a refresh token is not found.

func (RefreshTokenNotFoundError) Error

func (RefreshTokenNotFoundError) Is

func (e RefreshTokenNotFoundError) Is(target error) bool

type SAMLAttribute

type SAMLAttribute struct {
	Name    string      `json:"name,omitempty"`
	Names   []string    `json:"names,omitempty"`
	Default interface{} `json:"default,omitempty"`
	Array   bool        `json:"array,omitempty"`
}

type SAMLAttributeMapping

type SAMLAttributeMapping struct {
	Keys map[string]SAMLAttribute `json:"keys,omitempty"`
}

func (*SAMLAttributeMapping) Equal

func (*SAMLAttributeMapping) Scan

func (m *SAMLAttributeMapping) Scan(src interface{}) error

func (SAMLAttributeMapping) Value

func (m SAMLAttributeMapping) Value() (driver.Value, error)

type SAMLProvider

type SAMLProvider struct {
	ID uuid.UUID `db:"id" json:"-"`

	SSOProvider   *SSOProvider `belongs_to:"sso_providers" json:"-"`
	SSOProviderID uuid.UUID    `db:"sso_provider_id" json:"-"`

	EntityID    string  `db:"entity_id" json:"entity_id"`
	MetadataXML string  `db:"metadata_xml" json:"metadata_xml,omitempty"`
	MetadataURL *string `db:"metadata_url" json:"metadata_url,omitempty"`

	AttributeMapping SAMLAttributeMapping `db:"attribute_mapping" json:"attribute_mapping,omitempty"`

	NameIDFormat *string `db:"name_id_format" json:"name_id_format,omitempty"`

	CreatedAt time.Time `db:"created_at" json:"-"`
	UpdatedAt time.Time `db:"updated_at" json:"-"`
}

func (SAMLProvider) EntityDescriptor

func (p SAMLProvider) EntityDescriptor() (*saml.EntityDescriptor, error)

func (SAMLProvider) TableName

func (p SAMLProvider) TableName() string

type SAMLRelayState

type SAMLRelayState struct {
	ID uuid.UUID `db:"id"`

	SSOProviderID uuid.UUID `db:"sso_provider_id"`

	RequestID string  `db:"request_id"`
	ForEmail  *string `db:"for_email"`

	RedirectTo string `db:"redirect_to"`

	CreatedAt   time.Time  `db:"created_at" json:"-"`
	UpdatedAt   time.Time  `db:"updated_at" json:"-"`
	FlowStateID *uuid.UUID `db:"flow_state_id" json:"flow_state_id,omitempty"`
	FlowState   *FlowState `db:"-" json:"flow_state,omitempty" belongs_to:"flow_state"`
}

func FindSAMLRelayStateByID

func FindSAMLRelayStateByID(tx *storage.Connection, id uuid.UUID) (*SAMLRelayState, error)

func (SAMLRelayState) TableName

func (s SAMLRelayState) TableName() string

type SAMLRelayStateNotFoundError

type SAMLRelayStateNotFoundError struct{}

SAMLRelayStateNotFoundError represents an error when a SAML relay state can't be found.

func (SAMLRelayStateNotFoundError) Error

func (SAMLRelayStateNotFoundError) Is

func (e SAMLRelayStateNotFoundError) Is(target error) bool

type SSODomain

type SSODomain struct {
	ID uuid.UUID `db:"id" json:"-"`

	SSOProvider   *SSOProvider `belongs_to:"sso_providers" json:"-"`
	SSOProviderID uuid.UUID    `db:"sso_provider_id" json:"-"`

	Domain string `db:"domain" json:"domain"`

	CreatedAt time.Time `db:"created_at" json:"-"`
	UpdatedAt time.Time `db:"updated_at" json:"-"`
}

func (SSODomain) TableName

func (d SSODomain) TableName() string

type SSOProvider

type SSOProvider struct {
	ID           uuid.UUID    `db:"id" json:"id"`
	ResourceID   *string      `db:"resource_id" json:"resource_id,omitempty"`
	Disabled     *bool        `db:"disabled" json:"disabled"`
	SAMLProvider SAMLProvider `has_one:"saml_providers" fk_id:"sso_provider_id" json:"saml,omitempty"`
	SSODomains   []SSODomain  `has_many:"sso_domains" fk_id:"sso_provider_id" json:"domains"`

	CreatedAt time.Time `db:"created_at" json:"created_at"`
	UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}

func FindAllSSOProviders

func FindAllSSOProviders(tx *storage.Connection) ([]SSOProvider, error)

func FindAllSSOProvidersByFilter

func FindAllSSOProvidersByFilter(
	tx *storage.Connection,
	queryValues url.Values,
) ([]*SSOProvider, error)

FindAllSSOProvidersByFilter finds SSO Providers with the matching filter.

func FindSAMLProviderByEntityID

func FindSAMLProviderByEntityID(tx *storage.Connection, entityId string) (*SSOProvider, error)

func FindSSOProviderByDomain

func FindSSOProviderByDomain(tx *storage.Connection, domain string) (*SSOProvider, error)

func FindSSOProviderByID

func FindSSOProviderByID(tx *storage.Connection, id uuid.UUID) (*SSOProvider, error)

func FindSSOProviderByResourceID

func FindSSOProviderByResourceID(tx *storage.Connection, id string) (*SSOProvider, error)

func FindSSOProviderForEmailAddress

func FindSSOProviderForEmailAddress(tx *storage.Connection, emailAddress string) (*SSOProvider, error)

func (SSOProvider) IsEnabled

func (p SSOProvider) IsEnabled() bool

func (SSOProvider) TableName

func (p SSOProvider) TableName() string

func (SSOProvider) Type

func (p SSOProvider) Type() string

type SSOProviderNotFoundError

type SSOProviderNotFoundError struct{}

SSOProviderNotFoundError represents an error when a SSO Provider can't be found.

func (SSOProviderNotFoundError) Error

func (e SSOProviderNotFoundError) Error() string

func (SSOProviderNotFoundError) Is

func (e SSOProviderNotFoundError) Is(target error) bool

type Session

type Session struct {
	ID     uuid.UUID `json:"-" db:"id"`
	UserID uuid.UUID `json:"user_id" db:"user_id"`

	// NotAfter is overriden by timeboxed sessions.
	NotAfter *time.Time `json:"not_after,omitempty" db:"not_after"`

	CreatedAt time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt time.Time  `json:"updated_at" db:"updated_at"`
	FactorID  *uuid.UUID `json:"factor_id" db:"factor_id"`
	AMRClaims []AMRClaim `json:"amr,omitempty" has_many:"amr_claims"`
	AAL       *string    `json:"aal" db:"aal"`

	RefreshedAt *time.Time `json:"refreshed_at,omitempty" db:"refreshed_at"`
	UserAgent   *string    `json:"user_agent,omitempty" db:"user_agent"`
	IP          *string    `json:"ip,omitempty" db:"ip"`

	Tag           *string    `json:"tag" db:"tag"`
	OAuthClientID *uuid.UUID `json:"oauth_client_id" db:"oauth_client_id"`
	Scopes        *string    `json:"scopes,omitempty" db:"scopes"` // OAuth scopes granted for this session

	RefreshTokenHmacKey *string `json:"-" db:"refresh_token_hmac_key"`
	RefreshTokenCounter *int64  `json:"-" db:"refresh_token_counter"`
}

func FindAllSessionsForUser

func FindAllSessionsForUser(tx *storage.Connection, userId uuid.UUID, forUpdate bool) ([]*Session, error)

FindAllSessionsForUser finds all of the sessions for a user. If forUpdate is set, it will first lock on the user row which can be used to prevent issues with concurrency. If the lock is acquired, it will return a UserNotFoundError and the operation should be retried. If there are no sessions for the user, a nil result is returned without an error.

func FindSessionByID

func FindSessionByID(tx *storage.Connection, id uuid.UUID, forUpdate bool) (*Session, error)

FindSessionByID looks up a Session by the provided id. If forUpdate is set to true, then the SELECT statement used by the query has the form SELECT ... FOR UPDATE SKIP LOCKED. This means that a FOR UPDATE lock will only be acquired if there's no other lock. In case there is a lock, a IsNotFound(err) error will be retured.

func FindSessionByUserID

func FindSessionByUserID(tx *storage.Connection, userId uuid.UUID) (*Session, error)

func FindSessionsByFactorID

func FindSessionsByFactorID(tx *storage.Connection, factorID uuid.UUID) ([]*Session, error)

func NewSession

func NewSession(userID uuid.UUID, factorID *uuid.UUID) (*Session, error)

func (*Session) ApplyGrantParams

func (s *Session) ApplyGrantParams(params *GrantParams)

func (*Session) CalculateAALAndAMR

func (s *Session) CalculateAALAndAMR(user *User) (aal AuthenticatorAssuranceLevel, amr []AMREntry, err error)

func (*Session) CheckValidity

func (s *Session) CheckValidity(config SessionValidityConfig, now time.Time, refreshTokenTime *time.Time, userHighestPossibleAAL AuthenticatorAssuranceLevel) SessionValidityReason

func (*Session) DetermineTag

func (s *Session) DetermineTag(tags []string) string

func (*Session) FindCurrentlyActiveRefreshToken

func (s *Session) FindCurrentlyActiveRefreshToken(tx *storage.Connection) (*RefreshToken, error)

FindCurrentlyActiveRefreshToken returns the currently active refresh token in the session. This is the last created (ordered by the serial primary key) non-revoked refresh token for the session.

func (*Session) GetAAL

func (s *Session) GetAAL() string

func (*Session) GetRefreshTokenHmacKey

func (s *Session) GetRefreshTokenHmacKey(dbEncryption conf.DatabaseEncryptionConfiguration) ([]byte, bool, error)

func (*Session) GetScopeList

func (s *Session) GetScopeList() []string

GetScopeList returns the scopes as a slice

func (*Session) HasScope

func (s *Session) HasScope(scope string) bool

HasScope checks if the session has a specific scope

func (*Session) IsAAL2

func (s *Session) IsAAL2() bool

func (*Session) LastRefreshedAt

func (s *Session) LastRefreshedAt(refreshTokenTime *time.Time) time.Time

func (*Session) ReEncryptRefreshTokenHmacKey

func (s *Session) ReEncryptRefreshTokenHmacKey(tx *storage.Connection, dbEncryption conf.DatabaseEncryptionConfiguration) error

func (*Session) SetupRefreshTokenData

func (s *Session) SetupRefreshTokenData(dbEncryption conf.DatabaseEncryptionConfiguration) error

func (Session) TableName

func (Session) TableName() string

func (*Session) UpdateAALAndAssociatedFactor

func (s *Session) UpdateAALAndAssociatedFactor(tx *storage.Connection, aal AuthenticatorAssuranceLevel, factorID *uuid.UUID) error

func (*Session) UpdateOnlyRefreshInfo

func (s *Session) UpdateOnlyRefreshInfo(tx *storage.Connection) error

func (*Session) UpdateOnlyRefreshToken

func (s *Session) UpdateOnlyRefreshToken(tx *storage.Connection) error

func (*Session) UpdateRefreshTokenCounterAndHmacKey

func (s *Session) UpdateRefreshTokenCounterAndHmacKey(tx *storage.Connection) error

type SessionNotFoundError

type SessionNotFoundError struct{}

func (SessionNotFoundError) Error

func (e SessionNotFoundError) Error() string

func (SessionNotFoundError) Is

func (e SessionNotFoundError) Is(target error) bool

type SessionValidityConfig

type SessionValidityConfig struct {
	Timebox           *time.Duration
	InactivityTimeout *time.Duration
	AllowLowAAL       *time.Duration
}

type SessionValidityReason

type SessionValidityReason = int

type SortDirection

type SortDirection string
const Ascending SortDirection = "ASC"
const Descending SortDirection = "DESC"

type SortField

type SortField struct {
	Name string
	Dir  SortDirection
}

type SortParams

type SortParams struct {
	Fields []SortField
}

type User

type User struct {
	ID uuid.UUID `json:"id" db:"id"`

	Aud       string             `json:"aud" db:"aud"`
	Role      string             `json:"role" db:"role"`
	Email     storage.NullString `json:"email" db:"email"`
	IsSSOUser bool               `json:"-" db:"is_sso_user"`

	EncryptedPassword *string    `json:"-" db:"encrypted_password"`
	EmailConfirmedAt  *time.Time `json:"email_confirmed_at,omitempty" db:"email_confirmed_at"`
	InvitedAt         *time.Time `json:"invited_at,omitempty" db:"invited_at"`

	Phone            storage.NullString `json:"phone" db:"phone"`
	PhoneConfirmedAt *time.Time         `json:"phone_confirmed_at,omitempty" db:"phone_confirmed_at"`

	ConfirmationToken  string     `json:"-" db:"confirmation_token"`
	ConfirmationSentAt *time.Time `json:"confirmation_sent_at,omitempty" db:"confirmation_sent_at"`

	// For backward compatibility only. Use EmailConfirmedAt or PhoneConfirmedAt instead.
	ConfirmedAt *time.Time `json:"confirmed_at,omitempty" db:"confirmed_at" rw:"r"`

	RecoveryToken  string     `json:"-" db:"recovery_token"`
	RecoverySentAt *time.Time `json:"recovery_sent_at,omitempty" db:"recovery_sent_at"`

	EmailChangeTokenCurrent  string     `json:"-" db:"email_change_token_current"`
	EmailChangeTokenNew      string     `json:"-" db:"email_change_token_new"`
	EmailChange              string     `json:"new_email,omitempty" db:"email_change"`
	EmailChangeSentAt        *time.Time `json:"email_change_sent_at,omitempty" db:"email_change_sent_at"`
	EmailChangeConfirmStatus int        `json:"-" db:"email_change_confirm_status"`

	PhoneChangeToken  string     `json:"-" db:"phone_change_token"`
	PhoneChange       string     `json:"new_phone,omitempty" db:"phone_change"`
	PhoneChangeSentAt *time.Time `json:"phone_change_sent_at,omitempty" db:"phone_change_sent_at"`

	ReauthenticationToken  string     `json:"-" db:"reauthentication_token"`
	ReauthenticationSentAt *time.Time `json:"reauthentication_sent_at,omitempty" db:"reauthentication_sent_at"`

	LastSignInAt *time.Time `json:"last_sign_in_at,omitempty" db:"last_sign_in_at"`

	AppMetaData  JSONMap `json:"app_metadata" db:"raw_app_meta_data"`
	UserMetaData JSONMap `json:"user_metadata" db:"raw_user_meta_data"`

	Factors    []Factor   `json:"factors,omitempty" has_many:"factors"`
	Identities []Identity `json:"identities" has_many:"identities"`

	CreatedAt   time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at" db:"updated_at"`
	BannedUntil *time.Time `json:"banned_until,omitempty" db:"banned_until"`
	DeletedAt   *time.Time `json:"deleted_at,omitempty" db:"deleted_at"`
	IsAnonymous bool       `json:"is_anonymous" db:"is_anonymous"`

	DONTUSEINSTANCEID uuid.UUID `json:"-" db:"instance_id"`
}

User respresents a registered user with email/password authentication

func FindUserByConfirmationOrRecoveryToken

func FindUserByConfirmationOrRecoveryToken(tx *storage.Connection, token string) (*User, error)

FindUserByConfirmationToken finds users with the matching confirmation token.

func FindUserByConfirmationToken

func FindUserByConfirmationToken(tx *storage.Connection, token string) (*User, error)

FindUserByConfirmationToken finds users with the matching confirmation token.

func FindUserByEmailAndAudience

func FindUserByEmailAndAudience(tx *storage.Connection, email, aud string) (*User, error)

FindUserByEmailAndAudience finds a user with the matching email and audience.

func FindUserByEmailChangeCurrentAndAudience

func FindUserByEmailChangeCurrentAndAudience(tx *storage.Connection, email, token, aud string) (*User, error)

FindUserByEmailChangeCurrentAndAudience finds a user with the matching email change and audience.

func FindUserByEmailChangeNewAndAudience

func FindUserByEmailChangeNewAndAudience(tx *storage.Connection, email, token, aud string) (*User, error)

FindUserByEmailChangeNewAndAudience finds a user with the matching email change and audience.

func FindUserByEmailChangeToken

func FindUserByEmailChangeToken(tx *storage.Connection, token string) (*User, error)

FindUserByEmailChangeToken finds a user with the matching email change token.

func FindUserByID

func FindUserByID(tx *storage.Connection, id uuid.UUID) (*User, error)

FindUserByID finds a user matching the provided ID.

func FindUserByPhoneAndAudience

func FindUserByPhoneAndAudience(tx *storage.Connection, phone, aud string) (*User, error)

FindUserByPhoneAndAudience finds a user with the matching email and audience.

func FindUserByPhoneChangeAndAudience

func FindUserByPhoneChangeAndAudience(tx *storage.Connection, phone, aud string) (*User, error)

FindUserByPhoneChangeAndAudience finds a user with the matching phone change and audience.

func FindUserByRecoveryToken

func FindUserByRecoveryToken(tx *storage.Connection, token string) (*User, error)

FindUserByRecoveryToken finds a user with the matching recovery token.

func FindUserForEmailChange

func FindUserForEmailChange(tx *storage.Connection, email, token, aud string, secureEmailChangeEnabled bool) (*User, error)

FindUserForEmailChange finds a user requesting for an email change

func FindUsersInAudience

func FindUsersInAudience(tx *storage.Connection, aud string, pageParams *Pagination, sortParams *SortParams, filter string) ([]*User, error)

FindUsersInAudience finds users with the matching audience.

func IsDuplicatedEmail

func IsDuplicatedEmail(tx *storage.Connection, email, aud string, currentUser *User, ownDomainProviders []string) (*User, error)

IsDuplicatedEmail returns whether a user exists with a matching email and audience importantly in the *default* identity linking domain (meaning SSO accounts and similar are not considered). If a currentUser is provided, we will need to filter out any identities that belong to the current user.

func NewUser

func NewUser(phone, email, password, aud string, userData map[string]interface{}) (*User, error)

NewUser initializes a new user from an email, password and user data.

func NewUserWithPasswordHash

func NewUserWithPasswordHash(phone, email, passwordHash, aud string, userData map[string]interface{}) (*User, error)

func (*User) Authenticate

func (u *User) Authenticate(ctx context.Context, tx *storage.Connection, password string, decryptionKeys map[string]string, encrypt bool, encryptionKeyID string) (bool, bool, error)

Authenticate a user from a password

func (*User) Ban

func (u *User) Ban(tx *storage.Connection, duration time.Duration) error

Ban a user for a given duration.

func (*User) BeforeSave

func (u *User) BeforeSave(tx *pop.Connection) error

BeforeSave is invoked before the user is saved to the database

func (*User) Confirm

func (u *User) Confirm(tx *storage.Connection) error

Confirm resets the confimation token and sets the confirm timestamp

func (*User) ConfirmEmailChange

func (u *User) ConfirmEmailChange(tx *storage.Connection, status int) error

ConfirmEmailChange confirm the change of email for a user

func (*User) ConfirmPhone

func (u *User) ConfirmPhone(tx *storage.Connection) error

ConfirmPhone resets the confimation token and sets the confirm timestamp

func (*User) ConfirmPhoneChange

func (u *User) ConfirmPhoneChange(tx *storage.Connection) error

ConfirmPhoneChange confirms the change of phone for a user

func (*User) ConfirmReauthentication

func (u *User) ConfirmReauthentication(tx *storage.Connection) error

ConfirmReauthentication resets the reauthentication token

func (*User) FindOwnedFactorByID

func (u *User) FindOwnedFactorByID(tx *storage.Connection, factorID uuid.UUID) (*Factor, error)

func (*User) GetEmail

func (u *User) GetEmail() string

GetEmail returns the user's email as a string

func (*User) GetPhone

func (u *User) GetPhone() string

GetPhone returns the user's phone number as a string

func (*User) HasBeenInvited

func (u *User) HasBeenInvited() bool

HasBeenInvited checks if user has been invited

func (*User) HasMFAEnabled

func (u *User) HasMFAEnabled() bool

func (*User) HasPassword

func (u *User) HasPassword() bool

func (*User) HasRole

func (u *User) HasRole(roleName string) bool

HasRole returns true when the users role is set to roleName

func (*User) HighestPossibleAAL

func (u *User) HighestPossibleAAL() AuthenticatorAssuranceLevel

HighestPossibleAAL returns the AAL level that this user can obtain. Derived from the number of verified MFA factors associated with the user object.

func (*User) IsBanned

func (u *User) IsBanned() bool

IsBanned checks if a user is banned or not

func (*User) IsConfirmed

func (u *User) IsConfirmed() bool

IsConfirmed checks if a user has already been registered and confirmed.

func (*User) IsPhoneConfirmed

func (u *User) IsPhoneConfirmed() bool

IsPhoneConfirmed checks if a user's phone has already been registered and confirmed.

func (*User) Recover

func (u *User) Recover(tx *storage.Connection) error

Recover resets the recovery token

func (*User) RemoveUnconfirmedIdentities

func (u *User) RemoveUnconfirmedIdentities(tx *storage.Connection, identity *Identity) error

RemoveUnconfirmedIdentities removes potentially malicious unconfirmed identities from a user (if any)

func (*User) SetEmail

func (u *User) SetEmail(tx *storage.Connection, email string) error

SetEmail sets the user's email

func (*User) SetPassword

func (u *User) SetPassword(ctx context.Context, password string, encrypt bool, encryptionKeyID, encryptionKey string) error

func (*User) SetPhone

func (u *User) SetPhone(tx *storage.Connection, phone string) error

SetPhone sets the user's phone

func (*User) SetRole

func (u *User) SetRole(tx *storage.Connection, roleName string) error

SetRole sets the users Role to roleName

func (*User) SoftDeleteUser

func (u *User) SoftDeleteUser(tx *storage.Connection) error

SoftDeleteUser performs a soft deletion on the user by obfuscating and clearing certain fields

func (*User) SoftDeleteUserIdentities

func (u *User) SoftDeleteUserIdentities(tx *storage.Connection) error

SoftDeleteUserIdentities performs a soft deletion on all identities associated to a user

func (User) TableName

func (User) TableName() string

TableName overrides the table name used by pop

func (*User) UpdateAppMetaData

func (u *User) UpdateAppMetaData(tx *storage.Connection, updates map[string]interface{}) error

UpdateAppMetaData updates all app data from a map of updates

func (*User) UpdateAppMetaDataProviders

func (u *User) UpdateAppMetaDataProviders(tx *storage.Connection) error

UpdateAppMetaDataProviders updates the provider field in AppMetaData column

func (*User) UpdateBannedUntil

func (u *User) UpdateBannedUntil(tx *storage.Connection) error

func (*User) UpdateLastSignInAt

func (u *User) UpdateLastSignInAt(tx *storage.Connection) error

UpdateLastSignInAt update field last_sign_in_at for user according to specified field

func (*User) UpdatePassword

func (u *User) UpdatePassword(tx *storage.Connection, sessionID *uuid.UUID) error

UpdatePassword updates the user's password. Use SetPassword outside of a transaction first!

func (*User) UpdateUserEmailFromIdentities

func (u *User) UpdateUserEmailFromIdentities(tx *storage.Connection) error

UpdateUserEmail updates the user's email to one of the identity's email if the current email used doesn't match any of the identities email

func (*User) UpdateUserMetaData

func (u *User) UpdateUserMetaData(tx *storage.Connection, updates map[string]interface{}) error

UpdateUserMetaData sets all user data from a map of updates, ensuring that it doesn't override attributes that are not in the provided map.

func (*User) WebAuthnCredentials

func (user *User) WebAuthnCredentials() []webauthn.Credential

func (*User) WebAuthnDisplayName

func (user *User) WebAuthnDisplayName() string

func (*User) WebAuthnID

func (user *User) WebAuthnID() []byte

func (*User) WebAuthnName

func (user *User) WebAuthnName() string

type UserEmailUniqueConflictError

type UserEmailUniqueConflictError struct{}

func (UserEmailUniqueConflictError) Error

func (UserEmailUniqueConflictError) Is

type UserNotFoundError

type UserNotFoundError struct{}

UserNotFoundError represents when a user is not found.

func (UserNotFoundError) Error

func (e UserNotFoundError) Error() string

func (UserNotFoundError) Is

func (e UserNotFoundError) Is(target error) bool

type WebAuthnChallenge

type WebAuthnChallenge struct {
	ID            uuid.UUID            `json:"id" db:"id"`
	UserID        *uuid.UUID           `json:"user_id,omitempty" db:"user_id"`
	ChallengeType string               `json:"challenge_type" db:"challenge_type"`
	SessionData   *WebAuthnSessionData `json:"session_data" db:"session_data"`
	CreatedAt     time.Time            `json:"created_at" db:"created_at"`
	ExpiresAt     time.Time            `json:"expires_at" db:"expires_at"`
}

WebAuthnChallenge maps to the webauthn_challenges table.

func FindWebAuthnChallengeByID

func FindWebAuthnChallengeByID(conn *storage.Connection, id uuid.UUID) (*WebAuthnChallenge, error)

func NewWebAuthnChallenge

func NewWebAuthnChallenge(userID *uuid.UUID, challengeType string, sessionData *WebAuthnSessionData, expiresAt time.Time) *WebAuthnChallenge

func (*WebAuthnChallenge) Delete

func (c *WebAuthnChallenge) Delete(tx *storage.Connection) error

func (*WebAuthnChallenge) IsExpired

func (c *WebAuthnChallenge) IsExpired() bool

func (WebAuthnChallenge) TableName

func (WebAuthnChallenge) TableName() string

type WebAuthnChallengeNotFoundError

type WebAuthnChallengeNotFoundError struct{}

WebAuthnChallengeNotFoundError represents when a WebAuthn challenge can't be found.

func (WebAuthnChallengeNotFoundError) Error

func (WebAuthnChallengeNotFoundError) Is

type WebAuthnCredential

type WebAuthnCredential struct {
	ID              uuid.UUID          `json:"id" db:"id"`
	UserID          uuid.UUID          `json:"user_id" db:"user_id"`
	CredentialID    []byte             `json:"-" db:"credential_id"`
	PublicKey       []byte             `json:"-" db:"public_key"`
	AttestationType string             `json:"attestation_type" db:"attestation_type"`
	AAGUID          *uuid.UUID         `json:"aaguid,omitempty" db:"aaguid"`
	SignCount       uint32             `json:"sign_count" db:"sign_count"`
	Transports      WebAuthnTransports `json:"transports" db:"transports"`
	BackupEligible  bool               `json:"backup_eligible" db:"backup_eligible"`
	BackedUp        bool               `json:"backed_up" db:"backed_up"`
	FriendlyName    string             `json:"friendly_name" db:"friendly_name"`
	CreatedAt       time.Time          `json:"created_at" db:"created_at"`
	UpdatedAt       time.Time          `json:"updated_at" db:"updated_at"`
	LastUsedAt      *time.Time         `json:"last_used_at,omitempty" db:"last_used_at"`
}

WebAuthnCredential maps to the webauthn_credentials table.

func FindWebAuthnCredentialByCredentialID

func FindWebAuthnCredentialByCredentialID(conn *storage.Connection, credentialID []byte) (*WebAuthnCredential, error)

func FindWebAuthnCredentialByID

func FindWebAuthnCredentialByID(conn *storage.Connection, id uuid.UUID) (*WebAuthnCredential, error)

func FindWebAuthnCredentialsByUserID

func FindWebAuthnCredentialsByUserID(conn *storage.Connection, userID uuid.UUID) ([]*WebAuthnCredential, error)

func NewWebAuthnCredential

func NewWebAuthnCredential(userID uuid.UUID, cred *webauthn.Credential, friendlyName string) *WebAuthnCredential

func (*WebAuthnCredential) Delete

func (pc *WebAuthnCredential) Delete(tx *storage.Connection) error

func (WebAuthnCredential) TableName

func (WebAuthnCredential) TableName() string

func (*WebAuthnCredential) ToWebAuthnCredential

func (pc *WebAuthnCredential) ToWebAuthnCredential() webauthn.Credential

ToWebAuthnCredential converts back to the library's Credential type for verification.

func (*WebAuthnCredential) UpdateFriendlyName

func (pc *WebAuthnCredential) UpdateFriendlyName(tx *storage.Connection, friendlyName string) error

func (*WebAuthnCredential) UpdateLastUsedAt

func (pc *WebAuthnCredential) UpdateLastUsedAt(tx *storage.Connection) error

func (*WebAuthnCredential) UpdateSignCount

func (pc *WebAuthnCredential) UpdateSignCount(tx *storage.Connection, signCount uint32) error

type WebAuthnCredentialNotFoundError

type WebAuthnCredentialNotFoundError struct{}

WebAuthnCredentialNotFoundError represents when a WebAuthn credential can't be found.

func (WebAuthnCredentialNotFoundError) Error

func (WebAuthnCredentialNotFoundError) Is

type WebAuthnSessionData

type WebAuthnSessionData struct {
	*webauthn.SessionData
}

func (*WebAuthnSessionData) Scan

func (s *WebAuthnSessionData) Scan(value interface{}) error

func (*WebAuthnSessionData) ToChallenge

func (ws *WebAuthnSessionData) ToChallenge(factorID uuid.UUID, ipAddress string) *Challenge

func (*WebAuthnSessionData) Value

func (s *WebAuthnSessionData) Value() (driver.Value, error)

type WebAuthnTransports

type WebAuthnTransports []protocol.AuthenticatorTransport

WebAuthnTransports is a JSON-serializable slice of authenticator transports.

func (*WebAuthnTransports) Scan

func (t *WebAuthnTransports) Scan(value interface{}) error

func (WebAuthnTransports) Value

func (t WebAuthnTransports) Value() (driver.Value, error)

Jump to

Keyboard shortcuts

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