middleware

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package middleware provides HTTP middleware for authentication and authorization.

Package middleware provides HTTP middleware for CoreForge session management.

Index

Constants

View Source
const (
	// ContextKeyAPIKey is the context key for the validated API key.
	ContextKeyAPIKey contextKey = "api_key"

	// ContextKeyPrincipal is the context key for the authenticated principal.
	ContextKeyPrincipal contextKey = "principal"
)

Variables

This section is empty.

Functions

func APIKeyMiddleware

func APIKeyMiddleware(config APIKeyMiddlewareConfig) func(http.Handler) http.Handler

APIKeyMiddleware creates middleware that validates API keys.

func ChiAuth

func ChiAuth(jwtService *jwt.Service) func(http.Handler) http.Handler

ChiAuth returns a Chi-compatible middleware that validates JWT tokens. This is an alias for HTTPAuth since Chi uses the standard http.Handler interface.

Usage with Chi:

r := chi.NewRouter()
r.Use(middleware.ChiAuth(jwtService))
r.Get("/api/protected", protectedHandler)

func ChiAuthOptional

func ChiAuthOptional(jwtService *jwt.Service) func(http.Handler) http.Handler

ChiAuthOptional returns a Chi-compatible middleware that validates JWT tokens if present. This is an alias for HTTPAuthOptional since Chi uses the standard http.Handler interface.

Usage with Chi:

r := chi.NewRouter()
r.Use(middleware.ChiAuthOptional(jwtService))
r.Get("/api/public", publicHandler)

func ChiRequireAnyPermission

func ChiRequireAnyPermission(permissions ...string) func(http.Handler) http.Handler

ChiRequireAnyPermission returns a Chi-compatible middleware that requires any of the specified permissions.

func ChiRequireAnyRole

func ChiRequireAnyRole(roles ...string) func(http.Handler) http.Handler

ChiRequireAnyRole returns a Chi-compatible middleware that requires any of the specified roles.

func ChiRequireOrganization

func ChiRequireOrganization() func(http.Handler) http.Handler

ChiRequireOrganization returns a Chi-compatible middleware that requires organization context.

func ChiRequirePermission

func ChiRequirePermission(permission string) func(http.Handler) http.Handler

ChiRequirePermission returns a Chi-compatible middleware that requires a specific permission.

func ChiRequirePlatformAdmin

func ChiRequirePlatformAdmin() func(http.Handler) http.Handler

ChiRequirePlatformAdmin returns a Chi-compatible middleware that requires platform admin status.

func ChiRequireRole

func ChiRequireRole(role string) func(http.Handler) http.Handler

ChiRequireRole returns a Chi-compatible middleware that requires a specific role.

Usage with Chi:

r.Group(func(r chi.Router) {
    r.Use(middleware.ChiAuth(jwtService))
    r.Use(middleware.ChiRequireRole("admin"))
    r.Get("/api/admin", adminHandler)
})

func ClaimsFromContext

func ClaimsFromContext(ctx context.Context) *jwt.Claims

ClaimsFromContext extracts JWT claims from the context. Returns nil if no claims are present.

func ContextWithClaims

func ContextWithClaims(ctx context.Context, claims *jwt.Claims) context.Context

ContextWithClaims returns a new context with the JWT claims attached.

func GetAPIKey

func GetAPIKey(ctx context.Context) *apikey.APIKey

GetAPIKey retrieves the validated API key from the request context.

func HTTPAuth

func HTTPAuth(jwtService *jwt.Service) func(http.Handler) http.Handler

HTTPAuth returns a standard http.Handler middleware that validates JWT tokens. It extracts the token from the Authorization header (Bearer scheme) and attaches the claims to the request context.

func HTTPAuthOptional

func HTTPAuthOptional(jwtService *jwt.Service) func(http.Handler) http.Handler

HTTPAuthOptional returns middleware that validates JWT tokens if present, but allows requests without tokens to proceed.

func HasAllPermissions

func HasAllPermissions(ctx context.Context, permissions ...string) bool

HasAllPermissions checks if the user has all of the specified permissions.

func HasAnyPermission

func HasAnyPermission(ctx context.Context, permissions ...string) bool

HasAnyPermission checks if the user has any of the specified permissions.

func HasAnyRole

func HasAnyRole(ctx context.Context, roles ...string) bool

HasAnyRole checks if the user has any of the specified roles.

func HasPermission

func HasPermission(ctx context.Context, permission string) bool

HasPermission checks if the user has a specific permission.

func HasRole

func HasRole(ctx context.Context, role string) bool

HasRole checks if the user has a specific role.

func IsPlatformAdminFromContext

func IsPlatformAdminFromContext(ctx context.Context) bool

IsPlatformAdminFromContext checks if the user is a platform admin. Returns false if no claims are present.

func OptionalAPIKey

func OptionalAPIKey(service *apikey.Service) func(http.Handler) http.Handler

OptionalAPIKey creates middleware that validates API keys if present but doesn't require them.

func OrganizationIDFromContext

func OrganizationIDFromContext(ctx context.Context) *uuid.UUID

OrganizationIDFromContext extracts the organization ID from the context. Returns nil if no organization context is present.

func PermissionsFromContext

func PermissionsFromContext(ctx context.Context) []string

