models

package
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AUTHORIZATION_GRANT_LIFETIME          = time.Hour * 24 * 60 // Lifetime of an authorization grant
	REPLACED_AUTHORIZATION_GRANT_LIFETIME = time.Hour * 24 * 30 // Lifetime of a replaced authorization grant
)
View Source
const (
	CLIENT_ID_PREFIX        = "cl_"
	CLIENT_ID_BYTE_SIZE     = 16
	CLIENT_SECRET_BYTE_SIZE = 32
)
View Source
const (
	TOKEN_DEFAULT_RANDOM_LENGTH = 24

	AUTHORIZATION_CODE_TOKEN_LIFETIME = 5 * time.Minute
	ACCESS_TOKEN_LIFETIME             = 10 * time.Minute
	REFRESH_TOKEN_LIFETIME            = 30 * 24 * time.Hour // 30 days
	CLIENT_CREDENTIALS_TOKEN_LIFETIME = 5 * time.Minute
	CUSTOM_TOKEN_LIFETIME             = 24 * time.Hour // 24 hours
)
View Source
const (
	ACCESS_TOKEN_PREFIX             = "at"
	AUTHORIZATION_CODE_TOKEN_PREFIX = "ac"
	REFRESH_TOKEN_PREFIX            = "rt"
	CLIENT_CREDENTIALS_TOKEN_PREFIX = "cc"
	CUSTOM_TOKEN_PREFIX             = "ct"
)
View Source
const RANDOM_TOKEN_LENGTH = 6 // Length of the random token for Magic Link

Variables

This section is empty.

Functions

func DeleteMagicLinkWhitelistByEmail

func DeleteMagicLinkWhitelistByEmail(ctx context.Context, db bun.IDB, email string) errors.HTTPError

func LogoutSession

func LogoutSession(ctx context.Context, db bun.IDB, sessionID string, reason ...string) errors.OIDCError

func LogoutSessionsByUserID

func LogoutSessionsByUserID(ctx context.Context, db bun.IDB, userID string, reason ...string) errors.OIDCError

func NewTokenQuery

func NewTokenQuery(db bun.IDB, value string, tokenType string) *tokenQuery

func RevokeTokenByValue

func RevokeTokenByValue(ctx context.Context, db bun.IDB, tokenValue string, tokenTypeHint *string) errors.OIDCError

Types

type Address

type Address struct {
	bun.BaseModel `bun:"table:oidc_addresses"`

	ID            uuid.UUID              `json:"-" bun:"address_id,type:uuid,pk,default:gen_random_uuid()"`
	UserID        uuid.UUID              `json:"-" bun:"user_id,type:uuid,notnull"`
	StreetAddress *utils.EncryptedString `json:"street_address,omitempty" bun:"street_address"` // encrypt
	Locality      *utils.EncryptedString `json:"locality,omitempty" bun:"locality"`             // encrypt
	Region        *utils.EncryptedString `json:"region,omitempty" bun:"region"`                 // encrypt
	PostalCode    *utils.EncryptedString `json:"postal_code,omitempty" bun:"postal_code"`       // encrypt
	Country       *string                `json:"country,omitempty" bun:"country"`               // encrypt
	Formatted     *string                `json:"formatted,omitempty" bun:"-"`

	*CreatedAt // Pointer to avoid marshaling zero value in JWT
	*UpdatedAt // Pointer to avoid marshaling zero value in JWT
}

func (*Address) AfterScanRow

func (a *Address) AfterScanRow(ctx context.Context) error

func (*Address) BeforeUpdate

func (a *Address) BeforeUpdate(ctx context.Context, query *bun.UpdateQuery) error

func (*Address) GetID

func (a *Address) GetID() string

func (*Address) Save

func (a *Address) Save(ctx context.Context, db bun.IDB) errors.HTTPError

func (*Address) String

func (a *Address) String() string

func (*Address) Validate

func (a *Address) Validate() error

type Authorization

