Documentation
¶
Overview ¶
Package authall is an embedded authentication framework for Go applications.
Auth-All runs inside the application, stores its data in the database the application owns, and integrates through net/http.
Index ¶
- Constants
- Variables
- type AccountLinkingOptions
- type Argon2Params
- type Auth
- func (a *Auth) Accounts(ctx context.Context, userID string) ([]store.Account, error)
- func (a *Auth) BasePath() string
- func (a *Auth) CheckSchema(ctx context.Context) error
- func (a *Auth) Cleanup(ctx context.Context) error
- func (a *Auth) CreateUser(ctx context.Context, in CreateUserInput) (*store.User, error)
- func (a *Auth) GetUser(ctx context.Context, id string) (*store.User, error)
- func (a *Auth) GetUserByEmail(ctx context.Context, address string) (*store.User, error)
- func (a *Auth) Handler() http.Handler
- func (a *Auth) Hooks() *hook.Hooks
- func (a *Auth) Migrate(ctx context.Context) ([]schema.Statement, error)
- func (a *Auth) MigrationPlan(ctx context.Context) ([]schema.Statement, error)
- func (a *Auth) MigrationSQL(d schema.Dialect) ([]schema.Statement, error)
- func (a *Auth) OpenAPI() *openapi.Document
- func (a *Auth) RevokeSession(ctx context.Context, sessionID string) error
- func (a *Auth) RevokeUserSessions(ctx context.Context, userID string) (int, error)
- func (a *Auth) Routes() []RouteInfo
- func (a *Auth) Schema() *schema.Schema
- func (a *Auth) Session(ctx context.Context, r *http.Request) (*store.Session, error)
- func (a *Auth) User(ctx context.Context, r *http.Request) (*store.User, error)
- func (a *Auth) VerifyEmailToken(ctx context.Context, token string) (*store.User, error)
- type Code
- type CookieOptions
- type CreateUserInput
- type EmailPasswordOptions
- type Error
- type Option
- func WithAccountLinking(o AccountLinkingOptions) Option
- func WithArgon2Params(p crypto.Argon2Params) Option
- func WithBasePath(p string) Option
- func WithBaseURL(u string) Option
- func WithClock(now func() time.Time) Option
- func WithCookie(o CookieOptions) Option
- func WithCookieSameSite(mode http.SameSite) Option
- func WithEmailPassword(opts ...EmailPasswordOptions) Option
- func WithEmailSender(s email.Sender) Option
- func WithEventHandler(h events.Handler) Option
- func WithLogger(l *slog.Logger) Option
- func WithPasswordPolicy(p PasswordPolicy) Option
- func WithPlugins(plugins ...plugin.Plugin) Option
- func WithProvider(providers ...oauth.Provider) Option
- func WithRateLimiter(l ratelimit.Limiter) Option
- func WithSession(o SessionOptions) Option
- func WithSessionLifetime(idle, absolute time.Duration) Option
- func WithStore(s store.Store) Option
- func WithStrictRateLimiting() Option
- func WithTokenTTL(o TokenTTLOptions) Option
- func WithTrustedOrigins(origins ...string) Option
- func WithTrustedProxies(cidrs ...string) Option
- type PasswordPolicy
- type RouteInfo
- type SessionOptions
- type TokenTTLOptions
Constants ¶
const ( DefaultBasePath = "/api/auth" DefaultCookieName = "authall.session" // DefaultSessionTTL is the absolute lifetime of a session. A session ends // at this age, even when the person stays active. DefaultSessionTTL = 30 * 24 * time.Hour // DefaultSessionIdleTimeout ends a session that saw no request for this // long. DefaultSessionIdleTimeout = 7 * 24 * time.Hour // DefaultSessionTouchInterval limits how often a session read writes // last_seen_at. DefaultSessionTouchInterval = 5 * time.Minute DefaultVerificationTTL = 24 * time.Hour DefaultPasswordResetTTL = time.Hour DefaultOAuthStateTTL = 15 * time.Minute )
Defaults used when an option is not supplied.
const Version = "1.0.0"
Version is the Auth-All API contract version.
Variables ¶
var ( ErrInvalidRequest = apierr.ErrInvalidRequest ErrInvalidCredentials = apierr.ErrInvalidCredentials ErrEmailAlreadyExists = apierr.ErrEmailAlreadyExists ErrWeakPassword = apierr.ErrWeakPassword ErrInvalidToken = apierr.ErrInvalidToken ErrForbidden = apierr.ErrForbidden ErrNotFound = apierr.ErrNotFound ErrLastAuthMethod = apierr.ErrLastAuthMethod // ErrNoPasswordCredential reports that the account has no password. An // OAuth-only user reaches it. ErrNoPasswordCredential = apierr.ErrNoPasswordCredential )
Re-exported public errors.
Functions ¶
This section is empty.
Types ¶
type AccountLinkingOptions ¶
type AccountLinkingOptions struct {
// AllowVerifiedEmailAutoLink links an external account to an existing user
// when the provider proves the same verified email address. It is off by
// default, because email matching alone allows account takeover through a
// provider that does not verify addresses.
AllowVerifiedEmailAutoLink bool
}
AccountLinkingOptions configures how an external account joins a user.
type Argon2Params ¶
type Argon2Params = crypto.Argon2Params
Argon2Params re-exports the password hashing parameters.
func DefaultArgon2Params ¶
func DefaultArgon2Params() Argon2Params
DefaultArgon2Params returns the default password hashing cost.
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
Auth is a configured Auth-All instance.
func (*Auth) CheckSchema ¶
CheckSchema reports an actionable error when the database schema is missing or outdated. Auth-All never migrates a schema on its own.
func (*Auth) CreateUser ¶
CreateUser creates a user, and a password credential when a password is supplied. It returns apierr.ErrEmailAlreadyExists for a duplicate address.
func (*Auth) GetUserByEmail ¶
GetUserByEmail returns one user by the normalized form of an address.
func (*Auth) Handler ¶
Handler returns the Auth-All HTTP handler. Mount it at the configured base path, for example mux.Handle("/api/auth/", auth.Handler()).
func (*Auth) Migrate ¶
Migrate applies the effective schema. It runs only when the application or the command line tool calls it.
func (*Auth) MigrationPlan ¶
MigrationPlan returns the statements that are not applied yet.
func (*Auth) MigrationSQL ¶
MigrationSQL returns the complete deterministic DDL for one dialect. It needs no database connection.
func (*Auth) RevokeSession ¶
RevokeSession revokes one session by id.
func (*Auth) RevokeUserSessions ¶
RevokeUserSessions revokes every session of one user and returns the count.
func (*Auth) Session ¶
Session returns the session of a request. It returns nil when the request carries no valid session.
func (*Auth) User ¶
User returns the authenticated user of a request. It returns nil when the request carries no valid session.
func (*Auth) VerifyEmailToken ¶
VerifyEmailToken consumes an email verification token and records that the user controls the address. It exists so an application can verify an address from its own page without a call to the HTTP API.
type CookieOptions ¶
type CookieOptions struct {
Name string
Domain string
Path string
SameSite http.SameSite
// Secure defaults to true. Set it to false only for local development
// over plain HTTP.
Secure *bool
}
CookieOptions configures the session cookie.
type CreateUserInput ¶
type CreateUserInput struct {
Email string
Password string
DisplayName string
ImageURL string
// EmailVerified marks the address as already proven.
EmailVerified bool
}
CreateUserInput describes a user created through the programmatic API.
type EmailPasswordOptions ¶
type EmailPasswordOptions struct {
// RequireEmailVerification blocks sign-in until the address is verified.
RequireEmailVerification bool
// SendVerificationOnSignUp sends a verification email after sign-up. It is
// implied by RequireEmailVerification.
SendVerificationOnSignUp bool
// VerifyEmailURL is the application page that receives a verification
// token. Auth-All appends the token query parameter. The default is
// BaseURL + /verify-email.
VerifyEmailURL string
// ResetPasswordURL is the application page that receives a password reset
// token. Auth-All appends the token query parameter. The default is
// BaseURL + /reset-password.
ResetPasswordURL string
// ChangeEmailURL is the application page that receives an email change
// token. Auth-All appends the token query parameter. The default is
// BaseURL + /change-email.
ChangeEmailURL string
// DeleteAccountURL is the application page that receives an account delete
// token. Auth-All appends the token query parameter. The default is
// BaseURL + /delete-account.
DeleteAccountURL string
}
EmailPasswordOptions configures email and password authentication.
type Error ¶
Error is the public Auth-All error type. Its code is part of the public API compatibility surface.
type Option ¶
type Option func(*config)
Option configures Auth-All.
func WithAccountLinking ¶
func WithAccountLinking(o AccountLinkingOptions) Option
WithAccountLinking configures the account linking policy.
func WithArgon2Params ¶
func WithArgon2Params(p crypto.Argon2Params) Option
WithArgon2Params configures the password hashing cost. A sign-in rehashes a password that was stored with different parameters.
func WithBasePath ¶
WithBasePath sets the mount path of the HTTP handler. The default is /api/auth.
func WithBaseURL ¶
WithBaseURL sets the absolute public URL of the application, for example https://app.example.com. Auth-All uses it to build links and to validate redirects. It is required when an OAuth provider is configured.
func WithCookieSameSite ¶
WithCookieSameSite sets the SameSite attribute of the session cookie.
Use http.SameSiteLaxMode when the application and the API share a registrable domain, for example app.example.com and api.example.com. Use http.SameSiteNoneMode only for a true cross-site setup. A browser refuses a cookie with SameSite=None and no Secure attribute, so that pair fails the construction. See docs/guides/deployment.md.
func WithEmailPassword ¶
func WithEmailPassword(opts ...EmailPasswordOptions) Option
WithEmailPassword enables email and password authentication.
func WithEmailSender ¶
WithEmailSender sets the email delivery boundary of the application.
func WithEventHandler ¶
WithEventHandler registers an observability handler.
func WithPasswordPolicy ¶
func WithPasswordPolicy(p PasswordPolicy) Option
WithPasswordPolicy configures the accepted passwords.
func WithPlugins ¶
WithPlugins registers one or more plugins.
func WithProvider ¶
WithProvider registers one or more OAuth providers.
func WithRateLimiter ¶
WithRateLimiter sets the rate limiter for sensitive operations.
func WithSession ¶
func WithSession(o SessionOptions) Option
WithSession configures session lifetime.
func WithSessionLifetime ¶
WithSessionLifetime sets the two session deadlines.
idle ends a session that saw no request for that long. absolute ends a session at that age, even when the person stays active. One value cannot serve both, because a stolen token that stays active would never expire.
The defaults are 7 days and 30 days.
func WithStrictRateLimiting ¶
func WithStrictRateLimiting() Option
WithStrictRateLimiting fails the construction when no rate limiter is configured.
A production deployment needs a limiter. Without one, every sensitive endpoint accepts unlimited attempts, so a brute-force attack and an enumeration attack run without a bound. The default only writes a warning, because a test and a local run do not need a limiter.
func WithTokenTTL ¶
func WithTokenTTL(o TokenTTLOptions) Option
WithTokenTTL configures one-time token lifetimes.
func WithTrustedOrigins ¶
WithTrustedOrigins adds browser origins that can call state-changing endpoints. The origin of BaseURL is always trusted. A credentialed wildcard origin is never allowed.
func WithTrustedProxies ¶
WithTrustedProxies declares the reverse proxies that stand in front of the application. Auth-All reads a forwarded client address only when the direct peer is inside one of these blocks.
Each value is a CIDR block, for example 10.0.0.0/8. A single IP address is also valid, and Auth-All treats it as one host. An invalid value fails the construction.
Auth-All ignores the X-Forwarded-For header when no trusted proxy is declared, because any client can set that header. Declare the proxies of the deployment. See docs/guides/deployment.md.
type PasswordPolicy ¶
PasswordPolicy configures the accepted passwords. Auth-All does not require special characters, because a length requirement protects better.
func DefaultPasswordPolicy ¶
func DefaultPasswordPolicy() PasswordPolicy
DefaultPasswordPolicy returns the default policy.
type RouteInfo ¶
type RouteInfo struct {
Method string
// Path is the complete path, including the configured base path.
Path string
// PluginID names the contributing plugin. It is empty for a core route.
PluginID string
// Documented reports whether the route appears in the OpenAPI document.
Documented bool
}
RouteInfo describes one mounted Auth-All route.
type SessionOptions ¶
type SessionOptions struct {
// TTL is the absolute lifetime. A session ends at this age, even when the
// person stays active. The default is 30 days.
TTL time.Duration
// IdleTimeout ends a session that saw no request for this long. The
// default is 7 days.
IdleTimeout time.Duration
// TouchInterval limits how often a session read updates last_seen_at.
TouchInterval time.Duration
}
SessionOptions configures session lifetime.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package apierr defines the stable, machine-readable error contract of Auth-All.
|
Package apierr defines the stable, machine-readable error contract of Auth-All. |
|
cmd
|
|
|
auth-all
command
Command auth-all manages the Auth-All schema and generates the published contract artifacts.
|
Command auth-all manages the Auth-All schema and generates the published contract artifacts. |
|
Package email defines the provider-independent email boundary of Auth-All.
|
Package email defines the provider-independent email boundary of Auth-All. |
|
Package events defines the structured observability events of Auth-All.
|
Package events defines the structured observability events of Auth-All. |
|
examples
|
|
|
go-app
command
Command example-app shows a complete Auth-All integration in a small Go application.
|
Command example-app shows a complete Auth-All integration in a small Go application. |
|
Package hook defines the typed lifecycle hooks of Auth-All.
|
Package hook defines the typed lifecycle hooks of Auth-All. |
|
humaauth
module
|
|
|
internal
|
|
|
clientgen
Package clientgen generates the official TypeScript client from the effective OpenAPI document.
|
Package clientgen generates the official TypeScript client from the effective OpenAPI document. |
|
crypto
Package crypto holds the password hashing and token primitives of Auth-All.
|
Package crypto holds the password hashing and token primitives of Auth-All. |
|
jwt
Package jwt verifies the compact RS256 identity tokens of OpenID Connect providers.
|
Package jwt verifies the compact RS256 identity tokens of OpenID Connect providers. |
|
reference
Package reference builds the canonical Auth-All configuration.
|
Package reference builds the canonical Auth-All configuration. |
|
sqlstore
Package sqlstore implements the Auth-All storage boundary over database/sql.
|
Package sqlstore implements the Auth-All storage boundary over database/sql. |
|
testsupport
Package testsupport builds migrated databases for the Auth-All test suites.
|
Package testsupport builds migrated databases for the Auth-All test suites. |
|
Package oauth defines the OAuth provider boundary of Auth-All.
|
Package oauth defines the OAuth provider boundary of Auth-All. |
|
github
Package github implements the GitHub OAuth provider for Auth-All.
|
Package github implements the GitHub OAuth provider for Auth-All. |
|
google
Package google implements the Google OpenID Connect provider for Auth-All.
|
Package google implements the Google OpenID Connect provider for Auth-All. |
|
Package openapi holds the OpenAPI document model of Auth-All.
|
Package openapi holds the OpenAPI document model of Auth-All. |
|
Package plugin is the public extension surface of Auth-All.
|
Package plugin is the public extension surface of Auth-All. |
|
plugins
|
|
|
magiclink
Package magiclink implements sign-in through an emailed one-time link.
|
Package magiclink implements sign-in through an emailed one-time link. |
|
Package ratelimit defines the rate-limit integration point of Auth-All.
|
Package ratelimit defines the rate-limit integration point of Auth-All. |
|
Package schema describes the Auth-All database schema independently from a specific database engine.
|
Package schema describes the Auth-All database schema independently from a specific database engine. |
|
Package store defines the storage boundary of Auth-All.
|
Package store defines the storage boundary of Auth-All. |
|
postgres
Package postgres provides the PostgreSQL storage adapter for Auth-All.
|
Package postgres provides the PostgreSQL storage adapter for Auth-All. |
|
sqlite
Package sqlite provides the SQLite storage adapter for Auth-All.
|
Package sqlite provides the SQLite storage adapter for Auth-All. |
|
storetest
Package storetest holds the behavioral contract suite that every Auth-All storage adapter must pass.
|
Package storetest holds the behavioral contract suite that every Auth-All storage adapter must pass. |
|
tools
|
|
|
evidence
command
Command evidence writes the v1 verification evidence of Auth-All.
|
Command evidence writes the v1 verification evidence of Auth-All. |