PermissionsFromContext extracts the user's permissions from the context. Returns nil if no permissions are present.

func RequireAPIKey

func RequireAPIKey(service *apikey.Service) func(http.Handler) http.Handler

RequireAPIKey creates middleware that requires a valid API key. This is a convenience function with default configuration.

func RequireAPIKeyWithScopes

func RequireAPIKeyWithScopes(service *apikey.Service, scopes ...string) func(http.Handler) http.Handler

RequireAPIKeyWithScopes creates middleware that requires specific scopes.

func RequireAnyPermission

func RequireAnyPermission(permissions ...string) func(http.Handler) http.Handler

RequireAnyPermission returns middleware that requires any of the specified permissions. Must be used after HTTPAuth middleware.

func RequireAnyRole

func RequireAnyRole(roles ...string) func(http.Handler) http.Handler

RequireAnyRole returns middleware that requires the user to have any of the specified roles. Must be used after HTTPAuth middleware.

func RequireAnyScope

func RequireAnyScope(scopes ...string) func(http.Handler) http.Handler

RequireAnyScope creates middleware that checks for any of the given scopes.

func RequireOrganization

func RequireOrganization() func(http.Handler) http.Handler

RequireOrganization returns middleware that requires an organization context. Must be used after HTTPAuth middleware.

func RequirePermission

func RequirePermission(permission string) func(http.Handler) http.Handler

RequirePermission returns middleware that requires a specific permission. Must be used after HTTPAuth middleware.

func RequirePlatformAdmin

func RequirePlatformAdmin() func(http.Handler) http.Handler

RequirePlatformAdmin returns middleware that requires platform admin status. Must be used after HTTPAuth middleware.

func RequireRole

func RequireRole(role string) func(http.Handler) http.Handler

RequireRole returns middleware that requires the user to have a specific role. Must be used after HTTPAuth middleware.

func RequireScope

func RequireScope(scope string) func(http.Handler) http.Handler

RequireScope creates middleware that checks for a specific scope. This should be used after APIKeyMiddleware.

func RoleFromContext

func RoleFromContext(ctx context.Context) string

RoleFromContext extracts the user's role from the context. Returns empty string if no role is present.

func UserIDFromContext

func UserIDFromContext(ctx context.Context) uuid.UUID

UserIDFromContext extracts the user ID from the context. Returns uuid.Nil if no claims or user ID is present.

Types

type APIKeyMiddlewareConfig

type APIKeyMiddlewareConfig struct {
	// Service is the API key service.
	Service *apikey.Service

	// RequiredScopes are scopes that must be present (all required).
	RequiredScopes []string

	// AnyScopes requires at least one of these scopes.
	AnyScopes []string

	// HeaderName is the header containing the API key.
	// Default: "Authorization" with "Bearer" scheme.
	HeaderName string

	// AllowQueryParam enables API key in query parameter.
	// Default: false (more secure).
	AllowQueryParam bool

	// QueryParamName is the query parameter name.
	// Default: "api_key".
	QueryParamName string

	// RecordUsage updates the last used timestamp on each request.
	// Default: true.
	RecordUsage bool

	// OnError is called when authentication fails.
	// If nil, returns 401 Unauthorized.
	OnError func(w http.ResponseWriter, r *http.Request, err error)

	// OnSuccess is called after successful authentication.
	OnSuccess func(r *http.Request, key *apikey.APIKey)

	// IPExtractor extracts the client IP from the request.
	// If nil, uses r.RemoteAddr.
	IPExtractor func(r *http.Request) string
}

APIKeyMiddlewareConfig contains configuration for the API key middleware.

func DefaultAPIKeyMiddlewareConfig

func DefaultAPIKeyMiddlewareConfig() APIKeyMiddlewareConfig

DefaultAPIKeyMiddlewareConfig returns default configuration.

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message,omitempty"`
}

ErrorResponse represents an error response body.

type Principal

type Principal struct {
	// Type is "user" or "api_key".
	Type string `json:"type"`

	// ID is the principal's unique identifier.
	ID uuid.UUID `json:"id"`

	// UserID is the user's ID (same as ID for users, owner ID for API keys).
	UserID uuid.UUID `json:"user_id"`

	// OrganizationID is the organization context (optional).
	OrganizationID *uuid.UUID `json:"organization_id,omitempty"`

	// Scopes are the permissions granted to this principal.
	Scopes []string `json:"scopes,omitempty"`

	// Environment is "live" or "test" for API keys.
	Environment string `json:"environment,omitempty"`

	// Metadata contains additional principal data.
	Metadata map[string]string `json:"metadata,omitempty"`
}

Principal represents an authenticated entity (user or API key).

func GetPrincipal

func GetPrincipal(ctx context.Context) *Principal

GetPrincipal retrieves the authenticated principal from the request context.

func (*Principal) HasScope

func (p *Principal) HasScope(scope string) bool

HasScope returns true if the principal has the given scope.

func (*Principal) IsAPIKey

func (p *Principal) IsAPIKey() bool

IsAPIKey returns true if the principal is an API key.

func (*Principal) IsUser

func (p *Principal) IsUser() bool

IsUser returns true if the principal is a user.

Jump to

Keyboard shortcuts

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