models

package
v0.0.0-...-e3e9b0f Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2024 License: MIT Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SessionValid        SessionValidityReason = iota
	SessionPastNotAfter                       = iota
	SessionPastTimebox                        = iota
	SessionTimedOut                           = iota
)
View Source
const CreatedAt = "created_at"
View Source
const InvalidCodeChallengeError = "code challenge does not match previously saved code verifier"
View Source
const InvalidCodeMethodError = "code challenge method not supported"
View Source
const TOTP = "totp"

Variables

Functions

func AddClaimToSession

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

func CountOtherUsers

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

CountOtherUsers counts how many other users exist besides the one provided

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) 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, token string, forUpdate bool) (*User, *RefreshToken, *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.

func GetAccountLinkingDomain

func GetAccountLinkingDomain(provider 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 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 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 LogoutAllRefreshTokens

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

Deprecated. For backward compatibility, some access tokens may not have a sessionId. Use models.Logout instead. LogoutAllRefreshTokens deletes all sessions for a user.

func LogoutSession

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

LogoutSession deletes the current session for a user

func NewAuditLogEntry

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

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.

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) 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"
)

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
	SSOSAML
	Recovery
	Invite
	MagicLink
	EmailSignup
	EmailChange
	TokenRefresh
	Anonymous
)

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 (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"`
}

func FindChallengeByID

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

func NewChallenge

func NewChallenge(factor *Factor, ipAddress string) *Challenge

func (*Challenge) GetExpiryTime

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

func (*Challenge) HasExpired

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

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

type Clan

type Clan struct {
	ID                      uuid.UUID          `json:"id" db:"id" bun:"id,pk"` //uuid.UUID
	Name                    *string            `json:"name" db:"name"`
	DisplayName             *string            `json:"display_name" db:"display_name"`
	Slug                    *string            `json:"slug" db:"slug"`
	Branding                *JSONMap           `json:"branding" db:"branding"`
	Email                   storage.NullString `json:"email" db:"email"`
	Phone                   *string            `json:"phone" db:"phone"`
	MissionStatement        *string            `json:"mission_statement" db:"mission_statement"`
	MissionStatementSummary *string            `json:"mission_statement_summary" db:"mission_statement_summary"`
	AdditionalTraits        *JSONMap           `json:"additional_traits" db:"additional_traits"`
	DateEstablished         *calendar.Date     `json:"date_established" db:"date_established"`
	CreatedBy               *uuid.UUID         `json:"created_by" db:"created_by"`
	IsPublic                bool               `json:"is_public" db:"is_public"`
	IsBanned                bool               `json:"is_banned" db:"is_banned"`
	SuspendedUntil          *time.Time         `json:"suspended_until" db:"suspended_until"`
	MemberTraitsURL         *string            `json:"member_traits_url" db:"member_traits_url"`
	ClanTypeID              *uuid.UUID         `json:"clan_type_id" db:"clan_type_id"`
	InsertedAt              *time.Time         `json:"inserted_at" db:"inserted_at"`
	UpdatedAt               *time.Time         `json:"updated_at" db:"updated_at"`

	Preferences map[string]interface{} `json:"preferences"`

	Owner       *Profile      `json:"owner" belongs-to:"profiles"`
	ClanType    *ClanType     `json:"clan_type" has_one:"clan_types"`
	ClanMembers *[]ClanMember `json:"clan_members" has_many:"clan_members"`
	ClanGroup   *[]ClanGroup  `json:"clan_group" has_many:"clan_groups"`
}

func FindClanByID

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

NewClan returns an Clan associated to the user's id.

func NewClan

func NewClan(name, display_name, email, slug string, ct uuid.UUID, user User) (*Clan, error)

func (*Clan) GetEmail

func (i *Clan) GetEmail() string

GetEmail returns the user's email as a string

func (Clan) TableName

func (Clan) TableName() string

func (Clan) Validate

func (p Clan) Validate() error

type ClanAffiliation

type ClanAffiliation struct {
	ID           uuid.UUID  `json:"id" db:"id" bun:"id,pk"` //uuid.UUID
	ClanID       *uuid.UUID `json:"clan_id" db:"clan_id"`
	RelatedTo    *uuid.UUID `json:"related_to" db:"related_to"`
	Relationship string     `json:"relationship" db:"relationship"`
	InsertedAt   *time.Time `json:"inserted_at" db:"inserted_at"`
	UpdatedAt    *time.Time `json:"updated_at" db:"updated_at"`
}