type Authorization struct {
	bun.BaseModel `bun:"table:oidc_authorizations"` // Base model for the authorization table

	ID uuid.UUID `json:"-" bun:"authorization_id,pk,type:uuid,default:gen_random_uuid()"` // Unique identifier for the authorization

	Scope           []utils.Scope           `json:"scope" schema:"scope,required" validate:"required,dive,scope" bun:"scope,type:oidc_standard_scope[],notnull"`  // List of scopes associated with the authorization
	ACRValues       *[]utils.ACR            `json:"acr_values,omitempty" schema:"acr_values" validate:"omitempty,dive,acr" bun:"acr_values,type:oidc_acr_type[]"` // Authentication Context Class Reference values
	ClaimsRequested *map[string]interface{} `json:"claims_requested,omitempty" schema:"-" bun:"claims_requested,type:jsonb"`                                      // Optional claims requested by the client, stored as JSON
	ClaimsGranted   *map[string]interface{} `json:"claims_granted,omitempty" schema:"-" bun:"claims_granted,type:jsonb"`                                          // Optional claims granted by the authorization server, stored as JSON
	RedirectURI     string                  `json:"redirect_uri" schema:"redirect_uri,required" validate:"required,uri" bun:"redirect_uri,notnull"`
	ResponseType    utils.ResponseType      `` /* 138-byte string literal not displayed */

	CodeChallenge       *string           `json:"code_challenge,omitempty" schema:"code_challenge" bun:"code_challenge"` // Code challenge for PKCE, if applicable
	CodeChallengeMethod *utils.PKCEMethod ``                                                                             // Method used for the code challenge, if applicable
	/* 130-byte string literal not displayed */

	State        *string             `json:"state,omitempty" schema:"state" bun:"state"` // State parameter for the authorization request, if applicable
	Nonce        *string             `json:"nonce,omitempty" schema:"nonce" bun:"nonce"` // Nonce parameter for the authorization request, if applicable
	AuthTime     *time.Time          `json:"-" schema:"-" bun:"auth_time"`               // Time at which the End-User authenticated
	ResponseMode *utils.ResponseMode `json:"-" schema:"response_mode" validate:"omitempty,response-mode" bun:"-"`

	IsActive bool              `json:"is_active" schema:"-" bun:"is_active"`
	Status   *utils.AuthStatus `json:"status" schema:"-" validate:"omitempty,auth-status" bun:"status"` // Status of the authorization (e.g., approved, pending, denied, revoked)

	ClientID string  `json:"-" schema:"client_id,required" validate:"required" bun:"client_id,notnull"` // ID of the client associated with the authorization
	Client   *Client `json:"client" schema:"-" bun:"rel:has-one,join:client_id=client_id"`              // Client associated with the authorization

	UserID uuid.UUID `json:"-" schema:"-" bun:"user_id,type:uuid,nullzero"`          // ID of the user associated with the authorization
	User   *User     `json:"user" schema:"-" bun:"rel:has-one,join:user_id=user_id"` // User associated with the authorization

	ReplacedID            uuid.UUID      `json:"-" schema:"-" bun:"replaced_id,type:uuid,nullzero"`
	ReplacedAuthorization *Authorization `json:"replaced_authorization" schema:"-" bun:"rel:has-one,join:replaced_id=authorization_id"`

	// Additional request parameters for the authorization
	ClientSecret *string       `json:"-" schema:"client_secret" bun:"-"`                                     // Optional client secret for the authorization, if applicable
	LoginHint    *string       `json:"login_hint,omitempty" schema:"login_hint" bun:"-"`                     // Optional login hint for the authorization, if applicable
	MaxAge       *uint64       `json:"max_age,omitempty" schema:"max_age" validate:"omitempty" bun:"-"`      // Optional maximum age for the authorization, in seconds
	Prompt       *utils.Prompt `json:"prompt,omitempty" schema:"prompt" validate:"omitempty,prompt" bun:"-"` // Optional prompt parameter for the authorization, if applicable

	ApprovedAt *time.Time `json:"approved_at,omitempty" bun:"approved_at"` // Timestamp when the authorization was approved, if applicable
	RevokedAt  *time.Time `json:"revoked_at,omitempty" bun:"revoked_at"`   // Timestamp when the authorization was revoked, if applicable

	CreatedAt
	ExpiresAt
}

func GetAuthorizationByClientAndUser

func GetAuthorizationByClientAndUser(ctx context.Context, db bun.IDB, clientID string, userID uuid.UUID) (*Authorization, errors.HTTPError)

func GetAuthorizationByID

func GetAuthorizationByID(ctx context.Context, db bun.IDB, id string) (*Authorization, errors.HTTPError)

func (*Authorization) AfterScanRow

func (a *Authorization) AfterScanRow(ctx context.Context) error

func (*Authorization) BeforeAppendModel

func (a *Authorization) BeforeAppendModel(ctx context.Context, query bun.Query) error

func (*Authorization) IsApproved

func (a *Authorization) IsApproved() bool

func (*Authorization) Save

func (a *Authorization) Save(ctx context.Context, db bun.IDB) errors.OIDCError

func (*Authorization) Validate

func (a *Authorization) Validate() errors.OIDCError

type Client

