middleware

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const HealthPath = "/healthz"

HealthPath - the address answering whether the site is up.

View Source
const MaxRequestBody = 64 << 20

MaxRequestBody - the largest request body the application reads (64 MiB): the CSRF check parses a form's body before any route sees it, so a route's own limit comes too late for an oversized upload. A proxy in front (nginx client_max_body_size) usually limits it more.

View Source
const RouteNone = "none"

RouteNone - the route label of a request no route served (a redirect, a blocked visitor, the maintenance page, an address nothing matches).

Variables

View Source
var DurationBuckets = []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5}

DurationBuckets - the upper bounds (seconds) of the response time histogram.

Functions

func ActorMiddleware

func ActorMiddleware(next http.Handler) http.Handler

ActorMiddleware puts who acts in the request's context (audit.Actor): the signed-in user (OptionalAuthMiddleware, around it, found them) and the client's address - the actions the request records (audit.Record) carry them.

func AdminSaveAuditMiddleware

func AdminSaveAuditMiddleware(next http.Handler) http.Handler

AdminSaveAuditMiddleware records a saved admin settings page for the action log (audit.SettingsSave): a POST answered with a redirect that tells of no error (no "err" in its query: ?error=, ?perf=err…). The page is named by its admin menu item.

func AuthJSONMiddleware

func AuthJSONMiddleware(store *sessions.CookieStore) func(http.Handler) http.Handler

AuthJSONMiddleware requires a logged-in user and responds with JSON 401 if the session is missing or invalid.

func AuthMiddleware

func AuthMiddleware(store *sessions.CookieStore) func(http.Handler) http.Handler

AuthMiddleware requires a session-authenticated user, redirecting to login otherwise.

func BlockedBotMiddleware

func BlockedBotMiddleware(svc service.BlockedBotService) func(http.Handler) http.Handler

BlockedBotMiddleware returns 403 Forbidden for requests whose User-Agent matches a blocked pattern

func BlockedIPMiddleware

func BlockedIPMiddleware(svc service.BlockedIPService) func(http.Handler) http.Handler

BlockedIPMiddleware returns 403 Forbidden for requests from blocked IPs

func BodyLimitMiddleware

func BodyLimitMiddleware(limit int64) func(http.Handler) http.Handler

BodyLimitMiddleware caps every request body at limit bytes: reading past it fails (and the form parse with it).

func CSRFMiddleware

func CSRFMiddleware(store *sessions.CookieStore, tooLarge http.Handler) func(http.Handler) http.Handler

