middleware

package
v0.29.0 Latest Latest
Warning

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

Go to latest
Published: May 5, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SessionUserID       = "user_id"
	SessionUsername     = "username"
	SessionLastActivity = "last_activity"
	SessionFingerprint  = "session_fingerprint"
	SessionRememberMe   = "remember_me"
)
View Source
const ContextKeyClientIP = "client_ip"

ContextKeyClientIP is the gin context key for the client IP address.

Variables

This section is empty.

Functions

func ApplyRememberMe added in v0.29.0

func ApplyRememberMe(session sessions.Session, maxAge int, isProduction bool)

ApplyRememberMe marks the session as a "remember me" session and extends the cookie lifetime to maxAge. Downstream middleware reads SessionRememberMe to keep the cookie alive (sliding expiration) and to bypass idle timeout.

func CORSMiddleware added in v0.20.0

func CORSMiddleware(cfg *config.Config) gin.HandlerFunc

CORSMiddleware returns a CORS middleware configured from application settings. It allows cross-origin requests from the configured origins to API endpoints.

func CSRFMiddleware

func CSRFMiddleware() gin.HandlerFunc

CSRFMiddleware provides CSRF protection for state-changing operations

func GenerateFingerprint added in v0.19.0

func GenerateFingerprint(ip, userAgent string, includeIP bool) string

GenerateFingerprint creates a SHA256 hash from IP (optional) and User-Agent.

func GetCSRFToken

func GetCSRFToken(c *gin.Context) string

GetCSRFToken retrieves the CSRF token from the context

func MetricsAuthMiddleware

func MetricsAuthMiddleware(token string) gin.HandlerFunc

MetricsAuthMiddleware creates a middleware that protects metrics endpoint with Bearer token

func NewRateLimiter

func NewRateLimiter(config RateLimitConfig) (gin.HandlerFunc, error)

NewRateLimiter creates a new rate limiter with configurable store backend

func OptionalAuth added in v0.16.0

func OptionalAuth(userService *services.UserService) gin.HandlerFunc

OptionalAuth loads the user from session if logged in, but does not redirect if not. Use for public pages that show richer UI when authenticated.

func RequestContextMiddleware added in v0.25.0

func RequestContextMiddleware() gin.HandlerFunc

RequestContextMiddleware extracts client IP and HTTP request metadata (User-Agent, path, method) and stores them in the request context for downstream services (e.g. audit logging).

func RequireAdmin

func RequireAdmin() gin.HandlerFunc

RequireAdmin is a middleware that requires the user to have admin role. This middleware should be used after RequireAuth, which already fetches and caches the user in the gin context via loadUserFromSession.

func RequireAuth

func RequireAuth(userService *services.UserService) gin.HandlerFunc

RequireAuth is a middleware that requires the user to be logged in

func SecurityHeaders added in v0.20.0

func SecurityHeaders(useHSTS bool) gin.HandlerFunc

SecurityHeaders returns a middleware that sets HTTP security headers to protect against common web vulnerabilities. HSTS is only applied when useHSTS is true (i.e. when BaseURL uses https://), so local HTTP development is unaffected.

func SessionFingerprintMiddleware

func SessionFingerprintMiddleware(enabled, includeIP bool) gin.HandlerFunc

SessionFingerprintMiddleware validates session fingerprint to prevent session hijacking Checks User-Agent (and optionally IP) against stored fingerprint

func SessionIdleTimeout

func SessionIdleTimeout(idleTimeoutSeconds int) gin.HandlerFunc

SessionIdleTimeout checks if the session has been idle for too long and clears it if necessary. Set idleTimeoutSeconds to 0 to disable.

func SessionOptions added in v0.22.0

func SessionOptions(maxAge int, isProduction bool) sessions.Options

SessionOptions builds a sessions.Options with the project's standard cookie settings (Path "/", HttpOnly, SameSite Lax, Secure based on production flag).

func SessionRememberMeMiddleware added in v0.22.0

func SessionRememberMeMiddleware(rememberMeMaxAge int, isProduction bool) gin.HandlerFunc

SessionRememberMeMiddleware overrides cookie MaxAge for "remember me" sessions. Must run after sessions.Sessions() and before SessionIdleTimeout.

Types

type RateLimitConfig

type RateLimitConfig struct {
	// Rate limit settings
	RequestsPerMinute int           // Number of requests allowed per minute
	CleanupInterval   time.Duration // How often to cleanup (only for memory store)

	// Store settings
	StoreType RateLimitStoreType // "memory" or "redis"

	// Redis settings (only used when StoreType = "redis")
	// Must be provided when StoreType is "redis" (initialized in main.go)
	RedisClient *redis.Client // Required for Redis store: shared go-redis client

	// Audit settings
	AuditService core.AuditLogger // Required: audit service for logging rate limit events
}

RateLimitConfig holds the configuration for rate limiting with store support

type RateLimitStoreType

type RateLimitStoreType string

RateLimitStoreType defines the type of rate limit store

const (
	// RateLimitStoreMemory uses in-memory storage (single instance only)
	RateLimitStoreMemory RateLimitStoreType = "memory"
	// RateLimitStoreRedis uses Redis storage (distributed, multi-pod support)
	RateLimitStoreRedis RateLimitStoreType = "redis"
)

Jump to

Keyboard shortcuts

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