type Client struct {
	bun.BaseModel `bun:"table:oidc_clients"`

	ID          string              `json:"client_id,omitempty" bun:"client_id,pk"`
	Name        string              `json:"client_name" validate:"required" bun:"client_name,notnull"`       // Name of the client, used for display purposes
	Secret      *utils.HashedString `json:"-" bun:"client_secret,type:bytea"`                                // Hashed
	Description *string             `json:"client_description,omitempty" bun:"client_description,type:text"` // Optional description of the client
	URI         *string             `json:"client_uri,omitempty" validate:"omitempty,uri" bun:"client_uri"`  // Optional URI for the client
	GrantTypes  *[]utils.GrantType  ``                                                                       // List of grant types supported by the client
	/* 167-byte string literal not displayed */
	ResponseTypes *[]utils.ResponseType `` // List of response types supported by the client
	/* 168-byte string literal not displayed */
	AuthMethod *utils.AuthMethod `` // Authentication method for the token endpoint
	/* 179-byte string literal not displayed */

	RedirectURIs           []string `json:"redirect_uris" validate:"required,dive,uri" bun:"redirect_uris,type:text[]"`                                    // List of redirect URIs for the client
	PostLogoutRedirectURIs []string `json:"post_logout_redirect_uris,omitempty" validate:"omitempty,dive,uri" bun:"post_logout_redirect_uris,type:text[]"` // List of post logout redirect URIs for the client

	IsAuthTimeRequired *bool `json:"require_auth_time,omitempty" bun:"require_auth_time"`    // Whether the client requires auth time
	IsPKCERequired     *bool `json:"require_pkce,omitempty" bun:"require_pkce,default:true"` // Whether the client requires PKCE

	AccessTokenLifetime      int64                   `json:"access_token_lifetime,omitempty" validate:"omitempty,gt=0" bun:"access_token_lifetime,default:3600"`    // Lifetime of access tokens in seconds
	RefreshTokenLifetime     int64                   `json:"refresh_token_lifetime,omitempty" validate:"omitempty,gt=0" bun:"refresh_token_lifetime,default:86400"` // Lifetime of refresh tokens in seconds
	IDTokenLifetime          int64                   `json:"id_token_lifetime,omitempty" validate:"omitempty,gt=0" bun:"id_token_lifetime,default:300"`             // Lifetime of ID tokens in seconds
	IDTokenSignedResponseAlg *utils.SigningAlgorithm `json:"id_token_signed_response_alg,omitempty" validate:"omitempty,jws" bun:"id_token_signed_response_alg"`    // Signing algorithm for ID tokens

	IsActive              *bool        `json:"is_active,omitempty" bun:"is_active,default:true"`                                          // Whether the client is active
	IsConfidential        *bool        `json:"is_confidential,omitempty" bun:"is_confidential,default:false"`                             // Whether the client is confidential
	ClientSecretExpiresAt *utils.Epoch `json:"client_secret_expires_at,omitempty" bun:"client_secret_expires_at,default:to_timestamp(0)"` // Expiration time of the client secret

	OwnerID uuid.UUID `json:"-" validate:"required" bun:"owner_id,notnull"`                       // ID of the owner of the client
	Owner   *User     `json:"owner,omitempty" bun:"rel:belongs-to,join:owner_id=user_id,notnull"` // Owner of the client

	CreatedAt
	UpdatedAt
}

func GetClientByID

func GetClientByID(ctx context.Context, db bun.IDB, id string) (*Client, errors.HTTPError)

func GetClientByIDAndSecret

func GetClientByIDAndSecret(ctx context.Context, db bun.IDB, id string, secret string) (*Client, errors.HTTPError)

func (*Client) AfterScanRow

func (c *Client) AfterScanRow(ctx context.Context) error

func (*Client) BeforeAppendModel

func (c *Client) BeforeAppendModel(ctx context.Context, query bun.Query) error

func (*Client) NewSecret

func (c *Client) NewSecret(ctx context.Context, db bun.IDB, expiresAt ...time.Time) (string, errors.HTTPError)

func (*Client) Sanitize

func (c *Client) Sanitize()

func (*Client) Save

func (c *Client) Save(ctx context.Context, db bun.IDB) errors.HTTPError

func (*Client) SaveWithSecret added in v0.1.12

func (c *Client) SaveWithSecret(ctx context.Context, db bun.IDB) (string, errors.HTTPError)

SaveWithSecret saves a client and returns a newly generated plaintext secret, if one was created. Callers should disclose that value only once.

func (Client) String

func (c Client) String() string

func (*Client) Validate

