goauth

package module
v0.0.0-...-a5a4909 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNoDatabase = errors.New("go-auth: no database pool or DSN provided")

Functions

func ErrNoSchema

func ErrNoSchema(driver string) error

func GenerateSchema

func GenerateSchema(driver, outPath string) error

func GetSchema

func GetSchema(driver string) (string, error)

func SplitSQL

func SplitSQL(sql string) []string

func WithApp

func WithApp(cfg AppConfig) func(*Config)

WithApp configures app-level identity settings.

func WithCookie

func WithCookie(cfg CookieConfig) func(*Config)

WithCookie sets the session cookie configuration.

func WithEmail

func WithEmail(cfg EmailConfig) func(*Config)

WithEmail configures SMTP email delivery (transport only).

func WithIPAddressHeader

func WithIPAddressHeader(header string) func(*Config)

WithIPAddressHeader sets which header to trust for client IP (e.g. "CF-Connecting-IP"). Requires TrustedIPs to be set - validated in Config.validate().

func WithIPv6Subnet

func WithIPv6Subnet(prefixLen int) func(*Config)

WithIPv6Subnet sets the subnet prefix length used to bucket IPv6 clients for rate limiting.

func WithLogger

func WithLogger(logger *slog.Logger) func(*Config)

WithLogger sets the structured logger.

func WithMailer

func WithMailer(m port.Mailer) func(*Config)

WithMailer provides a custom mailer implementation.

func WithOrganizations

func WithOrganizations(cfg OrganizationConfig) func(*Config)

WithOrganizations configures the organizations feature.

func WithProvider

func WithProvider(p port.OAuthProvider) func(*Config)

WithProvider registers an OAuth provider. The provider's Name() must be non-empty and unique across all registered providers. Nil providers are rejected.

func WithRateLimit

func WithRateLimit(cfg ratelimit.Config) func(*Config)

WithRateLimit configures rate limiting. Takes a value to force a copy at the call site, preventing shared mutation across separate NewConfig calls.

func WithRateLimitDefault

func WithRateLimitDefault(r ratelimit.Rate) func(*Config)

WithRateLimitDefault overrides only the fallback rate applied to routes not present in Routes.

func WithRateLimitEnabled

func WithRateLimitEnabled(enabled bool) func(*Config)

WithRateLimitEnabled toggles rate limiting on/off without touching Routes, Default, or Store.

func WithRateLimitRoute

func WithRateLimitRoute(pattern string, r ratelimit.Rate) func(*Config)

WithRateLimitRoute overrides or adds a single route's rate without replacing the rest of the Routes table.

func WithRateLimitStore

func WithRateLimitStore(s ratelimit.Store) func(*Config)

WithRateLimitStore swaps the backing store (e.g. a Redis-backed Store) without touching Routes or Default.

func WithRegistration

func WithRegistration(cfg RegistrationConfig) func(*Config)

WithRegistration configures which registration methods are available. Login is ALWAYS unconditional regardless of these settings.

func WithSecurity

func WithSecurity(cfg SecurityConfig) func(*Config)

WithSecurity groups security-related settings.

func WithSession

func WithSession(cfg SessionConfig) func(*Config)

WithSession groups session lifetime settings.

func WithTemplates

func WithTemplates(p port.TemplateProvider) func(*Config)

WithTemplates provides a custom email template provider. When set, the provider's Render method is called for every email instead of the built-in default templates.

func WithTrustedIPs

func WithTrustedIPs(ips []string) func(*Config)

WithTrustedIPs sets the list of IPs/CIDRs trusted to supply IPAddressHeader.

Types

type AppConfig

type AppConfig struct {
	Name     string         // app name displayed in emails
	BaseURL  string         // frontend base URL for email links
	Database DatabaseConfig // database connection
}

AppConfig groups the three identity-level settings for the application instance.

type Auth

type Auth struct {
	Config     Config
	Pool       *pgxpool.Pool
	DB         *sqlstore.DB
	Services   Services
	Handlers   HandlerGroup
	Middleware MiddlewareGroup
	// contains filtered or unexported fields
}

func New

func New(config Config) (*Auth, error)

func (*Auth) CheckSession

func (a *Auth) CheckSession(ctx context.Context, tokenRaw string) bool

CheckSession validates a raw session token and returns whether it is valid. It checks the session exists, is not expired, and the associated user exists and is not banned.

func (*Auth) Close

func (a *Auth) Close()

func (*Auth) CompleteInviteRegistration

