Documentation
¶
Overview ¶
Package betterauth provides an embeddable, net/http-compatible authentication server for Go applications.
Index ¶
- Constants
- Variables
- func HashToken(raw string) string
- type AESGCMTokenCipher
- type AccountManagementConfig
- type AdapterCapabilities
- type AdminConfig
- type AdminRoleResolver
- type Argon2Params
- type Argon2idVerifier
- type AuditEvent
- type BackgroundTask
- type BackgroundTaskRunner
- type ChangePasswordParams
- type Clock
- type Config
- type CookieConfig
- type CountQuery
- type CreateEmailUserParams
- type CreateQuery
- type CryptoTokenSource
- type DatabaseAdapter
- type DatabaseHook
- type DatabaseHookContext
- type DatabaseHookHandler
- type DatabaseOperation
- type DeleteQuery
- type DomainEvent
- type EmailPasswordConfig
- type EmailVerificationConfig
- type EndpointValidator
- type EndpointValidatorFunc
- type Error
- type ErrorCode
- type EventHandler
- type FieldSchema
- type FieldType
- type FieldValidation
- type FindManyQuery
- type FindOneQuery
- type HookContext
- type HookMatcher
- type ImpersonationAuthorizer
- type IncrementQuery
- type IndexSchema
- type InlineBackgroundTasks
- type IssuedSession
- type Join
- type JoinRelation
- type Mail
- type Mailer
- type ModelSchema
- type NopRateLimiter
- type OAuthAccount
- type OAuthProfile
- type OAuthProvider
- type OAuthProviderSignUpPolicy
- type OAuthResult
- type OAuthState
- type OAuthTokenRefresher
- type OAuthUpsertPolicy
- type ObjectValidator
- type OneTimePurpose
- type OneTimeToken
- type OutboxDispatcher
- type PasswordCredential
- type PasswordVerification
- type PasswordVerifier
- type Plugin
- type PluginAfterHook
- type PluginBeforeHook
- type PluginEndpoint
- type PluginEndpointHandler
- type PluginInit
- type PluginInitContext
- type PluginInitResult
- type PluginMiddleware
- type PluginRateLimitRule
- type PluginResponse
- type ProviderTokens
- type RateLimitDecision
- type RateLimitRequest
- type RateLimiter
- type Record
- type RequestHook
- type RequestMetadata
- type ResourceIDSource
- type ResourceOwnershipConfig
- type ResponseHook
- type Schema
- type SchemaConfigurableAdapter
- type Server
- func (s *Server) Handler() http.Handler
- func (s *Server) ResolveSession(ctx context.Context, r *http.Request) (SessionResult, error)
- func (s *Server) Schema() Schema
- func (s *Server) SetPassword(ctx context.Context, userID, password string) error
- func (s *Server) VerifyPassword(ctx context.Context, userID, password string) (bool, error)
- type ServerHooks
- type Session
- type SessionResult
- type Sort
- type StoredOAuthAccount
- type StringMode
- type SyntheticUserFactory
- type SyntheticUserInput
- type TokenCipher
- type TokenSource
- type TrustedOriginResolver
- type TrustedOriginResolverFunc
- type TrustedProviderResolver
- type TrustedProviderResolverFunc
- type UpdateQuery
- type User
- type UserDeletionHook
- type UserLifecycleHook
- type UserManagementConfig
- type ValidationKind
- type Where
- type WhereConnector
- type WhereOperator
Constants ¶
const ( ModelUser = "user" ModelSession = "session" ModelAccount = "account" ModelVerification = "verification" ModelAuditEvent = "auditEvent" ModelOutboxEvent = "outboxEvent" )
const ( PurposePasswordReset OneTimePurpose = "password_reset" PurposeEmailVerify OneTimePurpose = "email_verify" PurposeEmailChange OneTimePurpose = "email_change" PurposeEmailChangeConfirmation OneTimePurpose = "email_change_confirmation" PurposeUserDeletion OneTimePurpose = "user_deletion" PurposeOAuthState OneTimePurpose = "oauth_state" ProviderGoogle = "google" EventUserCreated = "user.created" AuditImpersonationStart = "admin.impersonation.started" AuditImpersonationStop = "admin.impersonation.stopped" )
const ( // APIVersion is the stable HTTP API version implemented by this module. APIVersion = "v1" // Version is the library's semantic version. It is replaced by the release // process for tagged builds. Version = "0.1.0-dev" )
Variables ¶
var ( // ErrNotFound is returned by adapters for absent records. ErrNotFound = errors.New("betterauth: not found") // ErrConflict is returned when a unique identity already exists. ErrConflict = errors.New("betterauth: conflict") // ErrReplay is returned when a single-use value was already consumed. ErrReplay = errors.New("betterauth: replay") // ErrAccountNotLinked is returned when a same-email OAuth identity exists // but the configured implicit-linking policy denies attaching it. ErrAccountNotLinked = errors.New("betterauth: account not linked") // ErrSignUpDisabled is returned when an OAuth provider is allowed to sign // in existing identities but not create a new user for this request. ErrSignUpDisabled = errors.New("betterauth: oauth sign up disabled") )
var ErrNoSession = errors.New("betterauth: no session")
ErrNoSession means the request does not carry a currently valid session. It covers missing or invalid cookies, absent users or sessions, expired or revoked sessions, and disabled users.
Functions ¶
Types ¶
type AESGCMTokenCipher ¶
type AESGCMTokenCipher struct {
// contains filtered or unexported fields
}
func NewAESGCMTokenCipher ¶
func NewAESGCMTokenCipher(key []byte) (*AESGCMTokenCipher, error)
type AccountManagementConfig ¶
type AccountManagementConfig struct {
// UpdateAccountOnSignIn controls whether returning-provider sign-in writes
// the latest provider tokens. Nil defaults to true.
UpdateAccountOnSignIn *bool
// LinkingEnabled controls explicit and implicit provider linking. Nil
// defaults to true, matching Better Auth v1.6.
LinkingEnabled *bool
// DisableImplicitLinking prevents a social sign-in from attaching a new
// provider identity to an existing same-email user. Explicit link-social
// remains available when linking itself is enabled.
DisableImplicitLinking bool
// TrustedProviders is an immutable allowlist whose configured provider is
// accepted as verified identity evidence even when its profile omits an
// emailVerified flag.
TrustedProviders []string
// TrustedProviderResolver is the request-dependent v1.6 alternative to the
// static TrustedProviders list. Configuring both fails closed.
TrustedProviderResolver TrustedProviderResolver
// RequireLocalEmailVerified protects implicit same-email linking. Nil
// defaults to true.
RequireLocalEmailVerified *bool
// UpdateUserInfoOnLink copies non-identity name/image fields from a newly
// linked provider profile. Email and verification state are never changed.
UpdateUserInfoOnLink bool
// AllowUnlinkingAll permits removal of the final sign-in method. The secure
// default is false so a user cannot accidentally make their account
// unreachable.
AllowUnlinkingAll bool
// AllowLinkingDifferentEmails permits an authenticated user to link a
// provider identity whose verified email differs from the current user.
AllowLinkingDifferentEmails bool
}
type AdapterCapabilities ¶
type AdapterCapabilities struct {
JSON bool
Dates bool
Booleans bool
Arrays bool
NumericIDs bool
UUIDs bool
Joins bool
Transactions bool
}
AdapterCapabilities describe native storage behavior.
type AdminConfig ¶
type AdminConfig struct {
DefaultRole string
AdminRoles []string
AdminUserIDs []string
RoleResolver AdminRoleResolver
AllowImpersonatingAdmins bool
}
AdminConfig provides the Better Auth v1.6 administrator-selection options that govern core impersonation. Full admin CRUD/ban endpoints remain a separate plugin surface.
type AdminRoleResolver ¶
AdminRoleResolver returns application-owned roles for one user. It is invoked per request and must be concurrency-safe; roles are never cached on the shared server.
type Argon2Params ¶
type Argon2Params struct {
Memory uint32
Iterations uint32
Parallelism uint8
SaltLength uint32
KeyLength uint32
}
func DefaultArgon2Params ¶
func DefaultArgon2Params() Argon2Params
type Argon2idVerifier ¶
type Argon2idVerifier struct {
Params Argon2Params
MaxPassword int
}
Argon2idVerifier is the native password format.
func NewArgon2idVerifier ¶
func NewArgon2idVerifier(params Argon2Params, maxPassword int) (*Argon2idVerifier, error)
func (*Argon2idVerifier) Verify ¶
func (v *Argon2idVerifier) Verify(ctx context.Context, encoded, password string) (PasswordVerification, error)
type AuditEvent ¶
type AuditEvent struct {
ID string
SchemaVersion int
Action string
ActorUserID string
SubjectUserID string
SessionID string
OccurredAt time.Time
Request RequestMetadata
Details map[string]string
}
AuditEvent is an append-only security record.
type BackgroundTask ¶
BackgroundTask is submitted through an application-owned runner. The request context passed to Submit is detached from cancellation before Run.
type BackgroundTaskRunner ¶
type BackgroundTaskRunner interface {
Submit(context.Context, BackgroundTask) error
}
BackgroundTaskRunner accepts request-detached non-critical work.
type ChangePasswordParams ¶
type Config ¶
type Config struct {
BasePath string
PublicURL string
TrustedOrigins []string
TrustedOriginResolver TrustedOriginResolver
Database DatabaseAdapter
Schema Schema
Mailer Mailer
RateLimiter RateLimiter
ImpersonationAuthorizer ImpersonationAuthorizer
Passwords PasswordVerifier
Clock Clock
Tokens TokenSource
ProviderTokenCipher TokenCipher
SocialProviders map[string]OAuthProvider
AllowedRedirectURLs []string
Cookie CookieConfig
Account AccountManagementConfig
Admin AdminConfig
User UserManagementConfig
EmailPassword EmailPasswordConfig
EmailVerification EmailVerificationConfig
SessionDuration time.Duration
SessionFreshAge time.Duration
ImpersonationDuration time.Duration
PasswordResetTTL time.Duration
EmailVerificationTTL time.Duration
DeleteUserTTL time.Duration
OAuthStateTTL time.Duration
ProviderTimeout time.Duration
MaxRequestBytes int64
MinPasswordBytes int
MaxPasswordBytes int
TrustProxyHeaders bool
Plugins []Plugin
Hooks ServerHooks
BackgroundTasks BackgroundTaskRunner
MaxResponseBytes int64
}
type CookieConfig ¶
type CountQuery ¶
type CreateEmailUserParams ¶
type CreateEmailUserParams struct {
User User
PasswordHash string
Session Session
CreateSession bool
Event DomainEvent
}
type CreateQuery ¶
type CryptoTokenSource ¶
type CryptoTokenSource struct{}
type DatabaseAdapter ¶
type DatabaseAdapter interface {
ID() string
Capabilities() AdapterCapabilities
Create(context.Context, CreateQuery) (Record, error)
FindOne(context.Context, FindOneQuery) (Record, error)
FindMany(context.Context, FindManyQuery) ([]Record, error)
Count(context.Context, CountQuery) (int64, error)
Update(context.Context, UpdateQuery) (Record, error)
UpdateMany(context.Context, UpdateQuery) (int64, error)
Delete(context.Context, DeleteQuery) error
DeleteMany(context.Context, DeleteQuery) (int64, error)
ConsumeOne(context.Context, DeleteQuery) (Record, error)
IncrementOne(context.Context, IncrementQuery) (Record, error)
Transaction(context.Context, func(DatabaseAdapter) error) error
}
DatabaseAdapter follows Better Auth's database adapter vocabulary. Single-row update/delete methods reject an empty predicate.
func WrapDatabaseAdapter ¶
func WrapDatabaseAdapter(inner DatabaseAdapter, schema Schema) (DatabaseAdapter, error)
WrapDatabaseAdapter applies model/field mapping and capability-aware value transforms to an adapter. Server construction applies this automatically.
type DatabaseHook ¶
type DatabaseHook struct {
Model string
Operations []DatabaseOperation
Before DatabaseHookHandler
After DatabaseHookHandler
}
DatabaseHook registers mutation callbacks for one model or "*" and an optional operation allowlist.
type DatabaseHookContext ¶
type DatabaseHookContext struct {
Operation DatabaseOperation
Model string
Where []Where
Data Record
Increment map[string]float64
Result Record
Count int64
}
DatabaseHookContext contains cloned inputs and outputs for one adapter mutation. Before hooks may replace Where, Data, and Increment.
type DatabaseHookHandler ¶
type DatabaseHookHandler func(context.Context, *DatabaseHookContext) error
DatabaseHookHandler handles one logical adapter mutation.
type DatabaseOperation ¶
type DatabaseOperation string
DatabaseOperation identifies a logical adapter mutation.
const ( DatabaseCreate DatabaseOperation = "create" DatabaseUpdate DatabaseOperation = "update" DatabaseUpdateMany DatabaseOperation = "updateMany" DatabaseDelete DatabaseOperation = "delete" DatabaseDeleteMany DatabaseOperation = "deleteMany" DatabaseConsumeOne DatabaseOperation = "consumeOne" DatabaseIncrementOne DatabaseOperation = "incrementOne" )
Supported database hook operations.
type DeleteQuery ¶
type DomainEvent ¶
type DomainEvent struct {
ID string
SchemaVersion int
Name string
AggregateID string
OccurredAt time.Time
Payload map[string]string
}
DomainEvent is persisted to an outbox for idempotent consumers.
type EmailPasswordConfig ¶
type EmailPasswordConfig struct {
// DisableSignUp rejects new email/password registrations.
DisableSignUp bool
// AutoSignIn controls session creation after signup. Nil defaults to true.
// New copies the pointed-to value so later caller mutation cannot change a
// running server.
AutoSignIn *bool
// RequireEmailVerification suppresses signup sessions and blocks credential
// sign-in until the single-use verification token is consumed.
RequireEmailVerification bool
// RevokeSessionsOnPasswordReset atomically revokes every active user
// session when a reset token is consumed. Better Auth defaults to false.
RevokeSessionsOnPasswordReset bool
// OnPasswordReset runs after the password is durably replaced and before
// optional session revocation.
OnPasswordReset UserLifecycleHook
// OnExistingUserSignUp receives an existing user only through the
// application-owned background runner. Its result never changes the
// enumeration-resistant synthetic response.
OnExistingUserSignUp UserLifecycleHook
// CustomSyntheticUser adds application-defined public fields to protected
// duplicate-signup responses.
CustomSyntheticUser SyntheticUserFactory
}
EmailPasswordConfig controls the Better Auth v1.6 email/password lifecycle. AutoSignIn is optional because the upstream default is true.
type EmailVerificationConfig ¶
type EmailVerificationConfig struct {
SendOnSignUp *bool
SendOnSignIn bool
AutoSignInAfterVerification bool
BeforeVerification UserLifecycleHook
AfterVerification UserLifecycleHook
}
EmailVerificationConfig controls the Better Auth v1.6 verification lifecycle. SendOnSignUp is optional because its default follows EmailPassword.RequireEmailVerification.
type EndpointValidator ¶
EndpointValidator validates a decoded endpoint input. Body validators receive JSON-compatible values; query validators receive url.Values. Implementations must be concurrency-safe.
type EndpointValidatorFunc ¶
EndpointValidatorFunc adapts a function to EndpointValidator.
func (EndpointValidatorFunc) Validate ¶
func (validator EndpointValidatorFunc) Validate(value any) error
type Error ¶
type Error struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
Status int `json:"-"`
RetryAfter time.Duration `json:"-"`
RequestID string `json:"requestId,omitempty"`
// contains filtered or unexported fields
}
Error is a structured public-safe authentication error.
type ErrorCode ¶
type ErrorCode string
const ( CodeBadRequest ErrorCode = "bad_request" CodeValidation ErrorCode = "validation_error" CodeInvalidEmail ErrorCode = "invalid_email" CodePasswordTooShort ErrorCode = "password_too_short" CodePasswordTooLong ErrorCode = "password_too_long" CodeInvalidCredentials ErrorCode = "invalid_credentials" CodeEmailNotVerified ErrorCode = "email_not_verified" CodeEmailMismatch ErrorCode = "email_mismatch" CodeEmailAlreadyVerified ErrorCode = "email_already_verified" CodeInvalidPassword ErrorCode = "invalid_password" CodeCredentialNotFound ErrorCode = "credential_account_not_found" CodeAccountNotFound ErrorCode = "account_not_found" CodeUnlinkLastAccount ErrorCode = "failed_to_unlink_last_account" CodeLinkingNotAllowed ErrorCode = "linking_not_allowed" CodeLinkingDifferentEmails ErrorCode = "linking_different_emails_not_allowed" CodeAccountLinkedElsewhere ErrorCode = "account_already_linked_to_different_user" CodeAccountNotLinked ErrorCode = "account_not_linked" CodeOAuthSignUpDisabled ErrorCode = "oauth_sign_up_disabled" CodeProviderNotSupported ErrorCode = "provider_not_supported" CodeTokenRefreshUnsupported ErrorCode = "token_refresh_not_supported" CodeRefreshTokenNotFound ErrorCode = "refresh_token_not_found" CodeFailedRefreshToken ErrorCode = "failed_to_refresh_access_token" CodeSignUpDisabled ErrorCode = "email_password_sign_up_disabled" CodeUserAlreadyExists ErrorCode = "user_already_exists_use_another_email" CodeForbidden ErrorCode = "forbidden" CodeCannotImpersonateAdmins ErrorCode = "cannot_impersonate_admins" CodeCannotImpersonateUsers ErrorCode = "cannot_impersonate_users" CodeSessionNotFresh ErrorCode = "session_not_fresh" CodeNotFound ErrorCode = "not_found" CodeConflict ErrorCode = "conflict" CodeRateLimited ErrorCode = "rate_limited" CodeInvalidOrigin ErrorCode = "invalid_origin" CodeInvalidCSRF ErrorCode = "invalid_csrf" CodeInvalidToken ErrorCode = "invalid_or_expired_token" CodeProviderFailure ErrorCode = "provider_failure" CodeMethodNotAllowed ErrorCode = "method_not_allowed" CodeInternal ErrorCode = "internal_error" )
type EventHandler ¶
type EventHandler interface {
HandleEvent(context.Context, DomainEvent) error
}
EventHandler receives durable, versioned outbox events. Delivery is at-least-once; handlers must use DomainEvent.ID as their idempotency key.
type FieldSchema ¶
type FieldValidation ¶
type FieldValidation struct {
Kind ValidationKind
Required bool
Nullable bool
MinLength int
MaxLength int
Enum []string
}
FieldValidation declares a strict, dependency-free input rule.
type FindManyQuery ¶
type FindOneQuery ¶
type HookContext ¶
type HookContext struct {
Context context.Context
Request *http.Request
Path string
PluginID string
Params map[string]string
Headers http.Header
Query url.Values
Body any
RawBody []byte
Database DatabaseAdapter
Clock Clock
BaseURL string
Schema Schema
Cookies CookieConfig
Passwords PasswordVerifier
TrustedOrigins []string
SessionFreshAge time.Duration
Session *Session
User *User
Response *PluginResponse
Failure error
GenerateID func() (string, error)
GenerateToken func(int) (string, error)
IsTrustedOrigin func(string) bool
ValidateCSRF func() error
IssueSession func(string) (*IssuedSession, error)
// AuthenticateOAuth completes a plugin-owned, externally verified identity
// transition through the core account/session store. Plugins must validate
// issuer, audience, nonce, signature, and verified email before calling it.
AuthenticateOAuth func(OAuthProfile, ProviderTokens) (*IssuedSession, bool, error)
BackgroundTasks BackgroundTaskRunner
// contains filtered or unexported fields
}
HookContext is unique to one request.
func (*HookContext) RunInBackground ¶
func (ctx *HookContext) RunInBackground(task BackgroundTask) error
type HookMatcher ¶
type HookMatcher func(*HookContext) bool
HookMatcher selects requests using their normalized path and request-scoped context. A nil matcher selects every request.
type ImpersonationAuthorizer ¶
ImpersonationAuthorizer decides whether an authenticated actor may impersonate a subject. Returning an error denies the operation.
type IncrementQuery ¶
type IndexSchema ¶
IndexSchema declares a compound adapter index using logical field names.
type InlineBackgroundTasks ¶
type InlineBackgroundTasks struct{}
InlineBackgroundTasks runs submitted work synchronously with cancellation detached. Applications can replace it with a durable asynchronous runner.
func (InlineBackgroundTasks) Submit ¶
func (InlineBackgroundTasks) Submit(ctx context.Context, task BackgroundTask) error
type IssuedSession ¶
type IssuedSession struct {
Session Session `json:"session"`
User User `json:"user"`
// contains filtered or unexported fields
}
IssuedSession is the result of a plugin authentication transition. Bearer values remain private and can only be attached to a response through Apply.
func (*IssuedSession) Apply ¶
func (issued *IssuedSession) Apply(response *PluginResponse) error
Apply attaches the secure session transition to a plugin response. It may be called once; a second call fails instead of duplicating bearer cookies.
type JoinRelation ¶
type JoinRelation string
const ( JoinOneToOne JoinRelation = "one-to-one" JoinOneToMany JoinRelation = "one-to-many" JoinManyToMany JoinRelation = "many-to-many" )
type Mail ¶
Mail contains a transactional authentication message. Implementations should render their own templates; Token and ActionURL are secrets and must not be logged.
type ModelSchema ¶
type ModelSchema struct {
ModelName string
Fields map[string]FieldSchema
Indexes []IndexSchema
}
type NopRateLimiter ¶
type NopRateLimiter struct{}
NopRateLimiter permits every request.
func (NopRateLimiter) Allow ¶
func (NopRateLimiter) Allow(context.Context, RateLimitRequest) (RateLimitDecision, error)
type OAuthAccount ¶
type OAuthAccount struct {
ID string `json:"id"`
UserID string `json:"userId"`
Provider string `json:"providerId"`
ProviderAccountID string `json:"accountId"`
Scope string `json:"scope,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
OAuthAccount binds a provider identity to a user.
type OAuthProfile ¶
type OAuthProfile struct {
Provider string
ProviderAccountID string
Email string
EmailVerified bool
Name string
ImageURL string
}
OAuthProfile is the provider-neutral verified profile used for account creation and linking.
type OAuthProvider ¶
type OAuthProvider interface {
AuthorizationURL(state, codeChallenge, nonce, redirectURI string) (string, error)
Exchange(context.Context, string, string, string, string) (OAuthResult, error)
}
OAuthProvider performs provider communication behind bounded contexts.
type OAuthProviderSignUpPolicy ¶
OAuthProviderSignUpPolicy is an optional provider capability matching Better Auth v1.6's per-provider signup controls. Implementations that do not expose it retain the historical behavior of allowing implicit signup.
type OAuthResult ¶
type OAuthResult struct {
Profile OAuthProfile
Tokens ProviderTokens
}
type OAuthState ¶
type OAuthState struct {
ID string
Hash string
PKCEVerifier string
Nonce string
RedirectURI string
ReturnTo string
ErrorReturnTo string
NewUserReturnTo string
LinkUserID string
RequestSignUp bool
ExpiresAt time.Time
CreatedAt time.Time
}
OAuthState is a purpose-specific single-use authorization transaction.
type OAuthTokenRefresher ¶
type OAuthTokenRefresher interface {
Refresh(context.Context, string) (ProviderTokens, error)
}
OAuthTokenRefresher is implemented by providers that can exchange a refresh token for a new token set.
type OAuthUpsertPolicy ¶
type OAuthUpsertPolicy struct {
AllowImplicitLink bool
RequireLocalVerification bool
UpdateUserInfoOnLink bool
UpdateAccountOnSignIn bool
AllowSignUp bool
}
OAuthUpsertPolicy is the immutable store policy for an OAuth callback. It is evaluated inside the same transaction that creates or links the account.
type ObjectValidator ¶
type ObjectValidator struct {
Fields map[string]FieldValidation
AllowUnknown bool
}
ObjectValidator validates JSON objects and URL query values. Unknown fields are rejected unless AllowUnknown is explicitly enabled.
func (ObjectValidator) Validate ¶
func (validator ObjectValidator) Validate(value any) error
func (ObjectValidator) ValidateConfiguration ¶
func (validator ObjectValidator) ValidateConfiguration() error
ValidateConfiguration enables fail-closed validation during server construction.
type OneTimePurpose ¶
type OneTimePurpose string
OneTimePurpose prevents token use across recovery flows.
type OneTimeToken ¶
type OneTimeToken struct {
ID string
UserID string
Hash string
Purpose OneTimePurpose
ExpiresAt time.Time
CreatedAt time.Time
Metadata map[string]string
}
OneTimeToken is a hash-at-rest, expiring, single-use token record.
type OutboxDispatcher ¶
type OutboxDispatcher struct {
Database DatabaseAdapter
Handler EventHandler
Clock Clock
BatchSize int
}
type PasswordCredential ¶
PasswordCredential contains a user's encoded password hash.
type PasswordVerification ¶
type PasswordVerifier ¶
type PasswordVerifier interface {
Hash(context.Context, string) (string, error)
Verify(context.Context, string, string) (PasswordVerification, error)
}
PasswordVerifier supports native formats and optional migration bridges.
type Plugin ¶
type Plugin struct {
ID string
Dependencies []string
Init PluginInit
Schema Schema
Endpoints []PluginEndpoint
Middlewares []PluginMiddleware
Before []PluginBeforeHook
After []PluginAfterHook
OnRequest RequestHook
OnResponse ResponseHook
TrustedOrigins []string
RateLimits []PluginRateLimitRule
DatabaseHooks []DatabaseHook
}
Plugin is an immutable descriptor compiled during New. Callbacks must be concurrency-safe and must not retain HookContext values.
type PluginAfterHook ¶
type PluginAfterHook struct {
Matcher HookMatcher
Handler ResponseHook
}
PluginAfterHook runs after a matching endpoint has returned a response.
type PluginBeforeHook ¶
type PluginBeforeHook struct {
Matcher HookMatcher
Handler RequestHook
}
PluginBeforeHook runs immediately before a matching endpoint.
type PluginEndpoint ¶
type PluginEndpoint struct {
Name string
Path string
Method string
SkipOriginCheck bool
// AllowNonKebabPath permits protocol-mandated case-sensitive literals such
// as SCIM's ServiceProviderConfig. Ordinary plugin routes should remain
// lowercase kebab-case.
AllowNonKebabPath bool
Use []RequestHook
BodyValidator EndpointValidator
QueryValidator EndpointValidator
Handler PluginEndpointHandler
}
PluginEndpoint declares a collision-checked HTTP route relative to the configured authentication base path. SkipOriginCheck is only for non-browser protocol callbacks or bearer-authenticated endpoints; enabling it does not skip endpoint middleware, validators, hooks, or rate limits.
type PluginEndpointHandler ¶
type PluginEndpointHandler func(*HookContext) (*PluginResponse, error)
PluginEndpointHandler serves one plugin endpoint.
type PluginInit ¶
type PluginInit func(PluginInitContext) (PluginInitResult, error)
PluginInit initializes a plugin once during New.
type PluginInitContext ¶
type PluginInitContext struct {
PluginID string
BaseURL string
Database DatabaseAdapter
Schema Schema
TrustedOrigins []string
}
PluginInitContext contains immutable construction-time capabilities.
type PluginInitResult ¶
PluginInitResult contains validated contributions produced at construction.
type PluginMiddleware ¶
type PluginMiddleware struct {
Matcher HookMatcher
Handler RequestHook
}
PluginMiddleware runs before endpoint-specific middleware and before hooks.
type PluginRateLimitRule ¶
type PluginRateLimitRule struct {
Matcher HookMatcher
Action string
AccountKey func(*HookContext) string
Window time.Duration
Max int
}
PluginRateLimitRule adds a matcher-specific rule to the configured limiter.
type PluginResponse ¶
func CSRFMiddleware ¶
func CSRFMiddleware(context *HookContext) (*PluginResponse, error)
CSRFMiddleware enforces the configured double-submit CSRF token. Use it on state-changing plugin endpoints that authenticate with a session cookie. Trusted-origin enforcement still runs independently before plugin code.
func FreshSessionMiddleware ¶
func FreshSessionMiddleware(context *HookContext) (*PluginResponse, error)
FreshSessionMiddleware requires a session created within the server's configured SessionFreshAge. Plugins should use it for credential enrollment and other sensitive account mutations.
func JSONResponse ¶
func JSONResponse(status int, value any) (*PluginResponse, error)
JSONResponse creates a JSON plugin response.
func SessionMiddleware ¶
func SessionMiddleware(context *HookContext) (*PluginResponse, error)
SessionMiddleware rejects requests without an active session. It can be used in PluginEndpoint.Use or as a plugin middleware handler.
func (*PluginResponse) DecodeJSON ¶
func (response *PluginResponse) DecodeJSON(dst any) error
DecodeJSON decodes a plugin response body and rejects unknown fields.
func (*PluginResponse) SetCookie ¶
func (response *PluginResponse) SetCookie(cookie *http.Cookie) error
SetCookie appends a secure, host-only cookie to a plugin response. Plugin cookies use the __Host- prefix so they cannot be scoped to a parent domain or a path outside the authentication server.
func (*PluginResponse) SetJSON ¶
func (response *PluginResponse) SetJSON(value any) error
SetJSON replaces a plugin response body with encoded JSON.
type ProviderTokens ¶
type RateLimitDecision ¶
type RateLimitRequest ¶
type RateLimitRequest struct {
Action string
IP string
AccountKey string
Window time.Duration
Max int
}
RateLimitRequest is intentionally small so limiters can map it to local policies without receiving credentials.
type RateLimiter ¶
type RateLimiter interface {
Allow(context.Context, RateLimitRequest) (RateLimitDecision, error)
}
RateLimiter is called before expensive or abuse-sensitive work. Errors fail closed.
type Record ¶
Record is a schema-neutral database row. Adapter factories transform logical model and field names before a raw database adapter receives it.
type RequestHook ¶
type RequestHook func(*HookContext) (*PluginResponse, error)
RequestHook runs before an endpoint. A non-nil response stops the remaining request pipeline and becomes the response.
func RequireResourceOwnership ¶
func RequireResourceOwnership(config ResourceOwnershipConfig) (RequestHook, error)
RequireResourceOwnership returns middleware that requires a session and verifies a logical adapter record belongs to that user without disclosing whether a record with another owner exists.
type RequestMetadata ¶
RequestMetadata is safe, bounded request context for security audits.
type ResourceIDSource ¶
type ResourceIDSource string
ResourceIDSource identifies where ownership middleware reads a resource ID.
const ( ResourceIDParams ResourceIDSource = "params" ResourceIDQuery ResourceIDSource = "query" ResourceIDBody ResourceIDSource = "body" )
Supported resource ID locations.
type ResourceOwnershipConfig ¶
type ResourceOwnershipConfig struct {
Model string
IDField string
IDParam string
IDSource ResourceIDSource
OwnerField string
}
ResourceOwnershipConfig configures RequireResourceOwnership.
type ResponseHook ¶
type ResponseHook func(*HookContext, *PluginResponse) error
ResponseHook runs after an endpoint and may replace response fields.
type Schema ¶
type Schema map[string]ModelSchema
func CoreSchema ¶
func CoreSchema() Schema
CoreSchema returns an independent schema copy that plugins can extend before server construction.
type SchemaConfigurableAdapter ¶
type SchemaConfigurableAdapter interface {
WithSchema(Schema) (DatabaseAdapter, error)
}
SchemaConfigurableAdapter receives the fully merged logical schema before the server applies logical-to-physical query mapping. Adapters with a fixed schema do not need to implement it.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
func (*Server) ResolveSession ¶ added in v1.0.1
ResolveSession resolves the configured session cookie without invoking the HTTP handler or JSON serialization. Missing, invalid, expired, or revoked sessions and disabled users return ErrNoSession. Persistence and context failures are returned distinctly.
ResolveSession is safe for concurrent use. It does not mutate the request, rotate the session, refresh cookies, or return the opaque session token.
func (*Server) Schema ¶
Schema returns an independent copy of the fully merged core, application, and plugin schema. Schema-aware adapters use it for explicit migrations.
func (*Server) SetPassword ¶
SetPassword sets or replaces the credential password for a user. It is a trusted server API and is deliberately not exposed as an HTTP endpoint.
type ServerHooks ¶
type ServerHooks struct {
OnRequest RequestHook
Before []PluginBeforeHook
After []PluginAfterHook
OnResponse ResponseHook
}
ServerHooks configures application-owned lifecycle hooks outside a plugin.
type Session ¶
type Session struct {
ID string `json:"id"`
UserID string `json:"userId"`
TokenHash string `json:"-"`
ExpiresAt time.Time `json:"expiresAt"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
LastSeenAt time.Time `json:"lastSeenAt"`
RevokedAt *time.Time `json:"-"`
ImpersonatorID string `json:"impersonatedBy,omitempty"`
ImpersonationID string `json:"impersonationId,omitempty"`
}
Session is a server-side session. TokenHash is never serialized to clients.
type SessionResult ¶ added in v1.0.1
SessionResult is an authenticated session and its owning user as resolved from an incoming request.
type StoredOAuthAccount ¶
type StoredOAuthAccount struct {
Account OAuthAccount
Tokens ProviderTokens
}
type StringMode ¶
type StringMode string
const ( StringSensitive StringMode = "sensitive" StringInsensitive StringMode = "insensitive" )
type SyntheticUserFactory ¶
type SyntheticUserFactory func(SyntheticUserInput) Record
SyntheticUserFactory builds an enumeration-resistant duplicate-signup user shape, including application fields needed to match a real signup response.
type SyntheticUserInput ¶
SyntheticUserInput contains only public signup fields. AdditionalFields is reserved for application-declared user schema fields and is an independent map that a factory may safely retain or mutate.
type TokenCipher ¶
type TokenCipher interface {
Seal(context.Context, string) (string, error)
Open(context.Context, string) (string, error)
}
TokenCipher encrypts provider credentials before persistence.
type TokenSource ¶
TokenSource creates cryptographically unpredictable URL-safe opaque values.
type TrustedOriginResolver ¶
type TrustedOriginResolver interface {
TrustedOrigins(context.Context, *http.Request) ([]string, error)
}
TrustedOriginResolver returns additional Better Auth v1.6 trusted-origin policies for one request. Results are bounded, validated, and never retained on the shared server. Implementations must be concurrency-safe.
type TrustedOriginResolverFunc ¶
TrustedOriginResolverFunc adapts a function to TrustedOriginResolver.
func (TrustedOriginResolverFunc) TrustedOrigins ¶
type TrustedProviderResolver ¶
type TrustedProviderResolver interface {
TrustedProviders(context.Context, *http.Request) ([]string, error)
}
TrustedProviderResolver resolves Better Auth v1.6's request-dependent trustedProviders option without retaining request state on the server.
type TrustedProviderResolverFunc ¶
TrustedProviderResolverFunc adapts a function to TrustedProviderResolver.
func (TrustedProviderResolverFunc) TrustedProviders ¶
type UpdateQuery ¶
type User ¶
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name,omitempty"`
ImageURL string `json:"image,omitempty"`
EmailVerified bool `json:"emailVerified"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DisabledAt *time.Time `json:"-"`
}
User is the adapter-independent authenticated identity.
func (User) MarshalJSON ¶
MarshalJSON preserves the native Go string field while matching Better Auth's nullable public image field.
type UserDeletionHook ¶
UserDeletionHook runs application cleanup or policy immediately before or after durable account deletion. Implementations must be concurrency-safe.
type UserLifecycleHook ¶
UserLifecycleHook observes a Better Auth lifecycle transition. Implementations must be concurrency-safe.
type UserManagementConfig ¶
type UserManagementConfig struct {
ChangeEmailEnabled bool
SendChangeEmailConfirmation bool
UpdateEmailWithoutVerification bool
DeleteUserEnabled bool
SendDeleteAccountVerification bool
BeforeDelete UserDeletionHook
AfterDelete UserDeletionHook
}
type ValidationKind ¶
type ValidationKind string
ValidationKind is the JSON/query value type required by a FieldValidation.
const ( ValidationString ValidationKind = "string" ValidationNumber ValidationKind = "number" ValidationInteger ValidationKind = "integer" ValidationBoolean ValidationKind = "boolean" ValidationObject ValidationKind = "object" ValidationArray ValidationKind = "array" )
type Where ¶
type Where struct {
Field string
Operator WhereOperator
Value any
Connector WhereConnector
Mode StringMode
}
type WhereConnector ¶
type WhereConnector string
const ( WhereAND WhereConnector = "AND" WhereOR WhereConnector = "OR" )
type WhereOperator ¶
type WhereOperator string
const ( WhereEQ WhereOperator = "eq" WhereNE WhereOperator = "ne" WhereLT WhereOperator = "lt" WhereLTE WhereOperator = "lte" WhereGT WhereOperator = "gt" WhereGTE WhereOperator = "gte" WhereIn WhereOperator = "in" WhereNotIn WhereOperator = "not_in" WhereContains WhereOperator = "contains" WhereStartsWith WhereOperator = "starts_with" WhereEndsWith WhereOperator = "ends_with" )
Source Files
¶
- config.go
- database.go
- database_hooks.go
- errors.go
- handlers_account_tokens.go
- handlers_admin.go
- handlers_email.go
- handlers_management.go
- handlers_oauth.go
- handlers_recovery.go
- handlers_session.go
- outbox.go
- password.go
- plugin.go
- plugin_helpers.go
- plugin_http.go
- ports.go
- schema.go
- schema_adapter.go
- server.go
- store.go
- token.go
- token_cipher.go
- trusted_origins.go
- types.go
- validation.go
- version.go
Directories
¶
| Path | Synopsis |
|---|---|
|
adapter
|
|
|
memory
Package memory provides a concurrency-safe adapter for tests, examples, and ephemeral development.
|
Package memory provides a concurrency-safe adapter for tests, examples, and ephemeral development. |
|
mongodb
Package mongodb implements the generic Better Auth database adapter contract.
|
Package mongodb implements the generic Better Auth database adapter contract. |
|
postgresql
Package postgresql provides the Better Auth PostgreSQL database adapter.
|
Package postgresql provides the Better Auth PostgreSQL database adapter. |
|
sqladapter
Package sqladapter implements the shared database/sql adapter used by the PostgreSQL and SQLite dialect packages.
|
Package sqladapter implements the shared database/sql adapter used by the PostgreSQL and SQLite dialect packages. |
|
sqlite
Package sqlite provides the Better Auth SQLite database adapter.
|
Package sqlite provides the Better Auth SQLite database adapter. |
|
Package adaptertest publishes the conformance suite used by first-party and third-party database adapters.
|
Package adaptertest publishes the conformance suite used by first-party and third-party database adapters. |
|
examples
|
|
|
installcheck
command
|
|
|
nethttp
command
|
|
|
plugin
|
|
|
organization
Package organization provides Better Auth-shaped multi-tenant organization management and authorization.
|
Package organization provides Better Auth-shaped multi-tenant organization management and authorization. |
|
passkey
Package passkey provides an opt-in Better Auth-shaped WebAuthn plugin.
|
Package passkey provides an opt-in Better Auth-shaped WebAuthn plugin. |
|
scim
Package scim provides an inbound Better Auth-shaped SCIM 2.0 provisioning service.
|
Package scim provides an inbound Better Auth-shaped SCIM 2.0 provisioning service. |
|
sso
Package sso provides Better Auth-shaped OIDC, OAuth 2.0, and SAML enterprise single sign-on.
|
Package sso provides Better Auth-shaped OIDC, OAuth 2.0, and SAML enterprise single sign-on. |
|
twofactor
Package twofactor provides an opt-in Better Auth-shaped two-factor plugin.
|
Package twofactor provides an opt-in Better Auth-shaped two-factor plugin. |
|
Package social provides Better Auth-compatible built-in OAuth2/OIDC provider presets and a generic provider constructor.
|
Package social provides Better Auth-compatible built-in OAuth2/OIDC provider presets and a generic provider constructor. |