func (c *Client) Validate() errors.OIDCError

type CreatedAt

type CreatedAt struct {
	CreatedAt time.Time `json:"created_at,omitempty" bun:"created_at,notnull,default:now()"`
}

type ExpiresAt

type ExpiresAt struct {
	ExpiresAt time.Time `json:"expires_at,omitempty" validate:"omitempty,time-gt-now" bun:"expires_at,notnull,nullzero"`
}

type MagicLinkToken

type MagicLinkToken struct {
	bun.BaseModel `bun:"table:oidc_magic_link_tokens"`

	ID        uuid.UUID              `json:"-" schema:"-" bun:"token_id,pk,type:uuid,default:gen_random_uuid()"`                 // Unique identifier for the token
	Token     *utils.HashedString    `json:"-" schema:"token,required" bun:"token,type:bytea,notnull"`                           // Hashed token value
	Email     *utils.HashedString    `json:"-" schema:"email,required" validate:"required,email" bun:"email,type:bytea,notnull"` // Hashed email address associated with the token
	IPAddress *utils.EncryptedString `json:"-" schema:"-" validate:"omitempty,ip|hostname_port" bun:"ip_address,type:bytea"`     // Encrypted IP address of the user
	UserAgent *string                `json:"-" schema:"-" bun:"user_agent"`                                                      // User agent string of the user

	IsActive *bool         `json:"-" schema:"-" bun:"is_active,default:true"`             // Whether the token is active
	Result   *utils.Result `json:"-" schema:"-" validate:"omitempty,result" bun:"result"` // Result of the token validation (e.g., success, failed, expired)

	User *User `json:"-" schema:"-" bun:"rel:belongs-to,join:email=email_hash"` // User associated with the token

	ConsumedAt *time.Time `json:"-" schema:"-" bun:"consumed_at"` // Timestamp when the token was consumed, if applicable
	CreatedAt
	ExpiresAt
	UpdatedAt
}

func ConsumeMagicLinkToken

func ConsumeMagicLinkToken(ctx context.Context, db bun.IDB, id string, token string, meta ...string) (*MagicLinkToken, errors.HTTPError)

func CreateMagicLinkToken

func CreateMagicLinkToken(ctx context.Context, db bun.IDB, email string, meta ...string) (*MagicLinkToken, errors.HTTPError)

func GetMagicLinkTokenByID

func GetMagicLinkTokenByID(ctx context.Context, db bun.IDB, id string) (*MagicLinkToken, errors.HTTPError)

func (*MagicLinkToken) AfterScanRow

func (m *MagicLinkToken) AfterScanRow(ctx context.Context) error

func (*MagicLinkToken) BeforeAppendModel

func (m *MagicLinkToken) BeforeAppendModel(ctx context.Context, query bun.Query) error

func (*MagicLinkToken) Validate

func (m *MagicLinkToken) Validate() (err error)

type MagicLinkWhitelist

type MagicLinkWhitelist struct {
	bun.BaseModel `bun:"table:oidc_magic_link_whitelist"`

	ID        uuid.UUID              `json:"-" schema:"-" bun:"whitelist_id,pk,type:uuid,default:gen_random_uuid()"`                        // Unique identifier for the whitelist entry
	Email     *utils.EncryptedString `json:"email" schema:"email,required" validate:"required,email" bun:"email,type:bytea,unique,notnull"` // Encrypted email address to whitelist
	EmailHash *utils.HashedString    `json:"-" schema:"-" bun:"email_hash,type:bytea,unique,notnull"`                                       // Hashed email address for uniqueness
	Reason    *string                `json:"reason,omitempty" schema:"reason" validate:"omitempty,max=255" bun:"reason"`                    // Optional reason for whitelisting the email address
	Notes     *string                `json:"notes,omitempty" schema:"notes" validate:"omitempty,max=500" bun:"notes"`                       // Optional notes about the whitelist entry

	AddedByID *uuid.UUID `json:"added_by_id,omitempty" schema:"added_by" validate:"omitempty,uuid4" bun:"added_by,type:uuid"` // ID of the user who added the whitelist entry
	AddedBy   *User      `json:"-" schema:"-" bun:"rel:belongs-to,join:added_by=user_id"`                                     // User who added the whitelist entry

	CreatedAt
	ExpiresAt
}

func GetMagicLinkWhitelistByEmail

func GetMagicLinkWhitelistByEmail(ctx context.Context, db bun.IDB, email string) (*MagicLinkWhitelist, errors.HTTPError)

func (*MagicLinkWhitelist) BeforeAppendModel