func (a *Auth) CompleteInviteRegistration(ctx context.Context, input CompleteInviteInput) (*CompleteInviteResult, *domain.AuthError)

func (*Auth) GetSession

func (a *Auth) GetSession(ctx context.Context, tokenRaw string) (*domain.User, *domain.Session, error)

GetSession validates a raw session token and returns the associated user and session. Returns the user, session, and nil error on success. Returns nil, nil, error if the token is invalid, expired, or the user is banned.

func (*Auth) Login

func (a *Auth) Login(ctx context.Context, input LoginInput) (*LoginResult, *domain.AuthError)

func (*Auth) Mount

func (a *Auth) Mount(mux *http.ServeMux)

func (*Auth) Register

func (a *Auth) Register(ctx context.Context, input RegisterInput) (*RegisterResult, *domain.AuthError)

type CompleteInviteInput

type CompleteInviteInput struct {
	Code            string
	Name            string
	Password        string
	ConfirmPassword string
}

type CompleteInviteResult

type CompleteInviteResult struct {
	User         *domain.User
	Session      *domain.Session
	SessionToken string
	RefreshToken string
}

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config is the top-level configuration for go-auth. All fields are unexported — use NewConfig + With* functions.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

func NewConfig

func NewConfig(opts ...func(*Config)) (Config, error)

NewConfig applies the given option functions to DefaultConfig and validates. If validation fails, the returned error includes all invalid fields.

type CookieConfig

type CookieConfig struct {
	Name     string
	Domain   string
	Path     string
	Secure   bool
	SameSite http.SameSite
}

CookieConfig configures the session cookie.

type DatabaseConfig

type DatabaseConfig struct {
	URL    string        // connection string (preferred)
	DB     *sql.DB       // pre-opened *sql.DB (library borrows, does not close)
	Pool   *pgxpool.Pool // pre-opened pgx pool (library borrows, does not close)
	Driver Driver        // DriverPostgres (default), DriverSQLite, DriverMySQL
	// contains filtered or unexported fields
}

DatabaseConfig configures the database connection. Provide one of URL, DB, or Pool. URL is the preferred option — the library will open, validate, and close the connection automatically.

type Driver

type Driver string
const (
	DriverPostgres Driver = "postgres"
	DriverSQLite   Driver = "sqlite3"
	DriverMySQL    Driver = "mysql"
)

type EmailConfig

type EmailConfig struct {
	From          string
	Host          string
	Port          int
	User          string
	Pass          string
	TLSMode       TLSMode
	AllowHTTPURLs bool // allow http:// URLs in email templates (dev only, default false)
}

EmailConfig configures SMTP email delivery (transport only).

type HandlerGroup

type HandlerGroup struct {
	Register                 http.HandlerFunc
	Login                    http.HandlerFunc
	Logout                   http.HandlerFunc
	ForgotPassword           http.HandlerFunc
	ResetPassword            http.HandlerFunc
	ChangePassword           http.HandlerFunc
	SetPasswordRequest       http.HandlerFunc
	SetPasswordConfirm       http.HandlerFunc
	VerifyEmail              http.HandlerFunc
	ResendVerification       http.HandlerFunc
	ResendVerificationPublic http.HandlerFunc
	ListSessions             http.HandlerFunc
	RevokeSession            http.HandlerFunc
	RevokeAllSessions        http.HandlerFunc
	InviteRegister           http.HandlerFunc
	CheckSession             http.HandlerFunc
	RefreshToken             http.HandlerFunc
	GetMe                    http.HandlerFunc
	ChangeName               http.HandlerFunc
	DeleteAccount            http.HandlerFunc
	RequestDeleteAccount     http.HandlerFunc
	ConfirmDeleteAccount     http.HandlerFunc
	ListUsers                http.HandlerFunc
	UpdateUserRole           http.HandlerFunc
	BanUser                  http.HandlerFunc
	UnbanUser                http.HandlerFunc
	DeleteUser               http.HandlerFunc
	RevokeUserSessions       http.HandlerFunc
	AdminCreateUser          http.HandlerFunc
	AdminListUserSessions    http.HandlerFunc
	AdminRevokeUserSession   http.HandlerFunc
	GetInviteInfo            http.HandlerFunc
	CreateInvite             http.HandlerFunc
	ListInvites              http.HandlerFunc
	RevokeInvite             http.HandlerFunc
	ResendInvite             http.HandlerFunc
	HardDeleteInvite         http.HandlerFunc
	OAuthInitiate            http.HandlerFunc
	OAuthCallback            http.HandlerFunc
	OAuthLink                http.HandlerFunc
	OAuthUnlink              http.HandlerFunc
	OAuthProviders           http.HandlerFunc
	CSRFToken                http.HandlerFunc
	CreateOrg                http.HandlerFunc
	GetOrg                   http.HandlerFunc
	UpdateOrg                http.HandlerFunc
	DeleteOrg                http.HandlerFunc
	ListUserOrgs             http.HandlerFunc
	ListOrgMembers           http.HandlerFunc
	RemoveOrgMember          http.HandlerFunc
	UpdateOrgMemberRole      http.HandlerFunc
	LeaveOrg                 http.HandlerFunc
	SetActiveOrg             http.HandlerFunc
	ClearActiveOrg           http.HandlerFunc
	CreateOrgInvite          http.HandlerFunc
	AcceptOrgInvite          http.HandlerFunc
	ListOrgInvites           http.HandlerFunc
	ResendOrgInvite          http.HandlerFunc
	DeleteOrgInvite          http.HandlerFunc
}

