Version: v1.17.0 Latest Latest

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

Go to latest
Published: Feb 27, 2023 License: Apache-2.0 Imports: 40 Imported by: 0



Package middleware contains application specific gin middleware functions.

Package middleware defines shared middleware for handlers.

Package middleware defines shared middleware for handlers.

Package middleware defines shared middleware for handlers.



View Source
const (
	// CSRFHeaderField is the name of the header where the CSRF token resides.
	CSRFHeaderField = "X-CSRF-Token"

	// CSRFFormField is the form field name.
	CSRFFormField         = "csrf_token"
	CSRFFormFieldTemplate = `<input type="hidden" name="%s" value="%s" />`

	// CSRFMetaTagName is the meta tag name (used by Javascript).
	CSRFMetaTagName     = "csrf-token"
	CSRFMetaTagTemplate = `<meta name="%s" content="%s">`

	// TokenLength is the length of the token (in bytes).
	TokenLength = 64
View Source
const (
	ErrMissingExistingToken = Error("missing existing csrf token in session")
	ErrMissingIncomingToken = Error("missing csrf token in request")
	ErrInvalidToken         = Error("invalid csrf token")
View Source
const (
	HeaderDebug         = "x-debug"
	HeaderDebugBuildID  = "x-build-id"
	HeaderDebugBuildTag = "x-build-tag"
View Source
const (
	HeaderAcceptLanguage = "Accept-Language"
	QueryKeyLanguage     = "lang"

	LeftAlign  = "ltr"
	RightAlign = "rtl"
View Source
const (
	// APIKeyHeader is the authorization header required for APIKey protected requests.
	APIKeyHeader = "X-API-Key"
View Source
const ChaffHeader = "X-Chaff"

ChaffHeader is the chaff header key.

View Source
const (
	// NonceHeader is the header for the incoming nonce
	NonceHeader = "X-Nonce"


This section is empty.


func AddOperatingSystemFromUserAgent added in v0.26.0

func AddOperatingSystemFromUserAgent() mux.MiddlewareFunc

func ChaffHeaderDetector added in v0.19.0

func ChaffHeaderDetector() chaff.Detector

ChaffHeaderDetector returns a chaff header detector.

func CheckSessionIdleNoAuth added in v0.22.0

func CheckSessionIdleNoAuth(h *render.Renderer, sessionIdleTTL time.Duration) mux.MiddlewareFunc

CheckSessionIdleNoAuth is an explicit check for session idleness. This check is also performed along with authentication and is intended to be used when no other auth check is performed.

func ConfigureStaticAssets added in v0.26.0

func ConfigureStaticAssets(devMode bool) mux.MiddlewareFunc

ConfigureStaticAssets configures headers for static assets.

func GzipResponse added in v0.26.0

func GzipResponse() mux.MiddlewareFunc

GzipResponse serves gzipped responses if the requestor supports gzip.

func HandleCSRF added in v0.26.0

func HandleCSRF(h *render.Renderer) mux.MiddlewareFunc

HandleCSRF first extracts an existing CSRF token from the session (if one exists). Then, it generates a unique, per-request CSRF token and stores it in the session. This must come after RequireSession to ensure the session has been populated.

func InjectCurrentPath added in v0.9.0

func InjectCurrentPath() mux.MiddlewareFunc

func LoadCurrentMembership added in v0.19.0

func LoadCurrentMembership(h *render.Renderer) mux.MiddlewareFunc

LoadCurrentMembership attempts to load the current membership. If there is no current membership in the session, it does nothing. If a membership exists, but fails to load from the database/cache, it returns an error. Use RequireMembership to enforce membership.

This must come after RequireAuth so that the user is loaded onto the context.

func LoadDynamicTranslations added in v0.30.0

func LoadDynamicTranslations(locales *i18n.LocaleMap, db *database.Database, cacher cache.Cacher, period time.Duration) (mux.MiddlewareFunc, error)

func MutateMethod added in v0.3.0

func MutateMethod() mux.MiddlewareFunc

MutateMethod looks for HTML form values that define the "real" HTTP method and then forward that along to the router. This must be a very early middleware.

func OnlyIfEnabled added in v0.21.0

func OnlyIfEnabled(enabled bool, h *render.Renderer) mux.MiddlewareFunc

OnlyIfEnabled can be used to hide legitimate routes behind a 404 if the feature has been disabled.

func PopulateLogger added in v0.16.0

func PopulateLogger(originalLogger *zap.SugaredLogger) mux.MiddlewareFunc

PopulateLogger populates the logger onto the context. This must come AFTER PopulateRequestID and PopulateTraceID.

func PopulateRequestID added in v0.16.0

func PopulateRequestID(h *render.Renderer) mux.MiddlewareFunc

PopulateRequestID populates the request context with a random UUID.

func PopulateTemplateVariables

func PopulateTemplateVariables(cfg *config.ServerConfig) mux.MiddlewareFunc

PopulateTemplateVariables populates the template variables with common information and bootstraps the map for more values to be set by other middlewares.

func PopulateTraceID added in v1.3.0

func PopulateTraceID() mux.MiddlewareFunc

PopulateTraceID populates the trace ID injected by Google Cloud (if it exists).

func ProcessChaff added in v0.18.0

func ProcessChaff(db *database.Database, t *chaff.Tracker, det chaff.Detector) mux.MiddlewareFunc

ProcessChaff injects the chaff processing middleware. If chaff requests send a value of "daily" (case-insensitive), they will be counted toward the realm's total active users and return a chaff response. Any other values will only return a chaff response.

This must come after RequireAPIKey.

func ProcessDebug added in v0.8.0

func ProcessDebug() mux.MiddlewareFunc

ProcessDebug adds additional debugging information to the response if the request included the "X-Debug" header with any value.

func ProcessFirewall added in v0.10.0

func ProcessFirewall(h *render.Renderer, typ string) mux.MiddlewareFunc

ProcessFirewall verifies the application-level firewall configuration.

This must come after the realm has been loaded in the context, probably via a different middleware.

func ProcessLocale added in v0.17.0

func ProcessLocale(locales *i18n.LocaleMap) mux.MiddlewareFunc

ProcessLocale extracts the locale from the various possible locations and sets the template translator to the correct language.

This must be called after the template map has been created.

func ProcessNonce added in v0.31.0

func ProcessNonce(h *render.Renderer) mux.MiddlewareFunc

ProcessNonce reads the X-Nonce header and stores it in the context.

func QueryHeaderInjection added in v0.26.0

func QueryHeaderInjection(header, queryParam string) mux.MiddlewareFunc

QueryHeaderInjection is for development and should not be installed in production flows. This middleware will take query params from a get request and copy them to

func Recovery added in v0.23.0

func Recovery(h *render.Renderer) mux.MiddlewareFunc

Recovery recovers from panics and other fatal errors. It keeps the server and service running, returning 500 to the caller while also logging the error in a structured format.

func RequireAPIKey

func RequireAPIKey(cacher cache.Cacher, db *database.Database, h *render.Renderer, allowedTypes []database.APIKeyType) mux.MiddlewareFunc

RequireAPIKey reads the X-API-Key header and validates it is a real authorized app. It also ensures currentAuthorizedApp is set in the template map.

func RequireAuth

func RequireAuth(cacher cache.Cacher, authProvider auth.Provider, db *database.Database, h *render.Renderer, sessionIdleTTL, expiryCheckTTL time.Duration) mux.MiddlewareFunc

RequireAuth requires a user to be logged in. It also fetches and stores information about the user on the request context.

func RequireEmailVerified added in v0.19.0

func RequireEmailVerified(authProvider auth.Provider, h *render.Renderer) mux.MiddlewareFunc

RequireEmailVerified requires a user to have verified their login email.

MUST first run RequireAuth to populate user and RequireRealm to populate the realm.

func RequireHeader added in v0.4.0

func RequireHeader(header string, h *render.Renderer) mux.MiddlewareFunc

RequireHeader requires that the request have a certain header present. The header just needs to exist - it does not need to have a specific value.

func RequireHeaderValues added in v0.4.0

func RequireHeaderValues(header string, allowed []string, h *render.Renderer) mux.MiddlewareFunc

RequireHeaderValues requires that the request have a certain header present and that the value be one of the supplied entries.

func RequireHostHeader added in v0.26.0

func RequireHostHeader(allowed []string, h *render.Renderer, stripPort bool) mux.MiddlewareFunc

RequireHostHeader requires that the request's host header is one of the allowed values.

func RequireMFA added in v0.8.0

func RequireMFA(authProvider auth.Provider, h *render.Renderer) mux.MiddlewareFunc

RequireMFA checks the realm's MFA requirements and enforces them. Use requireRealm before requireMFA to ensure the currently selected realm is on context. If no realm is selected, this assumes MFA is required.

func RequireMembership added in v0.19.0

func RequireMembership(h *render.Renderer) mux.MiddlewareFunc

RequireMembership requires a membership (realm selection) to exist in the session.

This must come after LoadCurrentMembership so the membership is on the context

func RequireNamedSession added in v0.28.0

func RequireNamedSession(store sessions.Store, name string, splitValues []interface{}, h *render.Renderer) func(http.Handler) http.Handler

RequireNamedSession retrieves or creates a new session with a specific name, other than the default session name.

func RequireSession

func RequireSession(store sessions.Store, splitValues []interface{}, h *render.Renderer) func(http.Handler) http.Handler

RequireSession retrieves or creates a new session and stores it on the request's context for future retrieval. It also ensures the flash data is populated in the template map. Any handler that wants to utilize sessions should use this middleware.

func RequireSystemAdmin added in v0.16.0

func RequireSystemAdmin(h *render.Renderer) mux.MiddlewareFunc

RequireSystemAdmin requires the current user is a global administrator. It must come after RequireAuth so that a user is set on the context.

func SecureHeaders added in v0.6.0

func SecureHeaders(devMode bool, serverType string) mux.MiddlewareFunc

SecureHeaders sets a bunch of default secure headers that our servers should have.

func WithObservability added in v0.18.0

func WithObservability(ctx context.Context) (context.Context, mux.MiddlewareFunc)

WithObservability sets common observability context fields.


type Error added in v0.26.0

type Error string

func (Error) Error added in v0.26.0

func (e Error) Error() string

type Path added in v0.9.0

type Path struct {
	// contains filtered or unexported fields

func (*Path) IsDir added in v0.9.0

func (p *Path) IsDir(s string) bool

func (*Path) IsFile added in v0.9.0

func (p *Path) IsFile(s string) bool

func (*Path) IsPath added in v0.9.0

func (p *Path) IsPath(s string) bool

func (*Path) String added in v0.16.0

func (p *Path) String() string

Jump to

Keyboard shortcuts

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