middleware

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2023 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package middleware contains a collection of middleware for use with gin-gonic.

Index

Constants

View Source
const (
	ErrLoadIPLocationDBCode = 3501
)

Object error codes (3501-3750)

Variables

View Source
var (
	// JWTAuthHeader defines the name of the header holding the JWT authorization info.
	JWTAuthHeader = "Authorization"

	// JWTAuthTokenType defines the type of authorization token for the AuthHeader.
	JWTAuthTokenType = "Bearer"
)
View Source
var (
	// RedisRateLimitRemainingHeader is the header in which to store remaining rate limit information.
	RedisRateLimitRemainingHeader = "X-Redis-Rate-Limiter-Remaining"

	// RedisRateLimitRetryAfterHeader is the header in which to store retry information.
	RedisRateLimitRetryAfterHeader = "X-Redis-Rate-Limiter-Retry-After"
)
View Source
var (
	// RequestIDHeader represents the name of the header in which to store the request ID.
	RequestIDHeader = "X-Request-ID"
)

Functions

func IPFilter

func IPFilter(options IPFilterOptions) gin.HandlerFunc

IPFilter determines whether or not a client making a request to the server has been blacklisted and should be prevented from accessing the requested resource.

Because this middleware implements blacklisting, it's recommended that you include it as early as possible. However, be sure to include the Logger middleware before including this middleware if you wish to log messages using the current context's logger rather than the global logger.

Use the IPFilter... global variables to change the default headers used by this middleware.

If an error occurs, the IPFtilerErrorCodeHeader will be set and, if additional error details are available, the IPFilterErrorMessageHeader will contain the error message. The following error "codes" are used by this middleware for both the header and when calling the ErrorHandler, if one is supplied:

◽ Failure while retrieving the client's IP address: client-ip-lookup-failure
◽ Failure while retrieving the client IP's location information: ip-location-lookup-failure

If an ErrorHandler is not supplied, the request will be aborted with the following HTTP status codes:

◽ Failure while retrieving the client's IP address: 500
◽ Failure while retrieving the client IP's location information: 500

If an error handler is supplied, it is responsible for aborting the request or returning an appropriate response to the caller.

The IsBannedHandler supplied in the options is responsible for aborting the request or returning an appropriate response to the caller if the IP address is blacklisted.

func JWTAuth

func JWTAuth(options JWTAuthOptions) gin.HandlerFunc

JWTAuth is a middleware function for authenticating and authorizing a caller via a JWT.

Use the JWTAuth... global variables to change the default headers and/or token type used by this middleware.

If no authentication or authorization handler is specified, the caller is assumed to be authenticated or authorized, respectively, as long as the token is valid.

If an error occurs, the JWTAuthErrorCodeHeader will be set and, if additional error details are available, the JWTAuthErrorMessageHeader will contain the error message. The following error "codes" are used by this middleware for both the header and when calling the ErrorHandler, if one is supplied:

◽ Token is missing from the request: jwt-missing-auth-token
◽ Calling application failed to define a handler for creating the auth service: jwt-no-auth-service-defined
◽ Token verification fails: jwt-verify-token-failed
◽ Error returned by authentication handler: jwt-authentication-failed
◽ Caller is not authenticated: jwt-not-authenticated
◽ Error returned by authorization handler: jwt-authorization-failed
◽ Caller is not authorized: jwt-not-authorized

If an ErrorHandler is not supplied, the request will be aborted with the following HTTP status codes:

◽ Token is missing from the request: 401
◽ Calling application failed to define a handler for creating the auth service: 401
◽ Token verification fails: 401
◽ Error returned by authentication handler: 401
◽ Caller is not authenticated: 401
◽ Error returned by authorization handler: 403
◽ Caller is not authorized: 403

If an error handler is supplied, it is responsible for aborting the request or returning an appropriate response to the caller.

Be sure to include the Logger middleware before including this middleware if you wish to log messages using the current context's logger rather than the global logger.

func LoadIPLocationDB

func LoadIPLocationDB(ctx context.Context, path string) (*ip2location.DB, error)

LoadIPLocationDB loads the binary-formatted (BIN) IP location database file downloaded from https://lite.ip2location.com/database/ip-country.

func Localizer

func Localizer(options LocalizerOptions) gin.HandlerFunc

Localizer reads the "lang" query parameter and the Accept-Language header to determine which language translation engine will be stored in the context for later use in translating messages.