type LoginInput

type LoginInput struct {
	Email     string
	Password  string
	IP        string
	UserAgent string
}

type LoginResult

type LoginResult struct {
	User                 *domain.User
	Session              *domain.Session
	SessionToken         string
	RefreshToken         string
	RequiresVerification bool
}

type MiddlewareGroup

type MiddlewareGroup struct {
	Authenticate func(http.Handler) http.Handler
	RequireAdmin func(http.Handler) http.Handler
	RateLimit    func(http.Handler) http.Handler
	CORS         func(http.Handler) http.Handler
}

type OrganizationConfig

type OrganizationConfig struct {
	Enable         bool          // enable orgs feature (default false)
	MaxOrgsPerUser int           // max orgs a user can own (0=default 100, >100 rejected)
	InviteTTL      time.Duration // how long org invites last (default 7d)
}

OrganizationConfig controls the organizations feature.

type RegisterInput

type RegisterInput struct {
	Email    string
	Password string
	Name     string
}

type RegisterResult

type RegisterResult struct {
	User                 *domain.User
	Session              *domain.Session
	SessionToken         string
	RefreshToken         string
	RequiresVerification bool
}

type RegistrationConfig

type RegistrationConfig struct {
	EnableEmailPassword      bool          // email+password registration (default true)
	EnableOAuth              bool          // OAuth signup for new users (default true)
	EnableInvite             bool          // invite-code registration (default true)
	AllowPublic              bool          // public registration is allowed (default true)
	RequireEmailVerification bool          // require email verification on signup (default false)
	InviteTTL                time.Duration // how long signup invites last (default 7d)
	VerificationCodeTTL      time.Duration // how long verification codes live (default 15m)
}

RegistrationConfig controls which registration methods are available. Login is ALWAYS unconditional regardless of these flags.

type SMTPMailer

type SMTPMailer struct {
	// contains filtered or unexported fields
}

func (*SMTPMailer) Send

func (m *SMTPMailer) Send(ctx context.Context, to, subject, html, text string) error

type SecurityConfig

type SecurityConfig struct {
	AllowedOrigins          []string                    // allowed origins for CSRF Origin/Referer check
	AllowMissingCSRFHeaders bool                        // allow requests without Origin/Referer headers (default false)
	CSRFToken               *middleware.CSRFTokenConfig // double-submit cookie CSRF (optional, disabled by default)
	PasswordPolicy          domain.PasswordPolicy       // password complexity requirements
	TokenTTL                time.Duration               // how long verification/reset tokens live (default 1h)
}

SecurityConfig groups security-related settings.

type SessionConfig

type SessionConfig struct {
	TTL             time.Duration // absolute hard expiry (default 30d)
	IdleTTL         time.Duration // idle timeout after last activity (default 7d)
	RefreshTokenTTL time.Duration // refresh token absolute expiry (default 30d)
	MaxLifetime     time.Duration // max session lifetime from created_at (0 = no limit)
	GraceWindow     time.Duration // grace period for reusing old refresh token (default 10s)
	TouchDebounce   time.Duration // minimum interval between last_active_at updates (default 5m)
}

SessionConfig groups session lifetime settings.

type TLSMode

type TLSMode int
const (
	TLSNone     TLSMode = iota // plaintext — dev/local only
	TLSStart                   // STARTTLS, typically port 587
	TLSImplicit                // implicit TLS, typically port 465
)

Directories

Path Synopsis
Package emailtemplate provides the default email template provider for go-auth.
Package emailtemplate provides the default email template provider for go-auth.
internal
provider

Jump to

Keyboard shortcuts

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