authkit

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package authkit serves gouncer sessions over HTTP.

Index

Constants

View Source
const MaxRequestBodyBytes = 1 << 20

MaxRequestBodyBytes caps how much of a request body Decode will read, so an unauthenticated caller cannot exhaust memory.

Variables

View Source
var ErrInvalidCredentials = errors.New("authkit: invalid credentials")

ErrInvalidCredentials reports a login that names no enabled account.

View Source
var ErrSelfDisable = errors.New("authkit: cannot disable your own account")

ErrSelfDisable reports an account disabling itself.

Functions

func CreateAdmin

func CreateAdmin(
	ctx context.Context,
	store gouncer.Store,
	email string,
	name string,
	stdin io.Reader,
	stdout io.Writer,
) error

CreateAdmin provisions a user account for command-line bootstrapping, reading the password as one line from stdin.

func Decode

func Decode[T any](w http.ResponseWriter, r *http.Request) (T, error)

Decode reads and JSON-decodes a single request body into a value of type T, bounding the body size and rejecting trailing content.

func EnsureAdmin added in v0.2.0

func EnsureAdmin(ctx context.Context, store gouncer.Store, email, name, password string) (bool, error)

EnsureAdmin creates a user account unless the email is already taken, reporting whether it created the account.

func Respond

func Respond(w http.ResponseWriter, status int, v any)

Respond writes v as a JSON response with the given status code, falling back to a 500 error payload if marshaling fails.

func RespondError

func RespondError(w http.ResponseWriter, status int, message string)

RespondError writes a JSON error response with the given status code and message.

func StatusForAuthError

func StatusForAuthError(err error) (int, string, bool)

StatusForAuthError returns the HTTP status code and client-facing message for a gouncer error, reporting false for errors it does not recognize.

func WithIdentity

func WithIdentity(ctx context.Context, id Identity) context.Context

WithIdentity returns a context carrying the authenticated user's identity.

Types

type Account added in v0.4.0

type Account struct {
	ID        uuid.UUID `json:"id"`
	Email     string    `json:"email"`
	Name      string    `json:"name"`
	Disabled  bool      `json:"disabled"`
	CreatedAt time.Time `json:"created_at"`
}

Account is one user account as administration reports it.

type AdminHandlers

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

AdminHandlers serves user administration over HTTP. Mount its handlers behind RequireSession.

func NewAdmin

func NewAdmin(store AdminStore) *AdminHandlers

NewAdmin returns AdminHandlers administering the accounts in store.

func (*AdminHandlers) Create

func (a *AdminHandlers) Create(w http.ResponseWriter, r *http.Request)

Create decodes credentials, creates a user account, persists it, and responds with the created account.

func (*AdminHandlers) CreateAccount added in v0.4.0

func (a *AdminHandlers) CreateAccount(ctx context.Context, email, name, password string) (Account, error)

CreateAccount validates and persists a new user account.

func (*AdminHandlers) List

func (a *AdminHandlers) List(w http.ResponseWriter, r *http.Request)

List responds with every user account.

func (*AdminHandlers) ListAccounts added in v0.4.0

func (a *AdminHandlers) ListAccounts(ctx context.Context) ([]Account, error)

ListAccounts returns every user account ordered for display.

func (*AdminHandlers) SetAccountDisabled added in v0.4.0

func (a *AdminHandlers) SetAccountDisabled(ctx context.Context, actorID, id uuid.UUID, disabled bool) error

SetAccountDisabled updates whether the account may log in, refusing an actor disabling itself.

func (*AdminHandlers) SetDisabled

func (a *AdminHandlers) SetDisabled(w http.ResponseWriter, r *http.Request)

SetDisabled parses the user id from the request's "id" path value and updates whether that account may log in, refusing to disable the requester.

type AdminStore

type AdminStore interface {
	gouncer.Store

	// ListUsers returns every user account ordered for display.
	ListUsers(ctx context.Context) ([]gouncer.User, error)

	// SetUserDisabled updates whether the account may log in.
	SetUserDisabled(ctx context.Context, id uuid.UUID, disabled bool) error
}