clans can have only 1 direct parent

func (ClanAffiliation) TableName

func (ClanAffiliation) TableName() string

func (ClanAffiliation) Validate

func (p ClanAffiliation) Validate() error

type ClanGroup

type ClanGroup struct {
	ID         *uuid.UUID `json:"id" db:"id" bun:"id,pk"` //uuid.UUID
	Name       *string    `json:"name" db:"name"`
	ClanID     *uuid.UUID `json:"clan_id" db:"clan_id"`
	InsertedAt *time.Time `json:"inserted_at" db:"inserted_at"`
	UpdatedAt  *time.Time `json:"updated_at" db:"updated_at"`

	Clan Clan `json:"clan" belongs_to:"clan"`
}

func (ClanGroup) TableName

func (ClanGroup) TableName() string

func (ClanGroup) Validate

func (p ClanGroup) Validate() error

type ClanMember

type ClanMember struct {
	ID               *uuid.UUID     `json:"id" db:"id" bun:"id,pk"`
	ProfileID        *uuid.UUID     `json:"profile_id" db:"profile_id"`
	ClanID           *uuid.UUID     `json:"clan_id" db:"clan_id"`
	DateJoined       *calendar.Date `json:"date_joined" db:"date_joined"` //date
	AdditionalTraits JSONMap        `json:"additional_traits" db:"additional_traits"`
	IsBanned         bool           `json:"is_banned" db:"is_banned"`
	Tags             []uuid.UUID    `json:"tags" db:"tags"`
	SuspendedUntil   *time.Time     `json:"suspended_until" db:"suspended_until"`
	InsertedAt       *time.Time     `json:"inserted_at" db:"inserted_at"`
	UpdatedAt        *time.Time     `json:"updated_at" db:"updated_at"`

	// Profile Profile `json:"profile" bun:"rel:belongs-to"`
	Clan Clan `json:"clan" belongs_to:"clan"`
}

func (ClanMember) TableName

func (ClanMember) TableName() string

type ClanType

type ClanType struct {
	ID          *uuid.UUID `json:"id" db:"id" bun:"id,pk"` //uuid.UUID
	ClanType    *string    `json:"type" db:"clan_type_type"`
	Description *string    `json:"description" db:"description"`
	RefCode     *string    `json:"ref_code" db:"ref_code"`
	InsertedAt  *time.Time `json:"inserted_at" db:"inserted_at"`
	UpdatedAt   *time.Time `json:"updated_at" db:"updated_at"`

	Clan Clan `json:"clan" belongs_to:"clan"`
}

func FindAllClanTypes

func FindAllClanTypes(tx storage.Connection) ([]*ClanType, error)

NewClanType returns all clan types in the database

func (ClanType) TableName

func (ClanType) TableName() string

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

type ConfirmationTokenNotFoundError

type ConfirmationTokenNotFoundError struct{}

ConfirmationTokenNotFoundError represents when a confirmation token is not found.

func (ConfirmationTokenNotFoundError) Error

type Factor

type Factor struct {
	ID           uuid.UUID   `json:"id" db:"id"`
	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"`
}

func FindFactorByFactorID

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

func NewFactor

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

func (*Factor) DowngradeSessionsToAAL1

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

func (*Factor) IsOwnedBy

func (f *Factor) IsOwnedBy(user *User) bool

func (*Factor) IsVerified

func (f *Factor) IsVerified() bool

func (Factor) TableName

func (Factor) TableName() string

func (*Factor) UpdateFactorType

func (f *Factor) UpdateFactorType(tx *storage.Connection, factorType string) error

UpdateFactorType modifies the factor type

func (*Factor) UpdateFriendlyName

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

UpdateFriendlyName changes the friendly name

func (*Factor) UpdateStatus

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

UpdateStatus modifies the factor status

type FactorNotFoundError

type FactorNotFoundError struct{}

FactorNotFoundError represents when a user is not found.

func (FactorNotFoundError) Error