CSRFMiddleware rejects every state-changing request (POST, PUT, PATCH, DELETE) that doesn't carry the session's CSRF token: the csrf_token form field or the X-CSRF-Token header. Reading a page creates no session for a visitor without one (no cookie: a guest's page can be cached by a CDN); the token is created when a page's script asks for it (GET /api/csrf-token, csrf_head) or a controller puts it in a form. A visitor with a session gets the token on any request, as before. csrfExemptPaths take no token. A form body past the request limit (BodyLimitMiddleware) can't be checked: it gets tooLarge (nil - a plain 413).

func ContentAccessMiddleware

func ContentAccessMiddleware(visitor func(ctx context.Context, userID int) (entity.ContentVisitor, error), logger *slog.Logger) func(http.Handler) http.Handler

ContentAccessMiddleware puts in the request's context what of the content its visitor may not view (entity.WithContentVisitor): every node and comment query of the request leaves it out. visitor - that of the signed-in user userID (0 - a guest). A failed check is a 500, never a request that sees everything. Inside OptionalAuth: it sees the user.

func GetNode

func GetNode(r *http.Request) (*entity.Node, bool)

GetNode - the node the node access middleware put in r's context.

func GetUser

func GetUser(r *http.Request) (*entity.User, bool)

GetUser - the signed-in user the node access middleware put in r's context; false - a guest.

func GetUserID

func GetUserID(r *http.Request) (int, bool)

GetUserID - the ID of r's signed-in user; false - a guest.

func GetUserIDFromContext

func GetUserIDFromContext(ctx context.Context) (int, bool)

GetUserIDFromContext returns the user ID from the context (set by AuthMiddleware).

func HealthMiddleware

func HealthMiddleware(ping func(context.Context) error) func(http.Handler) http.Handler

HealthMiddleware answers GET HealthPath before every other layer (the maintenance page, a session, the routes): 200 "ok" when ping (the database) answers within a few seconds, else 503 - for a load balancer, a container's health check, or app sites update waiting for a site it restarted. Any other request goes on to next.

func InactiveUserSessionMiddleware

func InactiveUserSessionMiddleware(store *sessions.CookieStore, userRepo entity.UserRepository, log *slog.Logger) func(http.Handler) http.Handler

InactiveUserSessionMiddleware drops user_id from the session when the account is no longer allowed to be logged in (blocked, pending approval, deleted), or the session's version isn't the account's any more (its sessions were ended: a new password, two-factor sign-in turned on or off - UserRepository.BumpSessionVersion).

Sessions are signed cookies, so blocking a user in the admin does not revoke an existing login by itself: the status is only checked at login time. Without this middleware a user who was logged in before being blocked keeps full access until the cookie expires.

Must be the outermost session-aware middleware: gorilla/sessions caches the session in the request context, so every downstream store.Get / GetUserID sees the cleared session and the request is handled as anonymous. The updated cookie is also sent back, logging the user out.

func LanguageMiddleware

func LanguageMiddleware(next http.Handler) http.Handler

LanguageMiddleware - the request's language from its address's prefix (entity.LanguageOfPrefix): /en/news/x is served as /news/x in English (i18n.WithLang: the interface, a new node's language), /en and /en/ as the front page; any other address - the site's default language. The site has no other languages - nothing to do.

func MaintenanceContextMiddleware

func MaintenanceContextMiddleware(svc service.MaintenanceService) func(http.Handler) http.Handler

MaintenanceContextMiddleware stores maintenance mode flag and message in request context so handlers can show a banner for users allowed to browse during maintenance. Must wrap the same routes as MaintenanceMiddleware and run outside it (executed first on incoming requests).

func MaintenanceMiddleware

func MaintenanceMiddleware(
	svc service.MaintenanceService,
	authSvc service.AuthService,
	userRepo entity.UserRepository,
	store *sessions.CookieStore,
	siteRepo entity.SiteInformationRepository,
) func(http.Handler) http.Handler

MaintenanceMiddleware returns 503 with maintenance message for users without permission when maintenance is enabled

func MaintenancePayloadFromRequest

func MaintenancePayloadFromRequest(r *http.Request) (enabled bool, message string)

MaintenancePayloadFromRequest returns maintenance-on flag and admin message HTML (may be empty).

func NodeAccessByIDMiddleware

func NodeAccessByIDMiddleware(
	nodeByIDFn func(context.Context, int) (*entity.Node, error),
	getUserFn func(context.Context, int) (*entity.User, error),
	authService service.AuthService,
	permission NodePermission,
	notFound http.HandlerFunc,
) func(http.Handler) http.Handler

NodeAccessByIDMiddleware checks node access by node ID.

func NodeAccessBySlugMiddleware

func NodeAccessBySlugMiddleware(
	nodeBySlugFn func(context.Context, string) (*entity.Node, error),
	getUserFn func(context.Context, int) (*entity.User, error),
	authService service.AuthService,
	permission NodePermission,
	notFound http.HandlerFunc,
	dynamicListFallback func(w http.ResponseWriter, r *http.Request) bool,
) func(http.Handler) http.Handler

NodeAccessBySlugMiddleware checks node access by slug.

dynamicListFallback runs only when no node matches the slug; it serves Views pages (/{view.URLPath}) through the same catch-all route, since next is never reached on a not-found slug. nil skips straight to 404.

func NodeCreateAccessByTypeMiddleware

func NodeCreateAccessByTypeMiddleware(
	getUserFn func(context.Context, int) (*entity.User, error),
	authService service.AuthService,
) func(http.Handler) http.Handler

NodeCreateAccessByTypeMiddleware checks that the request's user may create content of the route's {type} (a guest is sent to sign in); the handler finds a node of the type in the context (GetNode).

func NodeIDRedirect

func NodeIDRedirect(
	nodeByIDFn func(context.Context, int) (*entity.Node, error),
	getUserFn func(context.Context, int) (*entity.User, error),
	authService service.AuthService,
) func(w http.ResponseWriter, r *http.Request) bool

NodeIDRedirect - the slug route's fallback for /node/<id> (no node or View has that address): whoever may view node <id> goes to its own address, the query kept - a link that outlives the address (the action log's). A temporary redirect: the address may change. One who may not view it is answered as on its page (the login, 403). false - not such a path, or no such node (the caller answers 404).

func NotFoundHooksMiddleware

func NotFoundHooksMiddleware(next http.Handler) http.Handler

NotFoundHooksMiddleware tells the hooks of service.OnNotFound of a GET or HEAD answered 404 (its path and referrer). It sits inside the redirects and the blocks: a redirected path or a blocked bot never gets here. Without hooks it only passes the request on.

func OptionalAuthMiddleware

func OptionalAuthMiddleware(store *sessions.CookieStore) func(http.Handler) http.Handler

OptionalAuthMiddleware adds the user ID to the context if there is a valid session, and continues without redirecting otherwise.

func PageCacheMiddleware

func PageCacheMiddleware(maxAge int, sessionCookie string) func(http.Handler) http.Handler

PageCacheMiddleware lets a shared cache (a CDN in front of the site) keep guests' pages: a GET or HEAD from a visitor without the session cookie answered with a 200 HTML page that sets no cookie and no Cache-Control of its own gets "public, max-age=0, s-maxage=<maxAge>" (the CDN keeps it maxAge seconds, browsers ask again); every other HTML answer gets "private, no-store", so a signed-in visitor's page is never shared. maxAge <= 0 - off: answers are left as they are.

func PermissionMiddleware

func PermissionMiddleware(userRepo entity.UserRepository, authService service.AuthService, permission string) func(http.Handler) http.Handler

PermissionMiddleware ensures the user is signed in and has the given permission, e.g. service.PermAccessAdmin for /admin.

func RecoverMiddleware

func RecoverMiddleware(logger *slog.Logger) func(http.Handler) http.Handler

RecoverMiddleware turns a handler's panic into a 500 and an error line with the stack in the site's log; net/http would drop the connection and print it to stderr only. http.ErrAbortHandler passes on: it is the way to abort a response.

func RedirectMiddleware

func RedirectMiddleware(svc service.RedirectService) func(http.Handler) http.Handler

RedirectMiddleware issues a 301 when the request path matches a configured redirect.

func RequestIDMiddleware

func RequestIDMiddleware(next http.Handler) http.Handler

RequestIDMiddleware gives every request an id: a trusted proxy's X-Request-Id when it has a valid one (nginx's $request_id, so its log and the site's share it), else a new one. The id goes back in the X-Request-Id header and in the request's context (requestid.FromContext; the log lines written with the context carry it).

func RouteRecorder

func RouteRecorder(routes http.Handler) http.Handler

RouteRecorder wraps the routes (the ServeMux): after a request, it tells HTTPObserver the pattern that served it and the signed-in user, which the layers outside can't see in their copy of the request.

func SecurityHeadersMiddleware

func SecurityHeadersMiddleware(next http.Handler) http.Handler

SecurityHeadersMiddleware sets the headers of every response: no guessing of a type other than the one sent (nosniff), no framing by another site (a page under someone else's buttons), the address sent to another site without its path and query (they may carry a token), and, over HTTPS, HSTS.

func SetErrorPages

func SetErrorPages(p ErrorPages)

SetErrorPages sets the pages of the middleware's error responses.

func ThemePreviewMiddleware

func ThemePreviewMiddleware(store *sessions.CookieStore, userRepo entity.UserRepository, authService service.AuthService) func(http.Handler) http.Handler

ThemePreviewMiddleware renders the request in the theme the signed-in user previews (paths.WithTheme): the session's themes.PreviewSessionKey, when the user may change the theme (service.PermAccessAdmin, as the Appearance page) and the theme is available and not the active one; any other request is left as it is. Must run after OptionalAuthMiddleware.

func TwoFactorSetupMiddleware

func TwoFactorSetupMiddleware(needed func(ctx context.Context, userID int) bool, setupPath string) func(http.Handler) http.Handler

TwoFactorSetupMiddleware sends a signed-in user who must turn two-factor sign-in on (needed: their role needs it, it's off) to its page (setupPath): a page they open goes there, any other request is refused. Signed-out visitors and everyone else pass.

func UserLastAccessMiddleware

func UserLastAccessMiddleware(userRepo entity.UserRepository, log *slog.Logger) func(http.Handler) http.Handler

UserLastAccessMiddleware updates accessed_at for logged-in users, throttled, and skips static file paths. Must run inside OptionalAuthMiddleware so context carries user_id.

func UserMemoMiddleware

func UserMemoMiddleware(next http.Handler) http.Handler

UserMemoMiddleware - a request reads a user by ID from the database once (entity.WithUserMemo): its session's, its handler's and its page data's lookups of the signed-in user are one query.

func WithNode

func WithNode(ctx context.Context, node *entity.Node) context.Context

WithNode - ctx carrying node, as the node routes set it for the handlers (GetNode); used to render a node as an error page.

Types

type ErrorPages

type ErrorPages struct {
	Forbidden http.HandlerFunc
	NotFound  http.HandlerFunc
	// Rejected says why what was sent is refused (status, a message in
	// the visitor's language).
	Rejected func(w http.ResponseWriter, r *http.Request, status int, message string)
	// ExpiredForm - the message of a form whose CSRF token has expired.
	ExpiredForm func(r *http.Request) string
}

ErrorPages - the site's pages the middleware answers errors with (set at startup, SetErrorPages); a missing one is plain text.

type HTTPObserver

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

HTTPObserver - the requests' metrics (kosatka_http_…) and their log lines, each optional.

func NewHTTPObserver

func NewHTTPObserver(reg *metrics.Registry, requestLog *slog.Logger) *HTTPObserver

NewHTTPObserver - the requests' metrics added to reg (nil - none) and a line a request written to requestLog (nil - none); nil when neither.

func (*HTTPObserver) Middleware

func (o *HTTPObserver) Middleware(next http.Handler) http.Handler

Middleware counts and times each request and writes its log line. It goes outside the routes' layers, which RouteRecorder (around the routes) tells the route; a nil observer - next as it is.

type NodePermission

type NodePermission string

NodePermission - what a request does to a node, the node access middleware's check (hasPermission).

const (
	PermissionView    NodePermission = "view"
	PermissionEdit    NodePermission = "edit"
	PermissionDelete  NodePermission = "delete"
	PermissionCreate  NodePermission = "create"
	PermissionPublish NodePermission = "publish"
)

The node permissions: viewing, editing, deleting, creating (of the route's type) and publishing a node.

type UserTimezones

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

UserTimezones puts the request's time zone into its context (sitetime.WithLocation): the logged-in user's zone when user time zones are on, else the site's. User zones are cached; Forget drops one.

func NewUserTimezones

func NewUserTimezones(lookup func(ctx context.Context, userID int) (string, error)) *UserTimezones

NewUserTimezones - lookup gives a user's stored zone ("" - none).

func (*UserTimezones) Forget

func (u *UserTimezones) Forget(userID int)

Forget drops the cached zone of userID (their profile changed).

func (*UserTimezones) Middleware

func (u *UserTimezones) Middleware(next http.Handler) http.Handler

Middleware must run after OptionalAuthMiddleware (needs the user ID in the context).

Jump to

Keyboard shortcuts

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