goauth

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

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

goauth

Reusable authentication stack for Echo + React applications:

  • Username + password login (argon2id) with Redis-backed throttling
  • Passkeys (WebAuthn, discoverable credentials)
  • OIDC (e.g. Authentik) — runtime-configurable from the admin API, either as an extra button on the login page (optional) or as the required, exclusive method that bypasses local login entirely (required)
  • Server-side sessions via SCS + Redis (cookie, SameSite=Lax, Origin CSRF check)
  • Admin API for user management, OIDC providers and mode switching
  • Init admin bootstrap — first admin created from config when the users table is empty
  • Dev auto-login — opt-in, dev-only endpoint for frictionless manual testing

The companion React package lives in web/auth-react.

Dependencies

Besides Echo, GORM and go-redis, the module uses SCS's official github.com/alexedwards/scs/goredisstore session store and one sibling module:

  • github.com/cyphix/gologg — zerolog-based structured logging. goauth obtains its logger via logg.Ctx("goauth", "core"), so log output automatically matches any host application that also logs through gologg (level, format and writer are configured once by the host).

Session keys use the goauth:session: prefix via goredisstore.NewWithPrefix. Hosts provide raw *gorm.DB and *redis.Client handles; goauth does not open their connections.

Note: go.mod resolves gologg through replace to a sibling checkout (../gologg). To use goauth standalone, check out these two repositories side by side, or remove that replacement and use the required tagged version.

Backend integration (Echo)

goauth is handed ready-made database handles — it never opens connections itself. Everything below assumes an existing Echo app.

1. Provide the handles. A *gorm.DB (Postgres, SQLite, … — auth tables are AutoMigrated with an auth_ prefix on New) and a *redis.Client (sessions + login throttling).

2. Assemble the module.

import "github.com/cyphix/goauth"

a, err := goauth.New(goauth.Config{
    DB:                gormDB,        // *gorm.DB — tables are AutoMigrated with an auth_ prefix
    Redis:             redisClient,   // *redis.Client — sessions + throttling
    RPDisplayName:     "My App",
    RPID:              "localhost",   // WebAuthn relying-party ID (domain); empty disables passkeys
    Origins:           []string{"http://localhost:5173"},  // browser origins: WebAuthn + Origin CSRF check
    PublicBaseURL:     "http://localhost:5173", // used for the OIDC redirect URL
    CookieSecure:      false,         // true behind HTTPS
    ClientIP:          nil,           // defaults to TCP peer; configure trusted proxy extraction if needed
    InitAdminUsername: os.Getenv("AUTH_INIT_ADMIN_USERNAME"),
    InitAdminPassword: os.Getenv("AUTH_INIT_ADMIN_PASSWD"),
    DevAutoLogin:      isDev, // NEVER outside development
})
if err != nil {
    log.Fatal(err)
}

Login throttling defaults to the TCP peer address, ignoring forwarded headers. If the app runs behind a reverse proxy, configure a trusted extractor such as echo.ExtractIPFromXFFHeader(echo.TrustIPRange(...)); otherwise all clients share the proxy's per-IP bucket and can lock each other out. The limits are 10 attempts per account and client IP, 30 per account across all IPs, and 100 per client IP across all accounts, each within five minutes.

3. Mount it on Echo. The session middleware must be global (it also performs the Origin CSRF check); routes mount under a group of your choice (/auth is what the React package expects by default):

e := echo.New()

e.Use(a.SessionMiddleware())          // global: session load/save + Origin CSRF check
a.RegisterRoutes(e.Group("/auth"))    // all auth endpoints

// Protect your own routes with the provided guards:
api := e.Group("/api", a.RequireAuthenticated())
admin := e.Group("/admin", a.RequireRole(goauth.RoleAdmin))

4. Read the current user where you need it:

user := goauth.CurrentUser(c)         // in Echo handlers
user := goauth.UserFromContext(ctx)   // in services / GraphQL resolvers

The init admin is created on startup when the users table is empty. On the frontend, use @cyphix/auth-react for the client, hooks and route guards, or call the endpoints below directly. Install the visual auth UI from the cyphix/react-components registry (auth-login-form, auth-profile-card, auth-passkeys-card, auth-users-card).

Avatars

