Documentation
¶
Overview ¶
Package canopy provides Go-native authentication primitives for API servers.
Canopy includes email/password authentication, Google and Apple OAuth sign-in, database-backed opaque sessions, email verification, password reset, provider token refresh, audit hooks, and net/http handlers. The package is designed as a library, not a hosted service, so applications can use the built-in HTTP routes or call the service API directly.
Index ¶
- Constants
- Variables
- func ContextWithSession(ctx context.Context, data *SessionData) context.Context
- func DecodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool
- func InvalidFields(fields map[string]string) error
- func WriteError(w http.ResponseWriter, err error)
- func WriteJSON(w http.ResponseWriter, status int, body any)
- type Account
- type AccountLinkStore
- type AdminStore
- type AuditEvent
- type AuditLogger
- type Auth
- type Config
- type Core
- type EmailSender
- type EmailVerificationMessage
- type Environment
- type HookErrorHandler
- type Hooks
- type Invitation
- type Member
- type Module
- type ModuleKeyring
- type OAuthCallbackInput
- type OAuthCallbackResult
- type Organization
- type OrganizationStore
- type PasswordResetMessage
- type ProtectedMemberRemovalStore
- type ProviderTokenCodec
- type RefreshProviderTokenInput
- type RefreshProviderTokenOutput
- type RequestPasswordResetInput
- type ResetPasswordInput
- type Route
- type RouteModule
- type RuntimeConfig
- type SendEmailVerificationInput
- type Service
- func (s *Service) Audit(ctx context.Context, event AuditEvent)
- func (s *Service) Authenticate(r *http.Request) (*SessionData, error)
- func (s *Service) CleanupExpired(ctx context.Context, now time.Time) error
- func (s *Service) ClientIP(r *http.Request) string
- func (s *Service) Config() RuntimeConfig
- func (s *Service) GetSession(ctx context.Context, token string) (*SessionData, error)
- func (s *Service) HashPassword(ctx context.Context, value string) (string, error)
- func (s *Service) IssueSession(ctx context.Context, user User, opt SessionOptions) (*SessionData, string, error)
- func (s *Service) LinkAccount(ctx context.Context, identifier, value string, now time.Time, account *Account) error
- func (s *Service) Middleware(next http.Handler) http.Handler
- func (s *Service) OAuthCallback(ctx context.Context, in OAuthCallbackInput) (*OAuthCallbackResult, error)
- func (s *Service) OptionalSession(next http.Handler) http.Handler
- func (s *Service) Providers() map[string]oauth.Provider
- func (s *Service) RefreshProviderToken(ctx context.Context, in RefreshProviderTokenInput) (*RefreshProviderTokenOutput, error)
- func (s *Service) RequestPasswordReset(ctx context.Context, in RequestPasswordResetInput) error
- func (s *Service) RequireSession(next http.Handler) http.Handler
- func (s *Service) ResetPassword(ctx context.Context, in ResetPasswordInput) error
- func (s *Service) ResolveCallbackURL(callbackURL string) string
- func (s *Service) RevokeUserSessions(ctx context.Context, userID string) error
- func (s *Service) SendEmailVerification(ctx context.Context, in SendEmailVerificationInput) error
- func (s *Service) SignInEmail(ctx context.Context, in SignInEmailInput) (*SignInResult, error)
- func (s *Service) SignInSocial(ctx context.Context, in SignInSocialInput) (*SignInSocialOutput, string, error)
- func (s *Service) SignOut(ctx context.Context, token string) error
- func (s *Service) SignUpEmail(ctx context.Context, in SignUpEmailInput) (*SessionData, string, error)
- func (s *Service) Store() Store
- func (s *Service) UpdateLinkedAccount(ctx context.Context, account *Account) error
- func (s *Service) VerifyEmail(ctx context.Context, in VerifyEmailInput) (*User, error)
- type Session
- type SessionData
- type SessionOptions
- type SessionValidator
- type SignInEmailInput
- type SignInInterceptor
- type SignInResult
- type SignInSocialInput
- type SignInSocialOutput
- type SignUpEmailInput
- type StepUpChallenge
- type Store
- type Team
- type TeamMember
- type TwoFactor
- type TwoFactorStore
- type User
- type UserQuery
- type ValidationError
- type Verification
- type VerifyEmailInput
Constants ¶
const ProviderEmailPassword = "email-password"
Variables ¶
var ( ErrInvalidCredentials = errors.New("canopy: invalid credentials") ErrSignupDisabled = errors.New("canopy: signup disabled") ErrUnverifiedEmail = errors.New("canopy: unverified email") ErrInvalidState = errors.New("canopy: invalid state") ErrInvalidToken = errors.New("canopy: invalid token") ErrExpiredToken = errors.New("canopy: expired token") ErrProviderFailure = errors.New("canopy: provider failure") ErrStorageFailure = errors.New("canopy: storage failure") ErrAccountLinking = errors.New("canopy: account linking required") ErrAccountLinkMismatch = errors.New("canopy: provider email does not match account") ErrNoRefreshToken = errors.New("canopy: no provider refresh token") ErrProviderTokenRefreshFailed = errors.New("canopy: provider token refresh failed") ErrProviderAccountNotFound = errors.New("canopy: provider account not found") ErrNotFound = errors.New("canopy: not found") ErrConflict = errors.New("canopy: conflict") ErrInvalidInput = errors.New("canopy: invalid input") ErrForbidden = errors.New("canopy: forbidden") ErrUserBanned = errors.New("canopy: user banned") ErrInvalidTwoFactorCode = errors.New("canopy: invalid two-factor code") ErrRecentAuthentication = errors.New("canopy: recent authentication required") ErrOrganizationNotFound = errors.New("canopy: organization not found") ErrNotOrganizationMember = errors.New("canopy: not organization member") ErrTeamNotFound = errors.New("canopy: team not found") ErrInvitationInvalid = errors.New("canopy: invitation invalid") ErrLastOrganizationOwner = errors.New("canopy: organization must retain an owner") )
Functions ¶
func ContextWithSession ¶
func ContextWithSession(ctx context.Context, data *SessionData) context.Context
func DecodeJSON ¶ added in v1.0.0
DecodeJSON decodes a size-limited JSON request body into dst. It writes an error response and returns false on failure. A module handler uses it for the same body limit and error shape as the core handler.
func InvalidFields ¶ added in v1.0.0
InvalidFields returns a typed validation error with machine-readable field messages. The map is copied so callers may safely reuse it.
func WriteError ¶ added in v1.0.0
func WriteError(w http.ResponseWriter, err error)
WriteError writes a typed error as a JSON error envelope. A module handler uses it for an error shape that matches the core handler.
Types ¶
type Account ¶
type Account struct {
ID string `json:"id"`
UserID string `json:"userId"`
AccountID string `json:"accountId"`
ProviderID string `json:"providerId"`
AccessToken string `json:"-"`
RefreshToken string `json:"-"`
AccessTokenExpiresAt *time.Time `json:"accessTokenExpiresAt,omitempty"`
RefreshTokenExpiresAt *time.Time `json:"refreshTokenExpiresAt,omitempty"`
Scope string `json:"scope,omitempty"`
IDToken string `json:"-"`
Password string `json:"-"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type AccountLinkStore ¶ added in v1.0.0
type AccountLinkStore interface {
// CreateLinkedAccount atomically consumes the one-time link-confirmation
// verification and creates the provider account for the existing user.
// ErrNotFound: token missing/expired/consumed. ErrConflict: account exists.
CreateLinkedAccount(ctx context.Context, identifier, value string, now time.Time, account *Account) error
}
AccountLinkStore is an optional Store capability. The account-link module uses it for an atomic link confirmation. A store advertises it by implementing this method.
type AdminStore ¶ added in v1.0.0
type AdminStore interface {
// ListUsers returns a page of users and the total count.
ListUsers(ctx context.Context, q UserQuery) (users []User, total int, err error)
ListUserSessions(ctx context.Context, userID string) ([]Session, error)
}
AdminStore is an optional Store capability. The admin module requires it for listing users and their sessions.
type AuditEvent ¶
type AuditLogger ¶
type AuditLogger interface {
LogAuthEvent(ctx context.Context, event AuditEvent)
}
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
func (*Auth) Middleware ¶
Middleware is a deprecated alias for OptionalSession. Deprecated: use OptionalSession or RequireSession to make intent explicit.
func (*Auth) OptionalSession ¶ added in v1.0.0
OptionalSession adds session data to the request context when valid and continues anonymously otherwise.
type Config ¶
type Config struct {
Store Store
Secret string
PreviousSecrets []string
Environment Environment
BasePath string
DisableSignup bool
RequireEmailVerification bool
PasswordMinLength int
PasswordMaxLength int
PasswordHasher password.Hasher
ProviderTokenCodec ProviderTokenCodec
AuditLogger AuditLogger
HookErrorHandler HookErrorHandler
EmailSender EmailSender
TrustedOrigins []string
TrustedProxies []string
DisableOriginCheck bool
Providers []oauth.Provider
OAuthStateTTL time.Duration
OAuthStateCookieName string
EmailVerificationTTL time.Duration
PasswordResetTTL time.Duration
Modules []Module
Session sessions.Config
Hooks Hooks
}
type Core ¶ added in v1.0.0
type Core interface {
Store() Store
Config() RuntimeConfig
HashPassword(ctx context.Context, password string) (string, error)
ModuleKeys(purpose string) (ModuleKeyring, error)
ClientIP(r *http.Request) string
IssueSession(ctx context.Context, user User, opt SessionOptions) (*SessionData, string, error)
Authenticate(r *http.Request) (*SessionData, error)
Audit(ctx context.Context, event AuditEvent)
// Providers returns the configured OAuth providers keyed by provider
// ID. The map is a defensive copy.
Providers() map[string]oauth.Provider
// ResolveCallbackURL returns callbackURL only when it is safe to use.
// It returns an empty string for an untrusted or invalid URL.
ResolveCallbackURL(callbackURL string) string
// LinkAccount consumes the one-time link-confirmation verification and
// creates the provider account for an existing user. The consume and
// the create are atomic when the store supports AccountLinkStore.
LinkAccount(ctx context.Context, identifier, value string, now time.Time, account *Account) error
// UpdateLinkedAccount refreshes the credentials of a linked provider
// account. It keeps the stored credentials when a replacement value is
// empty.
UpdateLinkedAccount(ctx context.Context, account *Account) error
}
Core is the narrow facade that a module depends on. A module must not depend on the concrete Service type.
type EmailSender ¶
type EmailSender interface {
SendEmailVerification(ctx context.Context, message EmailVerificationMessage) error
SendPasswordReset(ctx context.Context, message PasswordResetMessage) error
}
type Environment ¶
type Environment string
const ( Development Environment = "development" Production Environment = "production" )
type HookErrorHandler ¶ added in v1.0.0
HookErrorHandler observes failures from After hooks. After hooks run after state is committed, so their errors are reported here instead of changing the operation's result.
type Hooks ¶
type Hooks struct {
BeforeUserCreate func(user *User) error
AfterUserCreate func(user User) error
AfterSignIn func(data SessionData) error
AfterSignOut func(session *Session) error
AfterOAuth func(data SessionData) error
AfterEmailVerified func(user User) error
AfterPasswordReset func(user User) error
}
type Invitation ¶ added in v1.0.0
type Invitation struct {
ID string `json:"id"`
OrganizationID string `json:"organizationId"`
Email string `json:"email"`
Role string `json:"role"`
Status string `json:"status"`
InviterID string `json:"inviterId,omitempty"`
TeamID string `json:"teamId,omitempty"`
ExpiresAt time.Time `json:"expiresAt"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
Invitation invites an email address to join an organization with a role. An optional TeamID also assigns the invitee to a team on acceptance.
type Member ¶ added in v1.0.0
type Member struct {
ID string `json:"id"`
OrganizationID string `json:"organizationId"`
UserID string `json:"userId"`
Role string `json:"role"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
Member links a user to an organization with a role.
type Module ¶ added in v1.0.0
Module is an optional feature that plugs into the Canopy handler and service. The built-in features implement Module. A third-party plugin uses the same seam. New calls Init once for each module.
type ModuleKeyring ¶ added in v1.0.0
ModuleKeyring contains purpose-separated keys for one module. Current is used for new data; Previous accepts data created before a key rotation.
type OAuthCallbackInput ¶
type OAuthCallbackResult ¶ added in v1.0.0
type OAuthCallbackResult struct {
Result *SignInResult
CallbackURL string
RememberMe *bool
}
OAuthCallbackResult is the outcome of an OAuth callback. It carries the sign-in result and the redirect data for the browser flow.
type Organization ¶ added in v1.0.0
type Organization struct {
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
Organization is a tenant that groups members.
type OrganizationStore ¶ added in v1.0.0
type OrganizationStore interface {
CreateOrganization(ctx context.Context, org *Organization) error
// CreateOrganizationWithOwner creates both records atomically.
CreateOrganizationWithOwner(ctx context.Context, org *Organization, owner *Member) error
FindOrganizationByID(ctx context.Context, id string) (*Organization, error)
FindOrganizationBySlug(ctx context.Context, slug string) (*Organization, error)
ListOrganizationsForUser(ctx context.Context, userID string) ([]Organization, error)
UpdateOrganization(ctx context.Context, org *Organization) error
DeleteOrganization(ctx context.Context, id string) error
CreateMember(ctx context.Context, member *Member) error
FindMember(ctx context.Context, orgID, userID string) (*Member, error)
ListMembers(ctx context.Context, orgID string) ([]Member, error)
UpdateMember(ctx context.Context, member *Member) error
// UpdateMemberRole updates a role atomically while ensuring at least one
// member retains protectedRole.
UpdateMemberRole(ctx context.Context, member *Member, protectedRole string) error
DeleteMember(ctx context.Context, orgID, userID string) error
ClearActiveOrganization(ctx context.Context, orgID, userID string) error
// RemoveMemberAndClearSessions removes the member and clears that
// organization from their active sessions atomically.
RemoveMemberAndClearSessions(ctx context.Context, orgID, userID string, now time.Time) error
CreateInvitation(ctx context.Context, invitation *Invitation) error
FindInvitation(ctx context.Context, id string) (*Invitation, error)
ListInvitationsForOrg(ctx context.Context, orgID string) ([]Invitation, error)
UpdateInvitation(ctx context.Context, invitation *Invitation) error
// AcceptInvitation marks a pending, unexpired invitation accepted and
// creates the member atomically. An existing membership is preserved.
// When the invitation carries a TeamID it also creates the team
// membership atomically in the same operation.
AcceptInvitation(ctx context.Context, invitationID, email string, now time.Time, member *Member) error
CreateTeam(ctx context.Context, team *Team) error
FindTeamByID(ctx context.Context, id string) (*Team, error)
ListTeamsForOrg(ctx context.Context, orgID string) ([]Team, error)
UpdateTeam(ctx context.Context, team *Team) error
// DeleteTeam removes the team and its team memberships and clears the
// team from pending invitations, all atomically.
DeleteTeam(ctx context.Context, orgID, teamID string) error
// AddTeamMember creates a team membership. The caller must have already
// verified the user is a member of the team's organization.
AddTeamMember(ctx context.Context, member *TeamMember) error
FindTeamMember(ctx context.Context, teamID, userID string) (*TeamMember, error)
ListTeamMembers(ctx context.Context, teamID string) ([]TeamMember, error)
RemoveTeamMember(ctx context.Context, teamID, userID string) error
}
OrganizationStore is an optional Store capability. The organization module requires it.
type PasswordResetMessage ¶
type ProtectedMemberRemovalStore ¶ added in v1.0.1
type ProtectedMemberRemovalStore interface {
// RemoveMemberAndClearSessionsProtected removes the member and clears
// that organization from their active sessions atomically. It re-reads
// the member role inside the same transaction. It returns ErrForbidden
// when the member holds protectedRole, and ErrNotFound when the member
// does not exist.
RemoveMemberAndClearSessionsProtected(ctx context.Context, orgID, userID, protectedRole string, now time.Time) error
}
ProtectedMemberRemovalStore is an optional OrganizationStore capability. A store that implements it removes a member only when the member does not hold the protected role at commit time.
The organization module checks the role before it removes a member. That check alone is not safe, because a concurrent role change can commit between the check and the removal. An organization that loses its last owner cannot recover, because no route can grant the owner role again.
Implement this capability on every production store. The module falls back to RemoveMemberAndClearSessions when a store does not implement it, and that path keeps the race.
type ProviderTokenCodec ¶ added in v1.0.0
type ProviderTokenCodec interface {
Seal(plaintext []byte) ([]byte, error)
Open(ciphertext []byte) ([]byte, error)
}
ProviderTokenCodec encrypts provider credentials before they reach the configured store. Seal must use authenticated encryption.
type RefreshProviderTokenOutput ¶
type RefreshProviderTokenOutput struct {
AccountID string `json:"accountId"`
ProviderID string `json:"providerId"`
AccessToken string `json:"accessToken"`
RefreshToken string `json:"-"`
AccessTokenExpiresAt *time.Time `json:"accessTokenExpiresAt,omitempty"`
RefreshTokenExpiresAt *time.Time `json:"refreshTokenExpiresAt,omitempty"`
Scope string `json:"scope,omitempty"`
}
type ResetPasswordInput ¶
type Route ¶ added in v1.0.0
type Route struct {
Method string
Pattern string
Handler http.Handler
// RequireSession makes the handler resolve a session first. The
// handler returns unauthorized when no session is present. The
// session is available through SessionFromContext.
RequireSession bool
}
Route is one HTTP route that a module mounts.
type RouteModule ¶ added in v1.0.0
RouteModule is a module that mounts HTTP routes under the handler. This is an optional capability. The handler discovers it with a type assertion.
type RuntimeConfig ¶ added in v1.0.0
type RuntimeConfig struct {
Environment Environment
BasePath string
PasswordMinLength int
PasswordMaxLength int
Session sessions.Config
}
RuntimeConfig contains the non-secret settings exposed to modules.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
func (*Service) Audit ¶ added in v1.0.0
func (s *Service) Audit(ctx context.Context, event AuditEvent)
Audit emits an audit event. It satisfies the Core interface.
func (*Service) Authenticate ¶ added in v1.0.0
func (s *Service) Authenticate(r *http.Request) (*SessionData, error)
Authenticate resolves the session for a request. It reads the bearer token or the session cookie. It satisfies the Core interface.
func (*Service) CleanupExpired ¶ added in v1.0.0
CleanupExpired removes expired sessions and verification records. Call it periodically from the application's scheduler.
func (*Service) ClientIP ¶ added in v1.0.0
ClientIP returns the direct peer unless it is a configured trusted proxy. For trusted proxies it walks X-Forwarded-For from right to left.
func (*Service) Config ¶ added in v1.0.0
func (s *Service) Config() RuntimeConfig
Config returns the non-secret runtime configuration exposed to modules.
func (*Service) GetSession ¶
func (*Service) HashPassword ¶ added in v1.0.0
HashPassword hashes a password with the configured hasher.
func (*Service) IssueSession ¶ added in v1.0.0
func (s *Service) IssueSession(ctx context.Context, user User, opt SessionOptions) (*SessionData, string, error)
IssueSession creates a session for the user and returns the token. It satisfies the Core interface, so a module can complete a sign-in.
func (*Service) LinkAccount ¶ added in v1.0.0
func (s *Service) LinkAccount(ctx context.Context, identifier, value string, now time.Time, account *Account) error
LinkAccount consumes the one-time link-confirmation verification and creates the provider account for an existing user. It encrypts the provider credentials before they reach the store. It satisfies the Core interface.
func (*Service) Middleware ¶
Middleware is a deprecated alias for OptionalSession. Deprecated: use OptionalSession or RequireSession to make intent explicit.
func (*Service) OAuthCallback ¶
func (s *Service) OAuthCallback(ctx context.Context, in OAuthCallbackInput) (*OAuthCallbackResult, error)
func (*Service) OptionalSession ¶ added in v1.0.0
OptionalSession resolves a session when present and always calls next.
func (*Service) Providers ¶ added in v1.0.0
Providers returns the configured OAuth providers keyed by provider ID. The map is a defensive copy. It satisfies the Core interface.
func (*Service) RefreshProviderToken ¶
func (s *Service) RefreshProviderToken(ctx context.Context, in RefreshProviderTokenInput) (*RefreshProviderTokenOutput, error)
func (*Service) RequestPasswordReset ¶
func (s *Service) RequestPasswordReset(ctx context.Context, in RequestPasswordResetInput) error
func (*Service) RequireSession ¶ added in v1.0.0
RequireSession resolves a session and returns unauthorized without calling next when credentials are missing or invalid.
func (*Service) ResetPassword ¶
func (s *Service) ResetPassword(ctx context.Context, in ResetPasswordInput) error
func (*Service) ResolveCallbackURL ¶ added in v1.0.0
ResolveCallbackURL returns callbackURL only when it is safe to use. It satisfies the Core interface.
func (*Service) RevokeUserSessions ¶
func (*Service) SendEmailVerification ¶
func (s *Service) SendEmailVerification(ctx context.Context, in SendEmailVerificationInput) error
func (*Service) SignInEmail ¶
func (s *Service) SignInEmail(ctx context.Context, in SignInEmailInput) (*SignInResult, error)
func (*Service) SignInSocial ¶
func (s *Service) SignInSocial(ctx context.Context, in SignInSocialInput) (*SignInSocialOutput, string, error)
func (*Service) SignUpEmail ¶
func (s *Service) SignUpEmail(ctx context.Context, in SignUpEmailInput) (*SessionData, string, error)
func (*Service) Store ¶ added in v1.0.0
Store returns the configured store. It satisfies the Core interface.
func (*Service) UpdateLinkedAccount ¶ added in v1.0.0
UpdateLinkedAccount refreshes the credentials of a linked provider account. It keeps the stored credentials when a replacement value is empty. It satisfies the Core interface.
func (*Service) VerifyEmail ¶
type Session ¶
type Session struct {
ID string `json:"id"`
UserID string `json:"userId"`
Token string `json:"-"`
ExpiresAt time.Time `json:"expiresAt"`
IPAddress string `json:"ipAddress,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
ActiveOrganizationID string `json:"activeOrganizationId,omitempty"`
ImpersonatedBy string `json:"impersonatedBy,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type SessionData ¶
func SessionFromContext ¶
func SessionFromContext(ctx context.Context) (*SessionData, bool)
type SessionOptions ¶ added in v1.0.0
type SessionOptions struct {
RememberMe *bool
IPAddress string
UserAgent string
ActiveOrganizationID string
ImpersonatedBy string
}
SessionOptions carries the values that IssueSession needs. A module sets ActiveOrganizationID or ImpersonatedBy when it applies.
type SessionValidator ¶ added in v1.0.0
type SessionValidator interface {
ValidateSession(ctx context.Context, data *SessionData) error
}
SessionValidator checks or refreshes module-owned session state whenever the core resolves a session. The organization module uses it to prevent a stale active organization from outliving membership.
type SignInEmailInput ¶
type SignInInterceptor ¶ added in v1.0.0
type SignInInterceptor interface {
AfterPrimaryAuth(ctx context.Context, user User) (*StepUpChallenge, error)
}
SignInInterceptor is a module that can pause session creation after primary authentication. This is an optional capability. The two-factor module uses it to require a second step.
type SignInResult ¶ added in v1.0.0
type SignInResult struct {
Session *SessionData
Token string
Challenge *StepUpChallenge
}
SignInResult is the outcome of a sign-in attempt. Exactly one of Session or Challenge is set. Session is set on a full sign-in. Challenge is set when a second authentication step is required.
func (SignInResult) TwoFactorRequired ¶ added in v1.0.0
func (r SignInResult) TwoFactorRequired() bool
TwoFactorRequired reports if the sign-in needs a second step.
type SignInSocialInput ¶
type SignInSocialOutput ¶
type SignInSocialOutput struct {
URL string `json:"url"`
}
type SignUpEmailInput ¶
type StepUpChallenge ¶ added in v1.0.0
StepUpChallenge tells the client that a second authentication step is required. Token is opaque and short-lived. Methods lists the accepted second factors, for example "totp" or "backup_code".
type Store ¶
type Store interface {
FindUserByID(ctx context.Context, id string) (*User, error)
FindUserByEmail(ctx context.Context, email string) (*User, error)
CreateUser(ctx context.Context, user *User) error
UpdateUser(ctx context.Context, user *User) error
FindAccount(ctx context.Context, providerID, accountID string) (*Account, error)
FindAccountByUserProvider(ctx context.Context, userID, providerID string) (*Account, error)
CreateAccount(ctx context.Context, account *Account) error
UpdateAccount(ctx context.Context, account *Account) error
CreateSession(ctx context.Context, session *Session) error
FindSessionByToken(ctx context.Context, token string) (*SessionData, error)
UpdateSession(ctx context.Context, session *Session) error
DeleteSessionByToken(ctx context.Context, token string) error
DeleteUserSessions(ctx context.Context, userID string) error
DeleteExpiredSessions(ctx context.Context, now time.Time) error
CreateVerification(ctx context.Context, verification *Verification) error
ReplaceVerification(ctx context.Context, verification *Verification) error
ConsumeVerification(ctx context.Context, identifier, value string, now time.Time) (*Verification, error)
DeleteVerificationsByIdentifier(ctx context.Context, identifier string) error
DeleteExpiredVerifications(ctx context.Context, now time.Time) error
}
type Team ¶ added in v1.0.0
type Team struct {
ID string `json:"id"`
OrganizationID string `json:"organizationId"`
Name string `json:"name"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
Team groups organization members for scoped access. A team belongs to exactly one organization.
type TeamMember ¶ added in v1.0.0
type TeamMember struct {
ID string `json:"id"`
TeamID string `json:"teamId"`
OrganizationID string `json:"organizationId"`
UserID string `json:"userId"`
CreatedAt time.Time `json:"createdAt"`
}
TeamMember links an organization member to a team.
type TwoFactor ¶ added in v1.0.0
type TwoFactor struct {
UserID string
Secret string
Enabled bool
// LastTOTPStep is the most recent accepted TOTP counter. A new code must
// have a greater counter to prevent replay.
LastTOTPStep int64
CreatedAt time.Time
UpdatedAt time.Time
}
TwoFactor is the stored two-factor state for a user. Secret is the encrypted TOTP secret. The two-factor module owns the encryption.
type TwoFactorStore ¶ added in v1.0.0
type TwoFactorStore interface {
GetTwoFactor(ctx context.Context, userID string) (*TwoFactor, error)
UpsertTwoFactor(ctx context.Context, tf *TwoFactor) error
// EnableTwoFactor stores enabled state and replaces backup codes
// atomically.
EnableTwoFactor(ctx context.Context, tf *TwoFactor, codeHashes []string) error
DeleteTwoFactor(ctx context.Context, userID string) error
// ReplaceBackupCodes replaces all backup code hashes for the user.
ReplaceBackupCodes(ctx context.Context, userID string, codeHashes []string) error
// ConsumeBackupCode removes one backup code hash. It reports if a
// code was removed. The removal must be atomic.
ConsumeBackupCode(ctx context.Context, userID, codeHash string) (bool, error)
// ConsumeTOTPStep records counter when it is newer than the last accepted
// counter. It must compare and update atomically.
ConsumeTOTPStep(ctx context.Context, userID string, counter int64) (bool, error)
}
TwoFactorStore is an optional Store capability. The two-factor module requires it. A store advertises it by implementing these methods.
type User ¶
type User struct {
ID string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
EmailVerified bool `json:"emailVerified"`
Image string `json:"image,omitempty"`
Role string `json:"role,omitempty"`
Banned bool `json:"banned"`
BanReason string `json:"banReason,omitempty"`
BanExpiresAt *time.Time `json:"banExpiresAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type ValidationError ¶ added in v1.0.0
ValidationError describes invalid request fields while remaining compatible with errors.Is(err, ErrInvalidInput).
func (*ValidationError) Error ¶ added in v1.0.0
func (e *ValidationError) Error() string
func (*ValidationError) Unwrap ¶ added in v1.0.0
func (e *ValidationError) Unwrap() error
type Verification ¶
type VerifyEmailInput ¶
type VerifyEmailInput struct {
Token string
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package accountlink adds an explicit account-linking confirmation flow to Canopy.
|
Package accountlink adds an explicit account-linking confirmation flow to Canopy. |
|
adapters
|
|
|
chi
module
|
|
|
echo
module
|
|
|
gin
module
|
|
|
Package admin adds administrator operations to Canopy.
|
Package admin adds administrator operations to Canopy. |
|
Package oauth defines provider interfaces and shared OAuth profile types used by Canopy.
|
Package oauth defines provider interfaces and shared OAuth profile types used by Canopy. |
|
Package organization adds organizations, members, roles, and invitations to Canopy.
|
Package organization adds organizations, members, roles, and invitations to Canopy. |
|
Package password provides password hashing interfaces and Canopy's default Argon2id implementation.
|
Package password provides password hashing interfaces and Canopy's default Argon2id implementation. |
|
providers
|
|
|
apple
Package apple provides Canopy's Apple OAuth provider implementation.
|
Package apple provides Canopy's Apple OAuth provider implementation. |
|
google
Package google provides Canopy's Google OAuth provider implementation.
|
Package google provides Canopy's Google OAuth provider implementation. |
|
Package sessions provides session cookie configuration and helpers for Canopy's database-backed opaque sessions.
|
Package sessions provides session cookie configuration and helpers for Canopy's database-backed opaque sessions. |
|
store
|
|
|
memory
Package memory is an in-memory canopy.Store.
|
Package memory is an in-memory canopy.Store. |
|
postgres
Package postgres provides a Postgres Store implementation and schema migration for Canopy.
|
Package postgres provides a Postgres Store implementation and schema migration for Canopy. |
|
Package twofactor adds TOTP two-factor authentication to Canopy.
|
Package twofactor adds TOTP two-factor authentication to Canopy. |