func (m *MagicLinkWhitelist) BeforeAppendModel(ctx context.Context, query bun.Query) error

func (*MagicLinkWhitelist) Save

func (MagicLinkWhitelist) String

func (m MagicLinkWhitelist) String() string

func (*MagicLinkWhitelist) Validate

func (m *MagicLinkWhitelist) Validate() (err error)

type OpenIDConfiguration

type OpenIDConfiguration struct {
	Issuer                                     string                   `json:"issuer" validate:"required,https_origin"`
	AuthorizationEndpoint                      string                   `json:"authorization_endpoint" validate:"required,https_url"`
	TokenEndpoint                              string                   `json:"token_endpoint" validate:"required,https_url"`
	TokenIntrospectionEndpoint                 string                   `json:"introspection_endpoint" validate:"omitempty,https_url"`
	UserInfoEndpoint                           string                   `json:"userinfo_endpoint,omitempty" validate:"omitempty,https_url"`
	JWKSURI                                    string                   `json:"jwks_uri" validate:"required,https_url"`
	RegistrationEndpoint                       string                   `json:"registration_endpoint,omitempty" validate:"omitempty,https_url"`
	EndSessionEndpoint                         string                   `json:"end_session_endpoint,omitempty" validate:"omitempty,https_url"`
	ScopesSupported                            []utils.Scope            `json:"scopes_supported" validate:"omitempty,dive,scope"`
	ResponseTypesSupported                     []utils.ResponseType     `json:"response_types_supported" validate:"contains-any=code,required,dive,response-type"`
	ResponseModesSupported                     []utils.ResponseMode     `json:"response_modes_supported" validate:"omitempty,dive,response-mode"`
	GrantTypesSupported                        []utils.GrantType        `json:"grant_types_supported" validate:"omitempty,dive,grant-type"`
	ACRValuesSupported                         []utils.ACR              `json:"acr_values_supported" validate:"omitempty,dive,acr"`
	SubjectTypesSupported                      []utils.SubjectType      `json:"subject_types_supported" validate:"required,dive,subject-type"`
	IDTokenSigningAlgValuesSupported           []utils.SigningAlgorithm `json:"id_token_signing_alg_values_supported" validate:"required,dive,jws,gt=0"`
	UserInfoSigningAlgValuesSupported          []utils.SigningAlgorithm `json:"userinfo_signing_alg_values_supported,omitempty" validate:"omitempty,dive,jws"`
	RequestObjectSigningAlgValuesSupported     []utils.SigningAlgorithm `json:"request_object_signing_alg_values_supported,omitempty" validate:"omitempty,dive,jws"`
	TokenEndpointAuthMethodsSupported          []utils.AuthMethod       `json:"token_endpoint_auth_methods_supported,omitempty" validate:"omitempty,dive,auth-method"`
	TokenEndpointAuthSigningAlgValuesSupported []utils.SigningAlgorithm `json:"token_endpoint_auth_signing_alg_values_supported,omitempty" validate:"omitempty,dive,jws"`
	DisplayValuesSupported                     []utils.Display          `json:"display_values_supported,omitempty" validate:"omitempty,dive,display"`
	ClaimTypesSupported                        []utils.ClaimType        `json:"claim_types_supported,omitempty" validate:"omitempty,dive,claim-type"`
	ClaimsSupported                            []string                 `json:"claims_supported,omitempty"`
	ServiceDocumentation                       string                   `json:"service_documentation,omitempty" validate:"omitempty,url"`
	UILocalesSupported                         []string                 `json:"ui_locales_supported,omitempty" validate:"omitempty,dive,bcp47_language_tag"`
	ClaimsLocalesSupported                     []string                 `json:"claims_locales_supported,omitempty" validate:"omitempty,dive,bcp47_language_tag"`
	ClaimsParameterSupported                   *bool                    `json:"claims_parameter_supported,omitempty"`
	RequestParameterSupported                  *bool                    `json:"request_parameter_supported,omitempty"`
	RequestURIParameterSupported               *bool                    `json:"request_uri_parameter_supported,omitempty"`
	RequireRequestURIRegistration              *bool                    `json:"require_request_uri_registration,omitempty"`
	OPPolicyUri                                string                   `json:"op_policy_uri,omitempty" validate:"omitempty,url"`
	OPTosUri                                   string                   `json:"op_tos_uri,omitempty" validate:"omitempty,url"`

	// JWE is not supported yet
	IDTokenEncryptionAlgValuesSupported       []string `json:"id_token_encryption_alg_values_supported,omitempty"`
	IDTokenEncryptionEncValuesSupported       []string `json:"id_token_encryption_enc_values_supported,omitempty"`
	UserInfoEncryptionAlgValuesSupported      []string `json:"userinfo_encryption_alg_values_supported,omitempty"`
	UserInfoEncryptionEncValuesSupported      []string `json:"userinfo_encryption_enc_values_supported,omitempty"`
	RequestObjectEncryptionAlgValuesSupported []string `json:"request_object_encryption_alg_values_supported,omitempty"`
	RequestObjectEncryptionEncValuesSupported []string `json:"request_object_encryption_enc_values_supported,omitempty"`
}