AdminStore persists users for both login and administration.

type Config

type Config struct {
	// Store persists users and their login sessions.
	Store gouncer.Store
	// CookieName names the session cookie. Empty applies "__Host-session".
	// Names should keep the __Host- prefix to retain its browser guarantees.
	CookieName string
	// SessionTTL bounds issued sessions and their cookie alike. Zero
	// applies gouncer.DefaultSessionDuration.
	SessionTTL time.Duration
}

Config parameterizes the session transport.

type Handlers

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

Handlers serves login sessions over HTTP.

func New

func New(cfg Config) *Handlers

New returns Handlers serving sessions from cfg.Store.

func (*Handlers) Authenticate added in v0.4.0

func (h *Handlers) Authenticate(ctx context.Context, email, password string) (Identity, error)

Authenticate verifies credentials, answering the account identity or ErrInvalidCredentials.

func (*Handlers) CookieName added in v0.4.0

func (h *Handlers) CookieName() string

CookieName reports the configured session cookie name.

func (*Handlers) EndSession added in v0.4.0

func (h *Handlers) EndSession(ctx context.Context, token string) (*http.Cookie, error)

EndSession deletes the session behind token, returning the clearing cookie.

func (*Handlers) Login

func (h *Handlers) Login(w http.ResponseWriter, r *http.Request)

Login verifies credentials and issues a session cookie.

func (*Handlers) Logout

func (h *Handlers) Logout(w http.ResponseWriter, r *http.Request)

Logout deletes the current session and clears its cookie.

func (*Handlers) RequireSession

func (h *Handlers) RequireSession(next http.Handler) http.Handler

RequireSession admits only requests carrying a usable session cookie, passing the authenticated identity down through the request context.

func (*Handlers) Session

func (h *Handlers) Session(w http.ResponseWriter, r *http.Request)

Session reports the logged-in user, whose identity the RequireSession middleware already resolved.

func (*Handlers) SessionIdentity added in v0.4.0

func (h *Handlers) SessionIdentity(ctx context.Context, token string) (Identity, error)

SessionIdentity resolves the identity behind a session token.

func (*Handlers) StartSession added in v0.4.0

func (h *Handlers) StartSession(ctx context.Context, userID uuid.UUID) (*http.Cookie, error)

StartSession issues and persists a session for userID, returning its cookie.

type Identity

type Identity struct {
	ID    uuid.UUID `json:"id"`
	Email string    `json:"email"`
	Name  string    `json:"name"`
}

Identity is the authenticated user exposed to handlers, deliberately excluding credentials such as the password hash.

func IdentityFromContext

func IdentityFromContext(ctx context.Context) Identity

IdentityFromContext returns the identity stored by the RequireSession middleware, or the zero identity outside of it.

type Reaper

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

Reaper periodically deletes expired sessions until stopped.

func NewReaper

func NewReaper(store SessionReaper, cfg ReaperConfig) *Reaper

NewReaper returns a Reaper sweeping store per cfg.

func (*Reaper) Start

func (r *Reaper) Start()

Start launches the sweep loop in a goroutine. Call it once.

func (*Reaper) Stop

func (r *Reaper) Stop()

Stop cancels the sweep loop and waits for it to finish. Stopping a never-started Reaper is not an error.

type ReaperConfig

type ReaperConfig struct {
	// Interval is how often expired sessions are swept. Zero applies one hour.
	Interval time.Duration
	// Timeout bounds each sweep. Zero applies thirty seconds.
	Timeout time.Duration
	// Logger receives sweep outcomes. Nil applies slog.Default.
	Logger *slog.Logger
}

ReaperConfig parameterizes a Reaper.

type SessionReaper

type SessionReaper interface {
	DeleteExpiredSessions(ctx context.Context, now time.Time) (int64, error)
}

SessionReaper deletes sessions that have expired.

Directories

Path Synopsis
postgres module
ratelimit module
Package testkit provides test doubles for authkit consumers.
Package testkit provides test doubles for authkit consumers.

Jump to

Keyboard shortcuts

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