middleware

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

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

View Source
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

func ClearLanguageCookie(c *gin.Context)

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

func ExtractToken(c *gin.Context) string

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

func GetCurrentUser(c *gin.Context) (uint, string, string, bool)

GetCurrentUser retrieves the current user from context.

func GetLanguage

func GetLanguage(c *gin.Context) string

GetLanguage gets the current language from context. Falls back to cookie detection if not set in context.

func IsAPIToken

func IsAPIToken(token string) bool

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

func ResolveTenantFromHost(host string) uint

ResolveTenantFromHost maps the request host to a tenant ID using GOATFLOW_CUSTOMER_HOSTMAP. Format: "host1=1,host2=2". Unknown hosts return 0.

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

func SetLanguageCookie(c *gin.Context, lang string)

SetLanguageCookie sets the language preference cookie.

func T

func T(c *gin.Context, key string, args ...interface{}) string

T translates a key in the current language.

func TranslateError

func TranslateError(c *gin.Context, key string, args ...interface{}) string

TranslateError translates an error message.

func TranslateSuccess

func TranslateSuccess(c *gin.Context, key string, args ...interface{}) string

TranslateSuccess translates a success message.

func TranslateValidation

func TranslateValidation(c *gin.Context, key string, args ...interface{}) string

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) GetUserID

func (m *AuthMiddleware) GetUserID(c *gin.Context) (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 PathItem

type PathItem map[string]Operation

PathItem represents an OpenAPI path item.

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter implements a token bucket rate limiter

func NewRateLimiter

func NewRateLimiter() *RateLimiter

NewRateLimiter creates a new 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.

type Response

type Response struct {
	Description string               `yaml:"description"`
	Content     map[string]MediaType `yaml:"content,omitempty"`
}

Response represents an OpenAPI response.

type Schema

type Schema struct {
	Type       string            `yaml:"type"`
	Properties map[string]Schema `yaml:"properties,omitempty"`
	Required   []string          `yaml:"required,omitempty"`
	Items      *Schema           `yaml:"items,omitempty"`
	Ref        string            `yaml:"$ref,omitempty"`
}

Schema represents a simplified OpenAPI schema.

Jump to

Keyboard shortcuts

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