Avatar routes are opt-in and independent of RegisterRoutes. Choose your app's paths and apply session/authentication and admin-role middleware on the groups:

me := e.Group("/api/me/avatar", a.SessionMiddleware(), a.RequireAuthenticated())
admin := e.Group("/api/admin", a.SessionMiddleware(), a.RequireRole(goauth.RoleAdmin))
a.RegisterAvatarRoutes(me, admin)

This mounts PUT/GET/DELETE /api/me/avatar and GET /api/admin/users/:id/avatar. For example, Worldbuilder can use /admin as the admin prefix instead. For custom routing, mount a.UploadAvatar, a.Avatar, a.DeleteAvatar and a.UserAvatar individually with the same middleware.

PUT accepts multipart field file. Config.MaxAvatarBytes limits the entire request (including multipart overhead), defaulting to 8 MiB. Nonempty uploads must sniff as image/*; bytes are stored as-is, without decoding or resizing. Upload replaces any existing avatar. Upload/delete return 204 and bump the user's updated_at for frontend cache busting. GET returns the stored content type and Cache-Control: private, max-age=0, must-revalidate, or 204 when absent.

UserAvatar stores bytes in auth_user_avatars, keyed by user_id with a foreign key to auth_users(id) and ON DELETE CASCADE (physical user deletion). Applications managing their own migrations must keep those migrations identical to goauth's models, including auth_user_avatars; goauth also adds the table through AutoMigrate. SQLite connections must enable foreign-key enforcement for cascading deletes (for example, _foreign_keys=on).

Endpoints (mounted at /auth by default)

Method Path Auth Purpose
GET /config — Login methods, OIDC mode/providers, dev auto-login flag
POST /login — Username + password
POST /logout session Destroy session
GET /me session Current user
POST /password session Change own password
POST /passkey/login/begin,finish — Discoverable passkey login
POST /passkey/register/begin,finish session Register a passkey
GET/DELETE /passkeys, /passkeys/:id session Manage own passkeys
GET /oidc/:id/start — Begin OIDC code flow (PKCE)
GET /oidc/callback — OIDC redirect URI
GET/POST/PATCH/DELETE /admin/users… admin User CRUD, role, disable, password reset
GET/POST/PATCH/DELETE /admin/oidc… admin OIDC provider CRUD
GET/PUT /admin/settings admin OIDC mode (disabled / optional / required)
POST /dev/login — Dev-only session as the init admin (flag-gated)

OIDC modes

  • disabled — local login only.
  • optional — local login stays fully usable; enabled providers are listed as buttons below the passkey button on the login page.
  • required — visiting the app unauthenticated goes straight to the provider; password/passkey endpoints are rejected. Switch back by an admin session (PUT /auth/admin/settings) or by clearing the auth_settings row.

Provider changes apply at runtime — discovery documents are cached per row revision and invalidated on admin edits.

Tests

go test ./...

The suite uses in-memory SQLite + miniredis, a mock OIDC provider and a software WebAuthn authenticator — no external services required.

Secret scanning

BetterLeaks gates pushes and PRs (.github/workflows/betterleaks.yml); the repo config lives in .betterleaks.toml. Enable the local pre-push scan once per clone:

./scripts/install-git-hooks.sh   # sets core.hooksPath; requires Docker or the betterleaks CLI
scripts/betterleaks-scan.sh      # manual scan of unpushed commits

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

View Source
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

View Source
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

func ContextWithUser(ctx context.Context, user *User) context.Context

ContextWithUser returns a child context that carries user for UserFromContext. Useful in GraphQL/service unit tests that do not go through Echo middleware.

func ErrInvalidInput

func ErrInvalidInput(msg string) error

ErrInvalidInput builds an InputError.

func IsInputError

func IsInputError(err error) bool

IsInputError reports whether err is an InputError.

func NormalizeEmail

func NormalizeEmail(email string) string

NormalizeEmail lowercases and trims an email address.

func NormalizeUsername

func NormalizeUsername(username string) string

NormalizeUsername lowercases and trims a username.

func ValidOIDCMode

func ValidOIDCMode(m OIDCMode) bool

ValidOIDCMode reports whether m is a known mode.

func ValidRole

func ValidRole(r Role) bool

ValidRole reports whether r is a known role.

Types

type Auth

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

Auth is the assembled authentication module.

func New

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

New validates the config, migrates the auth tables, bootstraps the init admin and returns a ready-to-mount Auth.

func (*Auth) Authenticate

func (a *Auth) Authenticate(identifier, password string) (*User, error)

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) Avatar

func (a *Auth) Avatar(c echo.Context) error

Avatar serves the current user's avatar, or 204 if none exists.

func (*Auth) ChangePassword

func (a *Auth) ChangePassword(userID uint, currentPassword, newPassword string) error

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

func (a *Auth) CreateUser(username, password, email string, role Role) (*User, error)

CreateUser creates a new local user. Password and email may be empty for accounts that only log in via passkey or OIDC.

func (*Auth) DB

func (a *Auth) DB() *gorm.DB

DB exposes the underlying GORM handle (mainly for tests and seeds).

func (*Auth) DeleteAvatar

func (a *Auth) DeleteAvatar(c echo.Context) error

DeleteAvatar removes the current user's avatar.

func (*Auth) DeleteUser

func (a *Auth) DeleteUser(id uint) error

DeleteUser soft-deletes a user, protecting the last active admin.

func (*Auth) EnsureUser

func (a *Auth) EnsureUser(username, password string, role Role) (*User, error)

EnsureUser creates the user when it does not exist yet; useful for seeding. Existing users are returned unchanged.

func (*Auth) FindUserByID

func (a *Auth) FindUserByID(id uint) (*User, error)

FindUserByID loads a user by primary key.

func (*Auth) FindUserByIdentifier

func (a *Auth) FindUserByIdentifier(identifier string) (*User, error)

FindUserByIdentifier loads a user by login identifier: username or email.

func (*Auth) FindUserByUsername

func (a *Auth) FindUserByUsername(username string) (*User, error)

FindUserByUsername loads a user by normalized username.

func (*Auth) GetSettings

func (a *Auth) GetSettings() (Settings, error)

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) ListUsers

func (a *Auth) ListUsers() ([]User, error)

ListUsers returns all users ordered by username.

func (*Auth) PasskeysEnabled

func (a *Auth) PasskeysEnabled() bool

PasskeysEnabled reports whether WebAuthn is configured.

func (*Auth) RegisterAvatarRoutes

func (a *Auth) RegisterAvatarRoutes(me, admin *echo.Group)

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

func (a *Auth) RegisterRoutes(g *echo.Group)

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

func (a *Auth) SetPassword(userID uint, password string) error

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

func (a *Auth) UpdateSettings(mode OIDCMode) (Settings, error)

UpdateSettings persists new runtime settings after validation.

func (*Auth) UpdateUser

func (a *Auth) UpdateUser(id uint, patch UserPatch) (*User, error)

UpdateUser applies an admin patch, protecting the last active admin from demotion or disabling.

func (*Auth) UploadAvatar

func (a *Auth) UploadAvatar(c echo.Context) error

UploadAvatar replaces the current user's avatar from multipart field file.

func (*Auth) UserAvatar

func (a *Auth) UserAvatar(c echo.Context) error

UserAvatar serves the avatar identified by :id. Callers must require admin role.

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

type ProfilePatch struct {
	Username *string
	Email    *string
}

ProfilePatch is a partial self-service update of the caller's profile.

type Role

type Role string

Role is the authorization role of a user.

const (
	RoleUser  Role = "user"
	RoleAdmin Role = "admin"
)

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.

func (Settings) TableName

func (Settings) TableName() string

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

func CurrentUser(c echo.Context) *User

CurrentUser returns the authenticated user attached by RequireAuthenticated (or RequireRole), or nil.

func UserFromContext

func UserFromContext(ctx context.Context) *User

UserFromContext returns the authenticated user from a request context (for GraphQL resolvers and services), or nil.

func (*User) HasPassword

func (u *User) HasPassword() bool

HasPassword reports whether local password login is possible for the user.

func (User) TableName

func (User) TableName() string

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 UserPatch

type UserPatch struct {
	Username *string
	Email    *string
	Role     *Role
	Disabled *bool
	Password *string
}

UserPatch is a partial admin update of a user.

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

Jump to

Keyboard shortcuts

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