func NewOpenIDConfiguration

func NewOpenIDConfiguration(customConfig ...*OpenIDConfiguration) (*OpenIDConfiguration, errors.HTTPError)

func (*OpenIDConfiguration) Validate

func (o *OpenIDConfiguration) Validate() (err error)

type Session

type Session struct {
	bun.BaseModel `bun:"table:oidc_sessions"`

	ID         uuid.UUID              `json:"-" schema:"-" bun:"session_id,pk,type:uuid,default:gen_random_uuid()"`
	IPAddress  *utils.EncryptedString `json:"-" schema:"-" validate:"omitempty,ip|hostname_port" bun:"ip_address,type:bytea"`      // Encrypted IP address of the session
	UserAgent  *string                `json:"-" schema:"-" bun:"user_agent"`                                                       // User agent string of the session
	DeviceInfo *string                `json:"-" schema:"-" bun:"device_info"`                                                      // Optional device information for the session
	Scope      *[]utils.Scope         `json:"-" schema:"-" validate:"omitempty,dive,scope" bun:"scope,type:oidc_standard_scope[]"` // List of scopes associated with the session
	ACRValues  *[]utils.ACR           `json:"-" schema:"-" validate:"omitempty,dive,acr" bun:"acr_values,type:oidc_acr_type[]"`    // Authentication Context Class Reference (ACR) that initiated the session
	AMR        *[]utils.AMR           `json:"-" schema:"-" validate:"omitempty,dive,amr" bun:"amr,type:oidc_amr_type[]"`           // Authentication Methods References (AMR) that initiated the session

	IsActive     *bool   `json:"is_active" schema:"-" bun:"is_active,default:true"`                                              // Whether the session is active
	LogoutReason *string `json:"logout_reason,omitempty" validate:"omitempty,lt=100" schema:"logout_reason" bun:"logout_reason"` // Optional reason for session logout

	RedirectURI *string `json:"-" schema:"-" validate:"omitempty,uri" bun:"-"`

	ClientID *string `json:"-" schema:"-" bun:"client_id"`                               // ID of the client that initiated the session
	Client   *Client `json:"-" schema:"-" bun:"rel:belongs-to,join:client_id=client_id"` // Client which initiated the session

	UserID uuid.UUID `json:"-" schema:"-" validate:"required,uuid4" bun:"user_id,type:uuid,notnull"` // ID of the user associated with the session
	User   *User     `json:"-" schema:"-" bun:"rel:belongs-to,join:user_id=user_id,notnull"`         // User associated with the session

	AuthTime       time.Time `json:"-" schema:"-" validate:"omitempty,time-lt-now" bun:"auth_time,default:now()"`        // Timestamp of the authentication time for the session
	LastAccessedAt time.Time `json:"-" schema:"-" validate:"omitempty,time-lt-now" bun:"last_accessed_at,default:now()"` // Timestamp of the last access to the session

	ExpiresAt
	CreatedAt
	UpdatedAt
}

func GetSessionByID

func GetSessionByID(ctx context.Context, db bun.IDB, id string) (*Session, errors.HTTPError)

func (*Session) AfterScanRow

func (s *Session) AfterScanRow(ctx context.Context) error

func (*Session) AfterSelect

func (s *Session) AfterSelect(ctx context.Context, query *bun.SelectQuery) error

func (*Session) BeforeAppendModel

func (s *Session) BeforeAppendModel(ctx context.Context, query bun.Query) error

func (*Session) Save

func (s *Session) Save(ctx context.Context, db bun.IDB) errors.OIDCError

func (*Session) Validate

func (s *Session) Validate() (err error)

type Token