func (e FactorNotFoundError) Error() string

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" db:"auth_code"`
	AuthenticationMethod string     `json:"authentication_method" db:"authentication_method"`
	CodeChallenge        string     `json:"code_challenge" db:"code_challenge"`
	CodeChallengeMethod  string     `json:"code_challenge_method" 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"`
}

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(providerType, codeChallenge string, codeChallengeMethod CodeChallengeMethod, authenticationMethod AuthenticationMethod, userID *uuid.UUID) *FlowState

func (*FlowState) IsExpired

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

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

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

	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

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 Pagination

type Pagination struct {
	Page    uint64
	PerPage uint64
	Count   uint64
}

func (*Pagination) Offset

func (p *Pagination) Offset() uint64

type Profile

type Profile struct {
	ID             *uuid.UUID     `json:"id" db:"id" bun:"id,pk"`
	FirstName      *string        `json:"first_name" db:"first_name"`
	LastName       *string        `json:"last_name" db:"last_name"`
	Username       *string        `json:"username" db:"username"`
	Email          string         `json:"email" db:"email"`
	Phone          *string        `json:"phone" db:"phone"`
	PhotoURI       *string        `json:"photo_uri" db:"photo_uri"`
	Bio            *string        `json:"bio" db:"bio"`
	BirthDate      *calendar.Date `json:"birth_date" db:"birth_date"` // date without time and timezone
	IsBanned       *bool          `json:"is_banned" db:"is_banned"`
	SuspendedUntil *time.Time     `json:"suspended_until" db:"suspended_until"`
	IdentityID     uuid.UUID      `json:"identity_id" db:"identity_id"`
	InsertedAt     *time.Time     `json:"inserted_at" db:"inserted_at"`
	UpdatedAt      *time.Time     `json:"updated_at" db:"updated_at"`

	Preference map[string]interface{} `json:"preferences,omitempty"`
	Clan       *[]Clan                `json:"clan" has_many:"clans"`
}

func FindProfileByID

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

func (Profile) TableName

func (Profile) TableName() string

func (*Profile) UpdateBio

func (p *Profile) UpdateBio(tx *storage.Connection, n *string) error

func (*Profile) UpdateDOB

func (p *Profile) UpdateDOB(tx *storage.Connection, n *calendar.Date) error

func (*Profile) UpdateFirstName

func (p *Profile) UpdateFirstName(tx *storage.Connection, n *string) error

UpdateLastSignInAt update field last_sign_in_at for user according to specified field

func (*Profile) UpdateLastName

func (p *Profile) UpdateLastName(tx *storage.Connection, n *string) error

func (*Profile) UpdateUsername

func (p *Profile) UpdateUsername(tx *storage.Connection, n *string) error

func (Profile) Validate

func (p Profile) Validate() error

type ProfileNotFoundError

type ProfileNotFoundError struct{}

ProfileNotFoundError represents when a Profile is not found.

func (ProfileNotFoundError) Error

func (e ProfileNotFoundError) Error() string

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(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

type SAMLAttribute

type SAMLAttribute struct {
	Name    string      `json:"name,omitempty"`
	Names   []string    `json:"names,omitempty"`
	Default interface{} `json:"default,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

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"`

	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 FindAllSAMLProviders

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

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 FindSSOProviderForEmailAddress

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

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

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"`
}

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) CalculateAALAndAMR

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

func (*Session) CheckValidity

func (s *Session) CheckValidity(now time.Time, refreshTokenTime *time.Time, timebox, inactivityTimeout *time.Duration) 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) IsAAL2

func (s *Session) IsAAL2() bool

func (*Session) LastRefreshedAt

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

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

type SessionNotFoundError

type SessionNotFoundError struct{}

func (SessionNotFoundError) Error

func (e SessionNotFoundError) Error() string

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) (*User, error)

IsDuplicatedEmail returns whether a user exists with a matching email and audience. 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 (*User) Authenticate

func (u *User) Authenticate(ctx context.Context, password string) bool

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) 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) HasRole

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

HasRole returns true when the users role is set to roleName

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) 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.

type UserEmailUniqueConflictError

type UserEmailUniqueConflictError struct{}

func (UserEmailUniqueConflictError) Error

type UserNotFoundError

type UserNotFoundError struct{}

UserNotFoundError represents when a user is not found.

func (UserNotFoundError) Error

func (e UserNotFoundError) Error() string

Jump to

Keyboard shortcuts

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