Your application must first create a new translator by calling the i18n.NewUniversalTranslator() function, loading any translations from files or defining them specifically through function calls and then calling the VerifyTranslations() function on the instance to ensure everything is working. Pass that translator object in the options.

Use the Localizer... global variables to change the default headers used by this middleware.

If an error occurs, the LocalizerErrorCodeHeader will be set and, if additional error details are available, the LocalizerErrorMessageHeader will contain the error message. The following error "codes" are used by this middleware for both the header and when calling the ErrorHandler, if one is supplied:

◽ Failure while retrieving parsing the Accept-Language header: parse-accept-language-failure

If an ErrorHandler is not supplied, the request will be aborted with the following HTTP status codes:

◽ Failure while retrieving parsing the Accept-Language header: 500

If an error handler is supplied, it is responsible for aborting the request or returning an appropriate response to the caller.

Be sure to include the Logger middleware before including this middleware if you wish to log messages using the current context's logger rather than the global logger.

func Logger

func Logger(excludeRequests ExcludeHTTPRequests, extraFields ...string) gin.HandlerFunc

Logger is a middleware function for logging requests to the server.

Be sure to include the RequestID middleware before including this middleware so that a unique request ID is written to log messages associated with the current gin context.

func Recover

func Recover(handler RecoveryHandler) gin.HandlerFunc

Recover is a middleware function for recovering from unexpected panics.

Be sure to include the Logger middleware before including this middleware if you wish to log messages using the current context's logger rather than the global logger.

func RedisRateLimiter

func RedisRateLimiter(options RedisRateLimiterOptions) gin.HandlerFunc

RedisRateLimiter uses a Redis backend to enforce request rate limits.

Use the RateLimit... and RedisRateLimit global variables to change the default headers used by this middleware.

If an error occurs, the RateLimitErrorCodeHeader will be set and, if additional error details are available, the RateLimitErrorMessageHeader will contain the error message. The following error "codes" are used by this middleware for both the header and when calling the ErrorHandler, if one is supplied:

◽ Failure while invoking rate limiter Allow function: rate-limiter-failure
◽ Rate limit reached: rate-limited

If an ErrorHandler is not supplied, the request will be aborted with the following HTTP status codes:

◽ Failure while invoking rate limiter Allow function: 500
◽ Rate limit reached: 429

If an error handler is supplied, it is responsible for aborting the request or returning an appropriate response to the caller.

Be sure to include the Logger middleware before including this middleware if you wish to log messages using the current context's logger rather than the global logger.

func RedisSession

func RedisSession(options RedisSessionOptions) gin.HandlerFunc

RedisSession uses a Redis backend to store session information.

Session data must always be serialized into a JSON string. Use the context.UnmarshalSessionData() and context.MarshalSessionData() to access and update session data in your application. If the data stored in the context is not a string, empty session data will be written back to Redis.

Use the Session... global variables to change the default headers used by this middleware.

If an error occurs, the SessionErrorCodeHeader will be set and, if additional error details are available, the SessionErrorMessageHeader will contain the error message. The following error "codes" are used by this middleware for both the header and when calling the ErrorHandler, if one is supplied:

◽ Failure while retrieving session ID: get-session-id-failure
◽ Failure while getting session data from Redis: get-session-data-failure
◽ Failure while storing session data in Redis: store-session-data-failure

If an ErrorHandler is not supplied, the request will be aborted with the following HTTP status codes:

◽ Failure while retrieving session ID: 500
◽ Failure while getting session data from Redis: 500
◽ Failure while storing session data in Redis: 500

If an error handler is supplied, it is responsible for aborting the request or returning an appropriate response to the caller.

Be sure to include the Logger middleware before including this middleware if you wish to log messages using the current context's logger rather than the global logger.

func RequestID

func RequestID() gin.HandlerFunc

RequestID is a middleware function for adding a unique request ID to every request.

Use the RequestIDHeader global variable to change the default header used to store the request ID for the client.

Types

type ErrLoadIPLocationDB

type ErrLoadIPLocationDB struct {
	Path string
	Err  error
}

ErrLoadIPLocationDB occurs when there is an error loading the IP location database.

func (*ErrLoadIPLocationDB) Code

func (e *ErrLoadIPLocationDB) Code() int

Code returns the corresponding error code.

func (*ErrLoadIPLocationDB) Error