type Token struct {
	bun.BaseModel `bun:"oidc_tokens"`

	ID          uuid.UUID          `json:"-" schema:"-" bun:"token_id,pk,type:uuid,default:gen_random_uuid()"`                                        // Unique identifier for the token
	Type        utils.TokenType    `json:"type" schema:"type,required" validate:"required,token-type" bun:"token_type,notnull"`                       // Type of the token (e.g., access token, refresh token)
	Value       utils.HashedString `json:"token,omitempty" schema:"token,omitempty" bun:"token_value,notnull"`                                        // Hashed value of the token for security
	RedirectURI *string            `json:"redirect_uri,omitempty" schema:"redirect_uri,omitempty" validate:"omitempty,uri,lt=512" bun:"redirect_uri"` // Optional redirect URI associated with the token

	IsActive         *bool   `json:"is_active" schema:"-" bun:"is_active,default:true"`                                          // Indicates if the token is active
	RevocationReason *string `json:"revocation_reason,omitempty" schema:"-" validate:"omitempty,lt=255" bun:"revocation_reason"` // Optional reason for token revocation
	RotationCount    *int    `json:"-" schema:"-" validate:"omitempty,gte=0" bun:"rotation_count"`                               // Count of how many times the token has been rotated (if applicable)

	// Custom token section below
	IsCustom    bool           `json:"isCustom,omitempty" schema:"is_custom,omitempty" bun:"is_custom"`                                                 // Indicates if the token is a custom token
	Description *string        `json:"description,omitempty" schema:"description,omitempty" validate:"omitempty,lt=512" bun:"description"`              // Optional description of the token
	Scope       *[]utils.Scope `json:"scope,omitempty" schema:"scope,omitempty" validate:"omitempty,dive,scope" bun:"scope,type:oidc_standard_scope[]"` // Optional scopes associated with the token

	// Relations
	AuthorizationID *uuid.UUID     `json:"-" schema:"-" bun:"authorization_id,type:uuid"`                            // ID of the associated authorization
	Authorization   *Authorization `json:"-" schema:"-" bun:"rel:belongs-to,join:authorization_id=authorization_id"` // Associated authorization

	ClientID *string `json:"-" schema:"-" bun:"client_id"`                               // Optional client ID associated with the token (for client_credentials)
	Client   *Client `json:"-" schema:"-" bun:"rel:belongs-to,join:client_id=client_id"` // Associated client (for client_credentials)

	UserID *uuid.UUID `json:"-" schema:"-" bun:"user_id,type:uuid"`                                // ID of the associated user (for custom tokens)
	User   *User      `json:"user,omitempty" schema:"-" bun:"rel:belongs-to,join:user_id=user_id"` // Associated user (for custom tokens)

	PreviousTokenID *uuid.UUID `json:"-" schema:"-" bun:"previous_token_id,type:uuid"`                    // ID of the previous token in a chain (if applicable)
	PreviousToken   *Token     `json:"-" schema:"-" bun:"rel:belongs-to,join:previous_token_id=token_id"` // Previous token in a chain (if applicable)

	ConsumedAt *time.Time `json:"-" schema:"-" validate:"omitempty,time-lte-now" bun:"consumed_at"`  // Timestamp when the token was consumed, if applicable (e.g. authorization_code)
	LastUsedAt *time.Time `json:"-" schema:"-" validate:"omitempty,time-lte-now" bun:"last_used_at"` // Timestamp when the token was last used, if applicable (e.g. access_token)
	RevokedAt  *time.Time `json:"-" schema:"-" validate:"omitempty,time-lte-now" bun:"revoked_at"`   // Timestamp when the token was revoked, if applicable
	CreatedAt
	ExpiresAt
}

func CreateToken

func CreateToken(ctx context.Context, db bun.IDB, tokenType string, obj interface{}) (*Token, errors.OIDCError)

func GetTokenByValue

func GetTokenByValue(ctx context.Context, db bun.IDB, value string, excludeColumns ...string) (*Token, errors.OIDCError)

func (*Token) AfterScanRow

func (m *Token) AfterScanRow(ctx context.Context) error

func (*Token) AfterSelect

func (m *Token) AfterSelect(ctx context.Context, query *bun.SelectQuery) error

func (*Token) BeforeAppendModel

func (m *Token) BeforeAppendModel(ctx context.Context, query bun.Query) error

func (*Token) GenerateTokenHash

func (t *Token) GenerateTokenHash() (string, error)

generates the hash value for use in a JWT e.g. as at_hash or c_hash claim

this function assumes that t.Value is the unhashed token value

func (*Token) Validate

func (t *Token) Validate() (err error)

type UpdatedAt

type UpdatedAt struct {
	UpdatedAt time.Time `json:"updated_at,omitempty" bun:"updated_at,notnull,default:now()"`
}

type User

