Documentation
¶
Overview ¶
Package middleware provides HTTP middleware for authentication and authorization.
Package middleware provides HTTP middleware for CoreForge session management.
Index ¶
- Constants
- func APIKeyMiddleware(config APIKeyMiddlewareConfig) func(http.Handler) http.Handler
- func ChiAuth(jwtService *jwt.Service) func(http.Handler) http.Handler
- func ChiAuthOptional(jwtService *jwt.Service) func(http.Handler) http.Handler
- func ChiRequireAnyPermission(permissions ...string) func(http.Handler) http.Handler
- func ChiRequireAnyRole(roles ...string) func(http.Handler) http.Handler
- func ChiRequireOrganization() func(http.Handler) http.Handler
- func ChiRequirePermission(permission string) func(http.Handler) http.Handler
- func ChiRequirePlatformAdmin() func(http.Handler) http.Handler
- func ChiRequireRole(role string) func(http.Handler) http.Handler
- func ClaimsFromContext(ctx context.Context) *jwt.Claims
- func ContextWithClaims(ctx context.Context, claims *jwt.Claims) context.Context
- func GetAPIKey(ctx context.Context) *apikey.APIKey
- func HTTPAuth(jwtService *jwt.Service) func(http.Handler) http.Handler
- func HTTPAuthOptional(jwtService *jwt.Service) func(http.Handler) http.Handler
- func HasAllPermissions(ctx context.Context, permissions ...string) bool
- func HasAnyPermission(ctx context.Context, permissions ...string) bool
- func HasAnyRole(ctx context.Context, roles ...string) bool
- func HasPermission(ctx context.Context, permission string) bool
- func HasRole(ctx context.Context, role string) bool
- func IsPlatformAdminFromContext(ctx context.Context) bool
- func OptionalAPIKey(service *apikey.Service) func(http.Handler) http.Handler
- func OrganizationIDFromContext(ctx context.Context) *uuid.UUID
- func PermissionsFromContext(ctx context.Context) []string
- func RequireAPIKey(service *apikey.Service) func(http.Handler) http.Handler
- func RequireAPIKeyWithScopes(service *apikey.Service, scopes ...string) func(http.Handler) http.Handler
- func RequireAnyPermission(permissions ...string) func(http.Handler) http.Handler
- func RequireAnyRole(roles ...string) func(http.Handler) http.Handler
- func RequireAnyScope(scopes ...string) func(http.Handler) http.Handler
- func RequireOrganization() func(http.Handler) http.Handler
- func RequirePermission(permission string) func(http.Handler) http.Handler
- func RequirePlatformAdmin() func(http.Handler) http.Handler
- func RequireRole(role string) func(http.Handler) http.Handler
- func RequireScope(scope string) func(http.Handler) http.Handler
- func RoleFromContext(ctx context.Context) string
- func UserIDFromContext(ctx context.Context) uuid.UUID
- type APIKeyMiddlewareConfig
- type ErrorResponse
- type Principal
Constants ¶
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 ¶
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 ¶
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 ¶
ChiRequireAnyPermission returns a Chi-compatible middleware that requires any of the specified permissions.
func ChiRequireAnyRole ¶
ChiRequireAnyRole returns a Chi-compatible middleware that requires any of the specified roles.
func ChiRequireOrganization ¶
ChiRequireOrganization returns a Chi-compatible middleware that requires organization context.
func ChiRequirePermission ¶
ChiRequirePermission returns a Chi-compatible middleware that requires a specific permission.
func ChiRequirePlatformAdmin ¶
ChiRequirePlatformAdmin returns a Chi-compatible middleware that requires platform admin status.
func ChiRequireRole ¶
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 ¶
ClaimsFromContext extracts JWT claims from the context. Returns nil if no claims are present.
func ContextWithClaims ¶
ContextWithClaims returns a new context with the JWT claims attached.
func HTTPAuth ¶
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 ¶
HTTPAuthOptional returns middleware that validates JWT tokens if present, but allows requests without tokens to proceed.
func HasAllPermissions ¶
HasAllPermissions checks if the user has all of the specified permissions.
func HasAnyPermission ¶
HasAnyPermission checks if the user has any of the specified permissions.
func HasAnyRole ¶
HasAnyRole checks if the user has any of the specified roles.
func HasPermission ¶
HasPermission checks if the user has a specific permission.
func IsPlatformAdminFromContext ¶
IsPlatformAdminFromContext checks if the user is a platform admin. Returns false if no claims are present.
func OptionalAPIKey ¶
OptionalAPIKey creates middleware that validates API keys if present but doesn't require them.
func OrganizationIDFromContext ¶
OrganizationIDFromContext extracts the organization ID from the context. Returns nil if no organization context is present.
func PermissionsFromContext ¶
PermissionsFromContext extracts the user's permissions from the context. Returns nil if no permissions are present.
func RequireAPIKey ¶
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 ¶
RequireAnyPermission returns middleware that requires any of the specified permissions. Must be used after HTTPAuth middleware.
func RequireAnyRole ¶
RequireAnyRole returns middleware that requires the user to have any of the specified roles. Must be used after HTTPAuth middleware.
func RequireAnyScope ¶
RequireAnyScope creates middleware that checks for any of the given scopes.
func RequireOrganization ¶
RequireOrganization returns middleware that requires an organization context. Must be used after HTTPAuth middleware.
func RequirePermission ¶
RequirePermission returns middleware that requires a specific permission. Must be used after HTTPAuth middleware.
func RequirePlatformAdmin ¶
RequirePlatformAdmin returns middleware that requires platform admin status. Must be used after HTTPAuth middleware.
func RequireRole ¶
RequireRole returns middleware that requires the user to have a specific role. Must be used after HTTPAuth middleware.
func RequireScope ¶
RequireScope creates middleware that checks for a specific scope. This should be used after APIKeyMiddleware.
func RoleFromContext ¶
RoleFromContext extracts the user's role from the context. Returns empty string if no role 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 ¶
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 ¶
GetPrincipal retrieves the authenticated principal from the request context.