Documentation
¶
Overview ¶
Package middleware provides HTTP middleware for authentication and authorization.
Package middleware provides HTTP middleware for GoatFlow.
Package middleware provides HTTP middleware for authentication and authorization.
Index ¶
- Constants
- func APITokenAuthMiddleware() gin.HandlerFunc
- func ClearLanguageCookie(c *gin.Context)
- func CustomerPortalGate(jwtManager *auth.JWTManager) gin.HandlerFunc
- func DatabaseHealthCheck() gin.HandlerFunc
- func DemoGuard() gin.HandlerFunc
- func DemoMode() gin.HandlerFunc
- func ExtractToken(c *gin.Context) string
- func GetCurrentUser(c *gin.Context) (uint, string, string, bool)
- func GetLanguage(c *gin.Context) string
- func IsAPIToken(token string) bool
- func LoadOpenAPIMiddleware() gin.HandlerFunc
- func MaintenanceNotification(db *sql.DB) gin.HandlerFunc
- func OptionalAuth(jwtManager *auth.JWTManager) gin.HandlerFunc
- func RateLimitByIP(requestsPerHour int) gin.HandlerFunc
- func RateLimitMiddleware() gin.HandlerFunc
- func RequestID() gin.HandlerFunc
- func RequireAdminAccess(rbac *auth.RBAC) gin.HandlerFunc
- func RequireAdminGroup() gin.HandlerFunc
- func RequireAgentAccess(rbac *auth.RBAC) gin.HandlerFunc
- func RequireAnyPermission(rbac *auth.RBAC, permissions ...auth.Permission) gin.HandlerFunc
- func RequireAnyQueueAccess(permType string) gin.HandlerFunc
- func RequirePermission(rbac *auth.RBAC, permission auth.Permission) gin.HandlerFunc
- func RequireQueueAccess(permType string) gin.HandlerFunc
- func RequireQueueAccessFromTicket(permType string) gin.HandlerFunc
- func RequireRole(roles ...string) gin.HandlerFunc
- func RequireScope(scope string) gin.HandlerFunc
- func RequireTicketAccess(rbac *auth.RBAC) gin.HandlerFunc
- func ResolveTenantFromHost(host string) uint
- func SecurityHeaders() gin.HandlerFunc
- func SessionMiddleware(jwtManager *auth.JWTManager) gin.HandlerFunc
- func SetAPITokenVerifier(v APITokenVerifier)
- func SetLanguageCookie(c *gin.Context, lang string)
- func T(c *gin.Context, key string, args ...interface{}) string
- func TranslateError(c *gin.Context, key string, args ...interface{}) string
- func TranslateSuccess(c *gin.Context, key string, args ...interface{}) string
- func TranslateValidation(c *gin.Context, key string, args ...interface{}) string
- func UnifiedAuthMiddleware(jwtManager interface{ ... }) gin.HandlerFunc
- type APITokenVerifier
- type AuthMiddleware
- func (m *AuthMiddleware) CanAccessTicket(c *gin.Context, ticketOwnerID uint) bool
- func (m *AuthMiddleware) GetUserID(c *gin.Context) (uint, bool)
- func (m *AuthMiddleware) GetUserRole(c *gin.Context) (string, bool)
- func (m *AuthMiddleware) IsAuthenticated(c *gin.Context) bool
- func (m *AuthMiddleware) OptionalAuth() gin.HandlerFunc
- func (m *AuthMiddleware) RequireAuth() gin.HandlerFunc
- func (m *AuthMiddleware) RequirePermission(permission auth.Permission) gin.HandlerFunc
- func (m *AuthMiddleware) RequireRole(roles ...string) gin.HandlerFunc
- type I18nMiddleware
- type MediaType
- type OpenAPISpec
- type OpenAPIValidator
- type Operation
- type PathItem
- type RateLimiter
- type RequestBody
- type Response
- type Schema
Constants ¶
const ( // LanguageContextKey is the key for storing language in context. LanguageContextKey = "language" // DefaultLanguage is the default language. DefaultLanguage = "en" )
Variables ¶
This section is empty.
Functions ¶
func APITokenAuthMiddleware ¶
func APITokenAuthMiddleware() gin.HandlerFunc
APITokenAuthMiddleware authenticates requests using GoatKit API tokens (gf_*). Sets user context similar to JWT auth for compatibility with existing handlers.
func ClearLanguageCookie ¶
ClearLanguageCookie clears the language preference cookie.
func CustomerPortalGate ¶
func CustomerPortalGate(jwtManager *auth.JWTManager) gin.HandlerFunc
CustomerPortalGate loads portal config, enforces enable/disable, and applies optional login rules.
func DatabaseHealthCheck ¶
func DatabaseHealthCheck() gin.HandlerFunc
and returns a friendly error page if the database is down.
func DemoGuard ¶
func DemoGuard() gin.HandlerFunc
DemoGuard blocks non-admin users from modifying account security settings (password, MFA) when demo mode is active. Returns 403 with a friendly message.
func DemoMode ¶
func DemoMode() gin.HandlerFunc
DemoMode sets is_demo=true on every request when app.demo_mode is enabled. This allows templates and handlers to check for demo mode globally.
func ExtractToken ¶ added in v0.7.0
extractToken extracts token from Authorization header or cookies ExtractToken extracts an auth token from the request. It checks the Authorization header first (Bearer JWT or raw API token), then falls back to cookies. On /customer paths customer-specific cookies are checked before agent cookies to avoid session conflicts in the same browser. The query parameter "token" is also accepted for WebSocket connections.
func GetCurrentUser ¶
GetCurrentUser retrieves the current user from context.
func GetLanguage ¶
GetLanguage gets the current language from context. Falls back to cookie detection if not set in context.
func IsAPIToken ¶
IsAPIToken checks if a token string is a GoatKit API token (gf_ prefix)
func LoadOpenAPIMiddleware ¶
func LoadOpenAPIMiddleware() gin.HandlerFunc
LoadOpenAPIMiddleware creates the OpenAPI validation middleware.
func MaintenanceNotification ¶
func MaintenanceNotification(db *sql.DB) gin.HandlerFunc
MaintenanceNotification middleware checks for active/upcoming maintenance and adds notification data to the context for templates.
func OptionalAuth ¶
func OptionalAuth(jwtManager *auth.JWTManager) gin.HandlerFunc
OptionalAuth is middleware that validates tokens if present but doesn't require them.
func RateLimitByIP ¶
func RateLimitByIP(requestsPerHour int) gin.HandlerFunc
RateLimitByIP applies IP-based rate limiting with a custom limit
func RateLimitMiddleware ¶
func RateLimitMiddleware() gin.HandlerFunc
RateLimitMiddleware applies rate limiting based on API token or IP
func RequestID ¶
func RequestID() gin.HandlerFunc
RequestID adds a unique request ID to each request.
func RequireAdminAccess ¶
func RequireAdminAccess(rbac *auth.RBAC) gin.HandlerFunc
RequireAdminAccess is a convenience function for admin-only routes.
func RequireAdminGroup ¶
func RequireAdminGroup() gin.HandlerFunc
RequireAdminGroup checks if the user is in the admin group.
func RequireAgentAccess ¶
func RequireAgentAccess(rbac *auth.RBAC) gin.HandlerFunc
RequireAgentAccess allows both admins and agents.
func RequireAnyPermission ¶
func RequireAnyPermission(rbac *auth.RBAC, permissions ...auth.Permission) gin.HandlerFunc
RequireAnyPermission checks if the user has any of the required permissions.
func RequireAnyQueueAccess ¶
func RequireAnyQueueAccess(permType string) gin.HandlerFunc
RequireAnyQueueAccess checks if the user has the specified permission for at least one queue. This is useful for routes where access to any queue is sufficient (like ticket list pages).
func RequirePermission ¶
func RequirePermission(rbac *auth.RBAC, permission auth.Permission) gin.HandlerFunc
RequirePermission checks if the user has the required permission.
func RequireQueueAccess ¶
func RequireQueueAccess(permType string) gin.HandlerFunc
RequireQueueAccess checks if the user has the specified permission for the queue. The queue ID is extracted from the URL parameter "queue_id" or query parameter "queue_id". Permission types: ro, rw, create, move_into, note, owner, priority
func RequireQueueAccessFromTicket ¶
func RequireQueueAccessFromTicket(permType string) gin.HandlerFunc
RequireQueueAccessFromTicket checks if the user has the specified permission for the queue that the ticket belongs to. The ticket ID is extracted from the URL parameter "ticket_id" or "id".
func RequireRole ¶
func RequireRole(roles ...string) gin.HandlerFunc
RequireRole checks if the user has the required role.
func RequireScope ¶
func RequireScope(scope string) gin.HandlerFunc
RequireScope middleware checks that the API token has the required scope. It also enforces AgentOnly and RequireRole restrictions from the scope definition.
func RequireTicketAccess ¶
func RequireTicketAccess(rbac *auth.RBAC) gin.HandlerFunc
RequireTicketAccess checks if the user can access a specific ticket.
func ResolveTenantFromHost ¶
ResolveTenantFromHost maps the request host to a tenant ID using GOATFLOW_CUSTOMER_HOSTMAP. Format: "host1=1,host2=2". Unknown hosts return 0.
func SecurityHeaders ¶ added in v0.8.0
func SecurityHeaders() gin.HandlerFunc
SecurityHeaders adds HTTP security headers to all responses.
CSP Note: GoatFlow uses Alpine.js (requires unsafe-eval for x-data/x-bind expression evaluation) and HTMX (injects inline scripts from AJAX responses). These frameworks are fundamentally incompatible with strict script-src CSP. XSS protection is provided by server-side HTML sanitisation (bluemonday), not by CSP script restrictions. CSP still protects against clickjacking, content sniffing, form hijacking, and framing attacks.
func SessionMiddleware ¶
func SessionMiddleware(jwtManager *auth.JWTManager) gin.HandlerFunc
SessionMiddleware validates JWT tokens from cookies or Authorization header.
func SetAPITokenVerifier ¶
func SetAPITokenVerifier(v APITokenVerifier)
SetAPITokenVerifier sets the global token verifier
func SetLanguageCookie ¶
SetLanguageCookie sets the language preference cookie.
func TranslateError ¶
TranslateError translates an error message.
func TranslateSuccess ¶
TranslateSuccess translates a success message.
func TranslateValidation ¶
TranslateValidation translates a validation message.
func UnifiedAuthMiddleware ¶
func UnifiedAuthMiddleware(jwtManager interface {
ValidateToken(string) (*auth.Claims, error)
}) gin.HandlerFunc
UnifiedAuthMiddleware handles both JWT tokens and API tokens (gf_*).
Types ¶
type APITokenVerifier ¶
type APITokenVerifier interface {
VerifyToken(ctx context.Context, rawToken string) (*models.APIToken, error)
UpdateLastUsed(ctx context.Context, tokenID int64, ip string) error
}
APITokenVerifier is the interface for verifying API tokens. This breaks the import cycle between api and middleware packages.
type AuthMiddleware ¶
type AuthMiddleware struct {
// contains filtered or unexported fields
}
func NewAuthMiddleware ¶
func NewAuthMiddleware(jwtManager *auth.JWTManager) *AuthMiddleware
func (*AuthMiddleware) CanAccessTicket ¶
func (m *AuthMiddleware) CanAccessTicket(c *gin.Context, ticketOwnerID uint) bool
func (*AuthMiddleware) GetUserRole ¶
func (m *AuthMiddleware) GetUserRole(c *gin.Context) (string, bool)
func (*AuthMiddleware) IsAuthenticated ¶
func (m *AuthMiddleware) IsAuthenticated(c *gin.Context) bool
func (*AuthMiddleware) OptionalAuth ¶
func (m *AuthMiddleware) OptionalAuth() gin.HandlerFunc
func (*AuthMiddleware) RequireAuth ¶
func (m *AuthMiddleware) RequireAuth() gin.HandlerFunc
func (*AuthMiddleware) RequirePermission ¶
func (m *AuthMiddleware) RequirePermission(permission auth.Permission) gin.HandlerFunc
func (*AuthMiddleware) RequireRole ¶
func (m *AuthMiddleware) RequireRole(roles ...string) gin.HandlerFunc
type I18nMiddleware ¶
type I18nMiddleware struct {
// contains filtered or unexported fields
}
I18nMiddleware handles language detection and sets it in context.
func NewI18nMiddleware ¶
func NewI18nMiddleware() *I18nMiddleware
NewI18nMiddleware creates a new i18n middleware.
func (*I18nMiddleware) Handle ¶
func (m *I18nMiddleware) Handle() gin.HandlerFunc
Handle returns the middleware handler function.
type MediaType ¶
type MediaType struct {
Schema Schema `yaml:"schema"`
}
MediaType represents an OpenAPI media type.
type OpenAPISpec ¶
type OpenAPISpec struct {
OpenAPI string `yaml:"openapi"`
Info map[string]interface{} `yaml:"info"`
Paths map[string]PathItem `yaml:"paths"`
}
OpenAPISpec represents a simplified OpenAPI specification.
type OpenAPIValidator ¶
type OpenAPIValidator struct {
// contains filtered or unexported fields
}
OpenAPIValidator provides OpenAPI contract validation.
func NewOpenAPIValidator ¶
func NewOpenAPIValidator(specPath string) (*OpenAPIValidator, error)
NewOpenAPIValidator creates a new OpenAPI validator from the spec file.
func (*OpenAPIValidator) ValidateResponse ¶
func (v *OpenAPIValidator) ValidateResponse() gin.HandlerFunc
ValidateResponse validates that a response matches the OpenAPI spec.
type Operation ¶
type Operation struct {
OperationID string `yaml:"operationId"`
Responses map[string]Response `yaml:"responses"`
RequestBody *RequestBody `yaml:"requestBody,omitempty"`
}
Operation represents an OpenAPI operation.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a token bucket rate limiter
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(key string, limit int) bool
Allow checks if a request is allowed and consumes a token
func (*RateLimiter) Remaining ¶
func (rl *RateLimiter) Remaining(key string) int
Remaining returns remaining tokens for a key
type RequestBody ¶
type RequestBody struct {
Required bool `yaml:"required"`
Content map[string]MediaType `yaml:"content"`
}
RequestBody represents an OpenAPI request body.