shared

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 16 Imported by: 0

Documentation

Overview

SPDX-License-Identifier: AGPL-3.0-or-later

SPDX-License-Identifier: AGPL-3.0-or-later

SPDX-License-Identifier: AGPL-3.0-or-later

SPDX-License-Identifier: AGPL-3.0-or-later

SPDX-License-Identifier: AGPL-3.0-or-later

Index

Constants

View Source
const (
	// ContextKeyUser is the context key for the authenticated user
	ContextKeyUser ContextKey = "user"
	// ContextKeyRequestID is the context key for the request ID
	ContextKeyRequestID ContextKey = "request_id"
	// CSRFTokenHeader is the header name for CSRF token
	CSRFTokenHeader = "X-CSRF-Token"
	// CSRFTokenCookie is the cookie name for CSRF token
	CSRFTokenCookie = "csrf_token"
)

Variables

This section is empty.

Functions

func AddRequestIDToContext

func AddRequestIDToContext(next http.Handler) http.Handler

AddRequestIDToContext middleware adds the request ID from chi middleware to our context

func GetUserFromContext

func GetUserFromContext(ctx context.Context) (*types.User, bool)

GetUserFromContext retrieves the user from the request context

func RequestLogger

func RequestLogger(next http.Handler) http.Handler

RequestLogger middleware logs all API requests with structured logging

func SecurityHeaders

func SecurityHeaders(next http.Handler) http.Handler

SecurityHeaders middleware adds security headers

func WriteConflict

func WriteConflict(w http.ResponseWriter, message string)

func WriteError

func WriteError(w http.ResponseWriter, statusCode int, code ErrorCode, message string, details map[string]interface{})

func WriteForbidden

func WriteForbidden(w http.ResponseWriter, message string)

func WriteInternalError

func WriteInternalError(w http.ResponseWriter)

func WriteJSON

func WriteJSON(w http.ResponseWriter, statusCode int, data interface{})

func WriteJSONWithMeta

func WriteJSONWithMeta(w http.ResponseWriter, statusCode int, data interface{}, meta map[string]interface{})

func WriteNotFound

func WriteNotFound(w http.ResponseWriter, resource string)

func WritePaginatedJSON

func WritePaginatedJSON(w http.ResponseWriter, data interface{}, page, limit, total int)

func WriteUnauthorized

func WriteUnauthorized(w http.ResponseWriter, message string)

func WriteValidationError

func WriteValidationError(w http.ResponseWriter, message string, fieldErrors map[string]string)

Types

type ContextKey

type ContextKey string

ContextKey represents a context key type

type ErrorCode

type ErrorCode string

ErrorCode represents standardized API error codes

const (
	// Client errors
	ErrCodeValidation   ErrorCode = "VALIDATION_ERROR"
	ErrCodeBadRequest   ErrorCode = "BAD_REQUEST"
	ErrCodeUnauthorized ErrorCode = "UNAUTHORIZED"
	ErrCodeForbidden    ErrorCode = "FORBIDDEN"
	ErrCodeNotFound     ErrorCode = "NOT_FOUND"
	ErrCodeConflict     ErrorCode = "CONFLICT"
	ErrCodeRateLimited  ErrorCode = "RATE_LIMITED"
	ErrCodeCSRFInvalid  ErrorCode = "CSRF_INVALID"

	// Server errors
	ErrCodeInternal           ErrorCode = "INTERNAL_ERROR"
	ErrCodeServiceUnavailable ErrorCode = "SERVICE_UNAVAILABLE"
)

type ErrorDetail

type ErrorDetail struct {
	Code    ErrorCode              `json:"code"`
	Message string                 `json:"message"`
	Details map[string]interface{} `json:"details,omitempty"`
}

ErrorDetail contains error details

type ErrorResponse

type ErrorResponse struct {
	Error ErrorDetail `json:"error"`
}

ErrorResponse represents a standardized error response

type Middleware

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

Middleware represents API middleware

func NewMiddleware

func NewMiddleware(authProvider providers.AuthProvider, baseURL string, authorizer providers.Authorizer) *Middleware

NewMiddleware creates a new middleware instance

func (*Middleware) CORS

func (m *Middleware) CORS(next http.Handler) http.Handler

CORS middleware for handling cross-origin requests

func (*Middleware) CSRFProtect

func (m *Middleware) CSRFProtect(next http.Handler) http.Handler

CSRFProtect middleware for CSRF protection

func (*Middleware) GenerateCSRFToken

func (m *Middleware) GenerateCSRFToken() (string, error)

GenerateCSRFToken generates a new CSRF token

func (*Middleware) OptionalAuth

func (m *Middleware) OptionalAuth(next http.Handler) http.Handler

OptionalAuth middleware adds user to context if authenticated, but doesn't block if not

func (*Middleware) RequireAdmin

func (m *Middleware) RequireAdmin(next http.Handler) http.Handler

RequireAdmin middleware ensures user is an admin

func (*Middleware) RequireAuth

func (m *Middleware) RequireAuth(next http.Handler) http.Handler

RequireAuth middleware ensures user is authenticated

func (*Middleware) ValidateCSRFToken

func (m *Middleware) ValidateCSRFToken(token string) bool

ValidateCSRFToken validates a CSRF token

type PaginationMeta

type PaginationMeta struct {
	Page       int `json:"page"`
	Limit      int `json:"limit"`
	Total      int `json:"total"`
	TotalPages int `json:"totalPages"`
}

PaginationMeta represents pagination metadata

type PaginationParams added in v1.2.3

type PaginationParams struct {
	Page     int `json:"page" schema:"page"`
	PageSize int `json:"page_size" schema:"page_size"`
	Offset   int `json:"-"`
}

PaginationParams represents pagination query parameters

func NewPaginationParams added in v1.2.3

func NewPaginationParams(defaultPage, defaultPageSize, maxPageSize int) *PaginationParams

func ParsePaginationParams added in v1.2.3

func ParsePaginationParams(r *http.Request, defaultPageSize, maxPageSize int) *PaginationParams

func (*PaginationParams) Validate added in v1.2.3

func (p *PaginationParams) Validate(maxPageSize int)

Validate validates pagination parameters and calculates offset

type RLSMiddleware added in v1.2.8

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

RLSMiddleware provides Row Level Security context for database queries. It wraps each request in a transaction with app.tenant_id set via set_config. RLS is always active - this is a security feature that cannot be disabled.

func NewRLSMiddleware added in v1.2.8

func NewRLSMiddleware(db *sql.DB, tenants tenant.Provider) *RLSMiddleware

NewRLSMiddleware creates a new RLS middleware.

func (*RLSMiddleware) Handler added in v1.2.8

func (m *RLSMiddleware) Handler(next http.Handler) http.Handler

Handler wraps HTTP requests with RLS transaction context. For each request: 1. Gets the current tenant ID from the provider 2. Starts a database transaction 3. Sets app.tenant_id in the session via set_config 4. Stores the transaction in the request context 5. Calls the next handler 6. Commits on success (2xx-3xx status) or rolls back on error/panic

type RateLimit

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

RateLimit represents a simple rate limiter

func NewRateLimit

func NewRateLimit(limit int, window time.Duration) *RateLimit

NewRateLimit creates a new rate limiter

func (*RateLimit) Middleware

func (rl *RateLimit) Middleware(next http.Handler) http.Handler

RateLimitMiddleware creates a rate limiting middleware

type Response

type Response struct {
	Data interface{}            `json:"data,omitempty"`
	Meta map[string]interface{} `json:"meta,omitempty"`
}

Response represents a standardized API response

Jump to

Keyboard shortcuts

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