Documentation
¶
Overview ¶
Package goauth is a reusable, embeddable authentication stack for Echo applications. It provides username+password login, passkeys (WebAuthn) and runtime-configurable OIDC, backed by server-side sessions (SCS + Redis) and GORM-managed tables.
Integration surface:
a, err := goauth.New(goauth.Config{DB: gormDB, Redis: redisClient, ...})
e.Use(a.SessionMiddleware())
a.RegisterRoutes(e.Group("/auth"))
api := e.Group("/graphql", a.RequireAuthenticated())
Index ¶
- Constants
- Variables
- func ContextWithUser(ctx context.Context, user *User) context.Context
- func ErrInvalidInput(msg string) error
- func IsInputError(err error) bool
- func NormalizeEmail(email string) string
- func NormalizeUsername(username string) string
- func ValidOIDCMode(m OIDCMode) bool
- func ValidRole(r Role) bool
- type Auth
- func (a *Auth) Authenticate(identifier, password string) (*User, error)
- func (a *Auth) Avatar(c echo.Context) error
- func (a *Auth) ChangePassword(userID uint, currentPassword, newPassword string) error
- func (a *Auth) CreateUser(username, password, email string, role Role) (*User, error)
- func (a *Auth) DB() *gorm.DB
- func (a *Auth) DeleteAvatar(c echo.Context) error
- func (a *Auth) DeleteUser(id uint) error
- func (a *Auth) EnsureUser(username, password string, role Role) (*User, error)
- func (a *Auth) FindUserByID(id uint) (*User, error)
- func (a *Auth) FindUserByIdentifier(identifier string) (*User, error)
- func (a *Auth) FindUserByUsername(username string) (*User, error)
- func (a *Auth) GetSettings() (Settings, error)
- func (a *Auth) ListOIDCProviders(enabledOnly bool) ([]OIDCProvider, error)
- func (a *Auth) ListUsers() ([]User, error)
- func (a *Auth) PasskeysEnabled() bool
- func (a *Auth) RegisterAvatarRoutes(me, admin *echo.Group)
- func (a *Auth) RegisterRoutes(g *echo.Group)
- func (a *Auth) RequireAuthenticated() echo.MiddlewareFunc
- func (a *Auth) RequireRole(role Role) echo.MiddlewareFunc
- func (a *Auth) SessionMiddleware() echo.MiddlewareFunc
- func (a *Auth) SetPassword(userID uint, password string) error
- func (a *Auth) UpdateProfile(userID uint, patch ProfilePatch) (*User, error)
- func (a *Auth) UpdateSettings(mode OIDCMode) (Settings, error)
- func (a *Auth) UpdateUser(id uint, patch UserPatch) (*User, error)
- func (a *Auth) UploadAvatar(c echo.Context) error
- func (a *Auth) UserAvatar(c echo.Context) error
- type Config
- type InputError
- type OIDCMode
- type OIDCProvider
- type ProfilePatch
- type Role
- type Settings
- type User
- type UserAvatar
- type UserDTO
- type UserPatch
- type WebauthnCredential
Constants ¶
const ( // DefaultCookieName is used when Config.CookieName is empty. DefaultCookieName = "goauth_session" // DefaultSessionLifetime is used when Config.SessionLifetime is zero. DefaultSessionLifetime = 7 * 24 * time.Hour // DefaultMountPath is used when Config.MountPath is empty. It must match // the Echo group prefix passed to RegisterRoutes. DefaultMountPath = "/auth" // DefaultMaxAvatarBytes limits the entire multipart upload request. DefaultMaxAvatarBytes int64 = 8 << 20 )
Variables ¶
var ( // ErrInvalidCredentials is returned for unknown users, wrong passwords // and disabled accounts (indistinguishable on purpose). ErrInvalidCredentials = errors.New("invalid credentials") // ErrNotFound is returned when a record does not exist. ErrNotFound = errors.New("not found") // ErrConcurrentUpdate is returned when a session-version bump lost a race with another update; retry. ErrConcurrentUpdate = errors.New("account was modified concurrently") // ErrPasswordManagedByIdP is returned when an OIDC-linked account without a local password tries to create one via self-service. ErrPasswordManagedByIdP = errors.New("password is managed by the identity provider") )
Functions ¶
func ContextWithUser ¶
ContextWithUser returns a child context that carries user for UserFromContext. Useful in GraphQL/service unit tests that do not go through Echo middleware.
func IsInputError ¶
IsInputError reports whether err is an InputError.
func NormalizeEmail ¶
NormalizeEmail lowercases and trims an email address.
func NormalizeUsername ¶
NormalizeUsername lowercases and trims a username.
func ValidOIDCMode ¶
ValidOIDCMode reports whether m is a known mode.
Types ¶
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
Auth is the assembled authentication module.
func New ¶
New validates the config, migrates the auth tables, bootstraps the init admin and returns a ready-to-mount Auth.
func (*Auth) Authenticate ¶
Authenticate verifies identifier+password and returns the user. The identifier may be the username or the account email. Disabled accounts and accounts without a password fail with ErrInvalidCredentials.
func (*Auth) ChangePassword ¶
ChangePassword verifies the current password before setting a new one. Passwordless non-OIDC accounts may set an initial password via their session.
func (*Auth) CreateUser ¶
CreateUser creates a new local user. Password and email may be empty for accounts that only log in via passkey or OIDC.
func (*Auth) DeleteAvatar ¶
DeleteAvatar removes the current user's avatar.
func (*Auth) DeleteUser ¶
DeleteUser soft-deletes a user, protecting the last active admin.
func (*Auth) EnsureUser ¶
EnsureUser creates the user when it does not exist yet; useful for seeding. Existing users are returned unchanged.
func (*Auth) FindUserByID ¶
FindUserByID loads a user by primary key.
func (*Auth) FindUserByIdentifier ¶
FindUserByIdentifier loads a user by login identifier: username or email.
func (*Auth) FindUserByUsername ¶
FindUserByUsername loads a user by normalized username.
func (*Auth) GetSettings ¶
GetSettings returns the current runtime settings.
func (*Auth) ListOIDCProviders ¶
func (a *Auth) ListOIDCProviders(enabledOnly bool) ([]OIDCProvider, error)
ListOIDCProviders returns providers, optionally only enabled ones.
func (*Auth) PasskeysEnabled ¶
PasskeysEnabled reports whether WebAuthn is configured.
func (*Auth) RegisterAvatarRoutes ¶
RegisterAvatarRoutes mounts self-service routes at me's prefix and the admin read at admin's prefix + /users/:id/avatar. Callers must apply SessionMiddleware, RequireAuthenticated on me and RequireRole(RoleAdmin) on admin.
func (*Auth) RegisterRoutes ¶
RegisterRoutes mounts every goauth endpoint on the group. The group's prefix must match Config.MountPath (default "/auth"). SessionMiddleware must already be applied (globally or on the group).
func (*Auth) RequireAuthenticated ¶
func (a *Auth) RequireAuthenticated() echo.MiddlewareFunc
RequireAuthenticated rejects requests without a valid session (401) and attaches the user to the request contexts.
func (*Auth) RequireRole ¶
func (a *Auth) RequireRole(role Role) echo.MiddlewareFunc
RequireRole rejects requests whose session user does not hold the role (403), or is unauthenticated (401). Admins pass every role check.
func (*Auth) SessionMiddleware ¶
func (a *Auth) SessionMiddleware() echo.MiddlewareFunc
SessionMiddleware loads/saves the SCS session for every request and enforces an Origin-header CSRF check on unsafe methods. Apply it once, globally, before any goauth routes or guarded routes.
func (*Auth) SetPassword ¶
SetPassword replaces the user's password (admin reset or self change).
func (*Auth) UpdateProfile ¶
func (a *Auth) UpdateProfile(userID uint, patch ProfilePatch) (*User, error)
UpdateProfile applies a self-service profile patch.
func (*Auth) UpdateSettings ¶
UpdateSettings persists new runtime settings after validation.
func (*Auth) UpdateUser ¶
UpdateUser applies an admin patch, protecting the last active admin from demotion or disabling.
func (*Auth) UploadAvatar ¶
UploadAvatar replaces the current user's avatar from multipart field file.
type Config ¶
type Config struct {
// DB is the GORM database handle the module stores its tables in. All
// tables are prefixed with "auth_".
DB *gorm.DB
// Redis backs sessions and login throttling.
Redis *redis.Client
// RPDisplayName / RPID / Origins configure WebAuthn (passkeys). When RPID
// is empty, passkey endpoints are disabled.
RPDisplayName string
RPID string
// Origins are the browser origins allowed for WebAuthn ceremonies and the
// Origin-header CSRF check (e.g. http://localhost:5173).
Origins []string
// PublicBaseURL is the externally reachable base URL of the app (no
// trailing slash), used to build the OIDC redirect URL. Example:
// "http://localhost:5173". Required for OIDC logins.
PublicBaseURL string
// MountPath is the route prefix RegisterRoutes is mounted at. Defaults to
// "/auth". Only used to build the OIDC callback URL.
MountPath string
CookieName string
// CookieSecure marks the session cookie Secure (HTTPS-only deployments).
CookieSecure bool
// ClientIP extracts the client IP used to key login throttling. Defaults to
// echo.ExtractIPDirect() (the TCP peer address), which ignores client-supplied
// X-Forwarded-For / X-Real-IP headers. Behind a reverse proxy, set a trusted
// extractor such as echo.ExtractIPFromXFFHeader(echo.TrustIPRange(proxyNet));
// otherwise every client shares the proxy's address.
ClientIP echo.IPExtractor
SessionLifetime time.Duration
// InitAdminUsername / InitAdminPassword bootstrap the very first admin
// account: when the users table is empty at startup, this admin is
// created. No-op once any user exists.
InitAdminUsername string
InitAdminPassword string
// DevAutoLogin registers POST {mount}/dev/login which creates a session
// as the init admin without credentials, and advertises the capability in
// GET {mount}/config. NEVER enable outside development builds.
DevAutoLogin bool
// MaxAvatarBytes limits avatar upload request bodies, including multipart
// overhead. Non-positive values use DefaultMaxAvatarBytes.
MaxAvatarBytes int64
}
Config configures a goauth instance. DB and Redis are required; everything else has sensible defaults.
type InputError ¶
type InputError struct {
// contains filtered or unexported fields
}
InputError marks validation problems that should surface as HTTP 400/409 instead of 500.
func (InputError) Error ¶
func (e InputError) Error() string
type OIDCMode ¶
type OIDCMode string
OIDCMode controls how OIDC participates in login.
const ( // OIDCModeDisabled: local login only (password + passkey). OIDCModeDisabled OIDCMode = "disabled" // OIDCModeOptional: local login stays fully usable; enabled OIDC // providers are listed as additional buttons on the login page. OIDCModeOptional OIDCMode = "optional" // OIDCModeRequired: OIDC is the default and required method; local login // is bypassed and password/passkey endpoints are rejected. OIDCModeRequired OIDCMode = "required" )
type OIDCProvider ¶
type OIDCProvider struct {
gorm.Model
Name string `gorm:"not null"`
IssuerURL string `gorm:"not null"`
ClientID string `gorm:"not null"`
ClientSecret string `gorm:"not null"`
// Scopes are extra scopes requested in addition to "openid profile".
Scopes string `gorm:"not null;default:''"`
// AutoProvision creates a local account on first login for unknown
// subjects. When false, only pre-linked users may log in.
AutoProvision bool `gorm:"not null"`
Enabled bool `gorm:"not null"`
}
OIDCProvider is a runtime-configurable OpenID Connect provider.
func (OIDCProvider) TableName ¶
func (OIDCProvider) TableName() string
type ProfilePatch ¶
ProfilePatch is a partial self-service update of the caller's profile.
type Settings ¶
type Settings struct {
ID uint `gorm:"primarykey"`
OIDCMode OIDCMode `gorm:"column:oidc_mode;type:varchar(16);not null;default:disabled"`
UpdatedAt time.Time
}
Settings is the single-row runtime configuration.
type User ¶
type User struct {
gorm.Model
Username string `gorm:"uniqueIndex:idx_auth_users_username_active,where:deleted_at IS NULL;not null"`
// Email is an optional, normalized login identifier. NULL means unset;
// uniqueness holds among active users only.
Email *string `gorm:"uniqueIndex:idx_auth_users_email_active,where:deleted_at IS NULL"`
PasswordHash *string `gorm:"type:text"`
Role Role `gorm:"type:varchar(16);not null;default:user"`
Disabled bool `gorm:"not null;default:false"`
SessionVersion int `gorm:"not null;default:0"` // bumped to revoke all existing sessions of the user
// OIDC identity link (set when the account was provisioned by or linked
// to an OIDC provider).
OIDCProviderID *uint `gorm:"column:oidc_provider_id;index"`
OIDCSub *string `gorm:"column:oidc_sub;index"`
Credentials []WebauthnCredential `gorm:"foreignKey:UserID"`
}
User is an account managed by goauth.
func CurrentUser ¶
CurrentUser returns the authenticated user attached by RequireAuthenticated (or RequireRole), or nil.
func UserFromContext ¶
UserFromContext returns the authenticated user from a request context (for GraphQL resolvers and services), or nil.
func (*User) HasPassword ¶
HasPassword reports whether local password login is possible for the user.
type UserAvatar ¶
type UserAvatar struct {
UserID uint `gorm:"primaryKey;autoIncrement:false"`
User User `gorm:"foreignKey:UserID;references:ID;constraint:OnDelete:CASCADE"`
ContentType string `gorm:"not null"`
Data []byte `gorm:"not null"`
UpdatedAt time.Time
}
UserAvatar stores the user's avatar image independently of the account row.
func (UserAvatar) TableName ¶
func (UserAvatar) TableName() string
type UserDTO ¶
type UserDTO struct {
ID uint `json:"id"`
Username string `json:"username"`
Email *string `json:"email"`
Role Role `json:"role"`
Disabled bool `json:"disabled"`
HasPassword bool `json:"hasPassword"`
PasskeyCount int `json:"passkeyCount"`
OIDCLinked bool `json:"oidcLinked"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
UserDTO is the JSON shape of a user returned by the API.
type WebauthnCredential ¶
type WebauthnCredential struct {
gorm.Model
UserID uint `gorm:"index;not null"`
Name string `gorm:"not null"`
CredentialID string `gorm:"uniqueIndex;not null"` // base64url of the credential ID
Credential []byte `gorm:"type:jsonb;not null"`
LastUsedAt *time.Time
}
WebauthnCredential stores a registered passkey. The raw webauthn credential is serialized as JSON in Credential.
func (WebauthnCredential) TableName ¶
func (WebauthnCredential) TableName() string