type User struct {
	bun.BaseModel `bun:"table:oidc_users"`

	ID                    uuid.UUID              `json:"sub,omitempty" bun:"user_id,type:uuid,pk,default:gen_random_uuid()"`
	Email                 *utils.EncryptedString `json:"email,omitempty" validate:"required,email" bun:"email,type:bytea,unique,notnull"` // encrypt
	EmailHash             *utils.HashedString    `json:"-" bun:"email_hash,type:bytea,unique,notnull"`                                    // hashed base64-url-encoded
	IsEmailVerified       *bool                  `json:"email_verified,omitempty" bun:"email_verified,notnull"`
	PhoneNumber           *utils.EncryptedString `json:"phone_number,omitempty" validate:"omitempty,e164" bun:"phone_number,type:bytea,unique"` // encrypt
	IsPhoneNumberVerified *bool                  `json:"phone_number_verified,omitempty" bun:"phone_number_verified"`
	GivenName             *utils.EncryptedString `json:"given_name,omitempty" validate:"omitempty,alphanumunicode" bun:"given_name,type:bytea"`   // encrypt
	FamilyName            *utils.EncryptedString `json:"family_name,omitempty" validate:"omitempty,alphanumunicode" bun:"family_name,type:bytea"` // encrypt
	MiddleName            *utils.EncryptedString `json:"middle_name,omitempty" validate:"omitempty,alphanumunicode" bun:"middle_name,type:bytea"` // encrypt
	Name                  *string                `json:"name,omitempty" bun:"-"`
	Nickname              *string                `json:"nickname,omitempty" validate:"omitempty,alphanum" bun:"nickname"`
	PreferredUsername     *string                `json:"preferred_username,omitempty" validate:"omitempty,alphanum" bun:"preferred_username"`
	Profile               *utils.EncryptedString `json:"profile,omitempty" validate:"omitempty,http_url" bun:"profile"`
	Picture               *utils.EncryptedString `json:"picture,omitempty" validate:"omitempty,http_url" bun:"picture"`
	Website               *utils.EncryptedString `json:"website,omitempty" validate:"omitempty,http_url" bun:"website"`
	Gender                *utils.EncryptedString `json:"gender,omitempty" validate:"omitempty,alphanumunicode" bun:"gender,type:bytea"`   // encrypt
	Birthdate             *utils.EncryptedDate   `json:"birthdate,omitempty" validate:"omitempty,time-lt-now" bun:"birthdate,type:bytea"` // encrypt
	Zoneinfo              *string                `json:"zoneinfo,omitempty" validate:"omitempty,timezone" bun:"zoneinfo"`
	Locale                *string                `json:"locale,omitempty" validate:"omitempty,bcp47_language_tag" bun:"locale"`

	LastLoginAt *time.Time `json:"last_login_at,omitempty" validate:"omitempty,time-lte-now" bun:"last_login_at"`
	IsActive    *bool      `json:"is_active,omitempty" bun:"is_active,notnull,default:true"`
	IsLocked    *bool      `json:"is_locked,omitempty" bun:"is_locked,notnull,default:false"`

	CustomClaims *map[string]interface{} `json:"custom_claims,omitempty" validate:"omitempty" bun:"custom_claims,type:jsonb"`

	Address *Address `json:"address,omitempty" validate:"omitempty" bun:"rel:has-one,join:user_id=user_id"`

	*CreatedAt // Pointer to avoid marshaling zero value in JWT
	*UpdatedAt // Pointer to avoid marshaling zero value in JWT
}

func GetUserByEmail

func GetUserByEmail(ctx context.Context, db bun.IDB, email string) (*User, errors.HTTPError)

func GetUserByID

func GetUserByID(ctx context.Context, db bun.IDB, id string) (*User, errors.HTTPError)

func (*User) AfterScanRow

func (u *User) AfterScanRow(ctx context.Context) error

func (*User) BeforeAppendModel

func (u *User) BeforeAppendModel(ctx context.Context, query bun.Query) error

func (*User) GetClaimsBasedOnScopes

func (u *User) GetClaimsBasedOnScopes(scopes []utils.Scope) *User

func (*User) GetID

func (u *User) GetID() string

func (*User) Hydrate

func (u *User) Hydrate()

func (*User) Sanitize

func (u *User) Sanitize()

func (*User) Save

func (u *User) Save(ctx context.Context, db bun.IDB) errors.HTTPError

func (User) String

func (u User) String() string

func (*User) Validate

func (u *User) Validate() error

func (*User) Write

func (u *User) Write(w http.ResponseWriter)

type ValidatabaleModelWithID

type ValidatabaleModelWithID interface {
	Validate() error
	GetID() string
}

Jump to

Keyboard shortcuts

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