Help us shape the future of Go! Take the 2026 Go Developer Survey

middleware

package
v1.21.2 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: GPL-3.0 Imports: 26 Imported by: 0

Documentation

Overview

Package middleware holds the Hertz middleware of the HTTP API: tracing, request logging and request metadata, CORS, session authentication and the administrator guard, the device transport envelope and the payment callback lookup. Middleware that needs module data declares the narrow interface it uses (SessionAccounts, PaymentMethods) and a module facade provides it, so the transport layer never reads a module's tables itself.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AdminGuard added in v1.21.0

func AdminGuard() app.HandlerFunc

AdminGuard admits only administrators. It runs after AuthMiddleware on the admin route groups, which the routes package opens only through a helper that installs both.

func AuthMiddleware

func AuthMiddleware(deps AuthDeps) app.HandlerFunc

func AuthenticateRequest

func AuthenticateRequest(ctx context.Context, deps AuthDeps, token string) (context.Context, error)

AuthenticateRequest resolves the session token to its account and returns ctx carrying the account, the session and the actor. A device session also needs its device to be enabled and still the account's.

The account gate (enabled, deleted, administrator) is read as stored now, not from the cached account row: that row lives for days and its invalidation is best effort, so a ban, deletion or demotion must not be served from it. The cached row still supplies the rest of the account, with the gate columns overlaid, so handlers see the current flags too.

func CorsMiddleware

func CorsMiddleware(c context.Context, ctx *app.RequestContext)

CorsMiddleware is the permissive CORS policy: it reflects any Origin and allows credentials, as the API always did. Deployments that configure AllowedOrigins get NewCorsMiddleware instead.

func DecryptDeviceRequest

func DecryptDeviceRequest(ctx context.Context, c *app.RequestContext, secret string, replayStore deviceauth.ReplayStore) error

DecryptDeviceRequest accepts only authenticated envelopes. All validation completes before plaintext is installed; unsigned query parameters cannot be mixed into an authenticated body or accepted on a bodyless POST.

func DeviceMiddleware

func DeviceMiddleware(configProvider func() config.DeviceConfig, replayStore deviceauth.ReplayStore) app.HandlerFunc

DeviceMiddleware applies the device transport to the requests of devices: the device login, a request that declares the device login type, and any request a device session signed in. The signed session counts without the Login-Type header too, so dropping the header cannot skip the transport. With transport security on, such a request is accepted only in a signed, encrypted envelope and the data of its response is encrypted for the device; a response that cannot be encrypted is replaced by an error, never sent in plaintext.

func EncryptDeviceResponse

func EncryptDeviceResponse(c *app.RequestContext, secret string) error

EncryptDeviceResponse preserves the data/time format and adds a signature.

func LoggerMiddleware

func LoggerMiddleware(enrichers ...requestmeta.Enricher) app.HandlerFunc

func NewCorsMiddleware added in v1.21.0

func NewCorsMiddleware(allowedOrigins []string) app.HandlerFunc

NewCorsMiddleware answers CORS for the browser origins in allowedOrigins, each as scheme://host[:port] and compared exactly (case-insensitively): a matching Origin is allowed with credentials, any other gets no CORS headers, so the browser refuses it the response. An empty list keeps the permissive default of reflecting whatever Origin the request carries, which is safe only while the API carries no cookie or ambient credential. Preflights are answered with 204 either way.

func NotifyMiddleware

func NotifyMiddleware(methods PaymentMethods) app.HandlerFunc

NotifyMiddleware resolves the payment method a gateway callback's URL names and puts it, with its platform, into the request context for the notify handler. A token that names no method, or a method of another platform than the URL's, is answered with 400 and the callback is not handled.

func OptionalAuthMiddleware

func OptionalAuthMiddleware(deps AuthDeps) app.HandlerFunc

OptionalAuthMiddleware authenticates a request when it supplies an Authorization header, while preserving anonymous access for routes that intentionally support guest checkout. Handlers on those routes must still explicitly require an authenticated user before operating on a user-owned resource.

func PaymentNotifyContext

func PaymentNotifyContext(ctx context.Context, methods PaymentMethods, platform, token string) (context.Context, error)

PaymentNotifyContext returns ctx carrying the payment method token names and its platform, refusing a method whose platform is not the URL's.

func RequireAdmin added in v1.21.0

func RequireAdmin(ctx context.Context) error

RequireAdmin reports whether the request's authenticated user is an administrator.

func TraceMiddleware

func TraceMiddleware() app.HandlerFunc

Types

type AuthDeps

type AuthDeps struct {
	JWT   config.JwtAuth
	Redis *redis.Client
	// Accounts resolves the session's account and device.
	Accounts SessionAccounts
}

AuthDeps is what request authentication needs: the session signing secret, the session store and the lookups of the session's account and device.

type PaymentMethods added in v1.21.0

type PaymentMethods interface {
	FindPaymentMethodByToken(ctx context.Context, token string) (*payment.Payment, error)
}

PaymentMethods finds the payment method whose notify URL carries a token. The billing facade provides it, so the middleware never reads billing's tables itself.

type PaymentParams

type PaymentParams struct {
	Platform string `uri:"platform"`
	Token    string `uri:"token"`
}

type SessionAccounts added in v1.21.0

type SessionAccounts interface {
	// FindUser returns the account, soft-deleted ones included, so a deleted
	// account is refused rather than reported as a lookup failure.
	FindUser(ctx context.Context, id int64) (*user.User, error)
	// FindAccountStateForAuth reads the account gate (enabled, deleted,
	// administrator) as stored now, bypassing caches, so a ban, deletion or
	// demotion refuses the account's sessions at once.
	FindAccountStateForAuth(ctx context.Context, id int64) (*user.AccountState, error)
	// FindDeviceForAuth reads the current device state, bypassing caches.
	FindDeviceForAuth(ctx context.Context, id int64) (*user.Device, error)
}

SessionAccounts resolves the account and device of a session. The identity facade provides it: the accounts and devices are identity's tables, which only the identity module reads.

Jump to

Keyboard shortcuts

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