func (e *ErrLoadIPLocationDB) Error() string

Error returns the string version of the error.

func (*ErrLoadIPLocationDB) InternalError

func (e *ErrLoadIPLocationDB) InternalError() error

InternalError returns the internal standard error object if there is one or nil if none is set.

type ErrorHandler

type ErrorHandler func(*gin.Context, string, error) bool

ErrorHandler is called when an error occurs within certain middlewares.

The current gin context is passed along with a custom error string "code" (as noted in the middleware's documentation) indicating the error that occurred along with any specific error information. If no additional error information is available, the caller should set the error parameter to nil. No handler function should assume the error is non-nil.

The handler should return true if the middleware should continue running or false if it should return immediately.

type ExcludeHTTPRequest

type ExcludeHTTPRequest struct {
	// HTTP method to ignore or "*" to ignore all methods.
	Method string

	// Path is a regular expression to use in order to match the request path.
	Path string
}

ExcludeHTTPRequest simply holds the method and path information for any type of HTTP request to exclude from logging.

func (*ExcludeHTTPRequest) Set

func (r *ExcludeHTTPRequest) Set(str string) error

Set parses the given string value into the object.

func (*ExcludeHTTPRequest) String

func (r *ExcludeHTTPRequest) String() string

String returns the string representation of the object.

func (*ExcludeHTTPRequest) Type

func (r *ExcludeHTTPRequest) Type() string

Type returns the type of the object.

type ExcludeHTTPRequests

type ExcludeHTTPRequests []ExcludeHTTPRequest

ExcludeHTTPRequests represents and array of ExcludeHTTPRequest objects.

func (*ExcludeHTTPRequests) Set

func (r *ExcludeHTTPRequests) Set(str string) error

Set parses the given string value into the object.

func (ExcludeHTTPRequests) String

func (r ExcludeHTTPRequests) String() string

String returns the string representation of the object.

func (ExcludeHTTPRequests) Type

func (r ExcludeHTTPRequests) Type() string

Type returns the type of the object.

type IPAddressRecord

type IPAddressRecord struct {
	// Address is the IP address.
	Address string

	// CountryCode is the two character country code based on ISO3166.
	CountryCode string

	// CountryName is the full country name based on ISO3166.
	CountryName string
}

IPAddressRecord holds detailed information about an IP address.

type IPFilterOptions

type IPFilterOptions struct {
	// ClientIPLookupHandler is an optional handler used to determine the actual client IP in the request.
	//
	// If this field is nil, the given context's ClientIP() function is used.
	ClientIPLookupHandler func(*gin.Context) (string, error)

	// EnableErrorCodeHeader indicates whether or not to set the custom X-*-Error-Code header if an error occurs.
	EnableErrorCodeHeader bool

	// EnableErrorMessageHeader indicates whether or not to set the custom X-*-Error-Message header if an error
	// occurs.
	EnableErrorMessageHeader bool

	// IPDBHandle is the handle to the IP location database used for lookups.
	//
	// You can use the LoadIPLocationDB() function to load the latest IP database file from
	// https://www.ip2location.com/.
	//
	// This field must NOT be nil.
	IPDBHandle *ip2location.DB

	// IsBannedHandler is called to determine if the request from the IP address, country or domain, respectively,
	// should be blocked. It should return true or false and any error that occurs while performing the check.
	//
	// A handler allows for the most flexible scenario in how to store and manage IP/country/domain blacklists
	// such as querying a DB for every request or providing some caching capabilities, etc.
	//
	// It is up to the handler to output any error messages or banned response to the writer and set the appropriate
	// HTTP response code. If the handler returns false, middleware will stop processing.
	//
	// This field must NOT be nil.
	IsBannedHandler func(*gin.Context, IPAddressRecord) bool

	// ErrorHandler is called if an error occurs while executing the middleware.
	ErrorHandler ErrorHandler
}

IPFilterOptions holds the options for configuring the IPFilter middleware.

func (IPFilterOptions) GetErrorCodeHeader

func (o IPFilterOptions) GetErrorCodeHeader() string

GetErrorCodeHeader returns the name of the X header to use for holding the middleware's error code.

func (IPFilterOptions) GetErrorMessageHeader

func (o IPFilterOptions) GetErrorMessageHeader() string

GetErrorMessageHeader returns the name of the X header to use for holding the middleware's error message.

func (IPFilterOptions) SetErrorCodeHeader

func (o IPFilterOptions) SetErrorCodeHeader() bool

SetErrorCodeHeader returns whether or not to set the error code header when an error occurs.

func (IPFilterOptions) SetErrorMessageHeader

func (o IPFilterOptions) SetErrorMessageHeader() bool

SetErrorMessageHeader returns whether or not to set the error code message when an error occurs.

type JWTAuthHandler

type JWTAuthHandler func(*gin.Context, *jwt.Token) (bool, error)

JWTAuthHandler is an app-specific function that is used to verify authentication or authorization.

type JWTAuthOptions

type JWTAuthOptions struct {
	// AuthnHandler is called to determine whether or not the user has successfully authenticated based on claims
	// in the token.
	AuthnHandler JWTAuthHandler

	// AuthznHandler is called to determine whether or not the user is authorized for the request based on
	// claims in the token.
	AuthzHandler JWTAuthHandler

	// AuthService is the JWT authentication service to use for verifying the token.
	AuthService crypto.JWTAuthService

	// Cookie defines the cookie in which to store the JWT token.
	Cookie struct {
		// Name of the cookie.
		Name string

		// MaxAge stores how long until the cookie expires.
		MaxAge time.Duration

		// Path restricts the cookie to a specific URI.
		Path string

		// Domain restricts the cookie to a specific domain.
		Domain string

		// Secure only allows the cookie to be transmitted over HTTPS connections.
		Secure bool

		// HttpOnly restricts the cookie from being accessed by anything such as JavaScript.
		HTTPOnly bool
	}

	// EnableErrorCodeHeader indicates whether or not to set the custom X-*-Error-Code header if an error occurs.
	EnableErrorCodeHeader bool

	// EnableErrorMessageHeader indicates whether or not to set the custom X-*-Error-Message header if an error
	// occurs.
	EnableErrorMessageHeader bool

	// ErrorHandler is called if an error occurs while executing the middleware.
	ErrorHandler ErrorHandler

	// SaveToCookie indicates whether or not to save the JWT token to a cookie.
	SaveToCookie bool
}

JWTAuthOptions holds the options for configuring the JWTAuth middleware.

func (JWTAuthOptions) GetErrorCodeHeader

func (o JWTAuthOptions) GetErrorCodeHeader() string

GetErrorCodeHeader returns the name of the X header to use for holding the middleware's error code.

func (JWTAuthOptions) GetErrorMessageHeader

func (o JWTAuthOptions) GetErrorMessageHeader() string

GetErrorMessageHeader returns the name of the X header to use for holding the middleware's error message.

func (JWTAuthOptions) SetErrorCodeHeader

func (o JWTAuthOptions) SetErrorCodeHeader() bool

SetErrorCodeHeader returns whether or not to set the error code header when an error occurs.

func (JWTAuthOptions) SetErrorMessageHeader

func (o JWTAuthOptions) SetErrorMessageHeader() bool

SetErrorMessageHeader returns whether or not to set the error code message when an error occurs.

type LocalizerOptions

type LocalizerOptions struct {
	// Translator is the main translation object which stores the list of supported languages.
	//
	// This field must NOT be nil.
	Translator *i18n.UniversalTranslator

	// EnableErrorCodeHeader indicates whether or not to set the custom X-*-Error-Code header if an error occurs.
	EnableErrorCodeHeader bool

	// EnableErrorMessageHeader indicates whether or not to set the custom X-*-Error-Message header if an error
	// occurs.
	EnableErrorMessageHeader bool

	// ErrorHandler is called if an error occurs while executing the middleware.
	ErrorHandler ErrorHandler
}

LocalizerOptions holds the options for configuring the Localizer middleware.

func (LocalizerOptions) GetErrorCodeHeader

func (o LocalizerOptions) GetErrorCodeHeader() string

GetErrorCodeHeader returns the name of the X header to use for holding the middleware's error code.

func (LocalizerOptions) GetErrorMessageHeader

func (o LocalizerOptions) GetErrorMessageHeader() string

GetErrorMessageHeader returns the name of the X header to use for holding the middleware's error message.

func (LocalizerOptions) SetErrorCodeHeader

func (o LocalizerOptions) SetErrorCodeHeader() bool

SetErrorCodeHeader returns whether or not to set the error code header when an error occurs.

func (LocalizerOptions) SetErrorMessageHeader

func (o LocalizerOptions) SetErrorMessageHeader() bool

SetErrorMessageHeader returns whether or not to set the error code message when an error occurs.

type RecoveryHandler

type RecoveryHandler func(*gin.Context, error, string)

RecoveryHandler is used for recovering from a panic.

This function should output content to the HTTP writer in order to send a response to the caller when a panic is encountered.

The handler will receive the current gin context, the error information and the stack when the error occurred.

type RedisRateLimiterOptions

type RedisRateLimiterOptions struct {
	// Client points to the Redis client object.
	//
	// This field must NOT be nil.
	Client *redis.Client

	// EnableErrorCodeHeader indicates whether or not to set the custom X-*-Error-Code header if an error occurs.
	EnableErrorCodeHeader bool

	// EnableErrorMessageHeader indicates whether or not to set the custom X-*-Error-Message header if an error
	// occurs.
	EnableErrorMessageHeader bool

	// ErrorHandler is called if an error occurs while executing the middleware.
	ErrorHandler ErrorHandler

	// KeyLookupHandler is called to determine the name of the key in which to store client request rate information.
	// This would typically be an API key or a client IP address or some combination thereof.
	//
	// This field must NOT be nil.
	KeyLookupHandler func(*gin.Context) string

	// Rate indicates the rate limit settings.
	//
	// This field must NOT be nil.
	Rate redisrate.Limit
}

RedisRateLimiterOptions holds the options for configuring the RedisRateLimiter middleware.

func (RedisRateLimiterOptions) GetErrorCodeHeader

func (o RedisRateLimiterOptions) GetErrorCodeHeader() string

GetErrorCodeHeader returns the name of the X header to use for holding the middleware's error code.

func (RedisRateLimiterOptions) GetErrorMessageHeader

func (o RedisRateLimiterOptions) GetErrorMessageHeader() string

GetErrorMessageHeader returns the name of the X header to use for holding the middleware's error message.

func (RedisRateLimiterOptions) SetErrorCodeHeader

func (o RedisRateLimiterOptions) SetErrorCodeHeader() bool

SetErrorCodeHeader returns whether or not to set the error code header when an error occurs.

func (RedisRateLimiterOptions) SetErrorMessageHeader

func (o RedisRateLimiterOptions) SetErrorMessageHeader() bool

SetErrorMessageHeader returns whether or not to set the error code message when an error occurs.

type RedisSessionOptions

type RedisSessionOptions struct {
	// Client points to the Redis client object.
	//
	// This field must NOT be nil.
	Client *redis.Client

	// EnableErrorCodeHeader indicates whether or not to set the custom X-*-Error-Code header if an error occurs.
	EnableErrorCodeHeader bool

	// EnableErrorMessageHeader indicates whether or not to set the custom X-*-Error-Message header if an error
	// occurs.
	EnableErrorMessageHeader bool

	// ErrorHandler is called if an error occurs while executing the middleware.
	ErrorHandler ErrorHandler

	// SessionIDLookupHandler is called to retrieve the ID for the session.
	//
	// This function should return the session ID with a nil error on success or an empty string with an error on
	// failure.
	//
	// By using a handler function, the application can obtain the session ID in any number of ways such as by
	// inspecting a JWT claim or simply using a cookie.
	//
	// This field must NOT be nil.
	SessionIDLookupHandler func(*gin.Context) (string, error)

	// TTL indicates the length session data will be stored before it expires.
	TTL time.Duration
}

RedisSessionOptions holds the options for configuring the RedisSession middleware.

func (RedisSessionOptions) GetErrorCodeHeader

func (o RedisSessionOptions) GetErrorCodeHeader() string

GetErrorCodeHeader returns the name of the X header to use for holding the middleware's error code.

func (RedisSessionOptions) GetErrorMessageHeader

func (o RedisSessionOptions) GetErrorMessageHeader() string

GetErrorMessageHeader returns the name of the X header to use for holding the middleware's error message.

func (RedisSessionOptions) SetErrorCodeHeader

func (o RedisSessionOptions) SetErrorCodeHeader() bool

SetErrorCodeHeader returns whether or not to set the error code header when an error occurs.

func (RedisSessionOptions) SetErrorMessageHeader

func (o RedisSessionOptions) SetErrorMessageHeader() bool

SetErrorMessageHeader returns whether or not to set the error code message when an error occurs.

Jump to

Keyboard shortcuts

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