web

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2025 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package web provides HTTP handlers for web-based functionality including authentication, form management, and user interface components.

Package web provides HTTP handlers for web-based functionality including authentication, form management, and user interface components.

Package web provides HTTP handlers for web-based functionality including authentication, form management, and user interface components.

Package web provides HTTP handlers for web-based functionality including authentication, form management, and user interface components.

Package web provides HTTP handlers for web-based functionality including authentication, form management, and user interface components.

Package web provides HTTP handlers for web-based functionality including authentication, form management, and user interface components.

Index

Constants

View Source
const (
	// SessionDuration is the duration for which a session remains valid
	SessionDuration = 24 * time.Hour
	// MinPasswordLength is the minimum required length for passwords
	MinPasswordLength = 8
	// XMLHttpRequestHeader is the standard header value for AJAX requests
	XMLHttpRequestHeader = "XMLHttpRequest"
)
View Source
const (
	MaxTitleLength       = 255
	MaxDescriptionLength = 1000
)

Validation constants

View Source
const (
	DefaultCorsMethods = "GET,POST,OPTIONS"
	DefaultCorsHeaders = "Content-Type,Accept,Origin"
)

Default CORS settings for forms

View Source
const (
	// StatusFound is the HTTP status code for redirects
	StatusFound = http.StatusFound // 302
)

Variables

View Source
var Module = fx.Module("web-handlers",

	fx.Provide(

		fx.Annotate(
			NewBaseHandler,
			fx.ParamTags(``, ``, ``, ``, ``, ``, ``, ``),
		),

		NewAuthRequestParser,
		fx.Annotate(
			NewAuthResponseBuilder,
			fx.ParamTags(``),
		),
		NewAuthService,

		fx.Annotate(
			func(
				logger logging.Logger,
				cfg *config.Config,
				sessionManager *session.Manager,
				middlewareManager *middleware.Manager,
				renderer view.Renderer,
				userService user.Service,
				formService form.Service,
			) *HandlerDeps {
				return &HandlerDeps{
					Logger:            logger,
					Config:            cfg,
					SessionManager:    sessionManager,
					MiddlewareManager: middlewareManager,
					Renderer:          renderer,
					UserService:       userService,
					FormService:       formService,
				}
			},
		),
	),

	fx.Provide(

		fx.Annotate(
			func(
				base *BaseHandler,
				authMiddleware *auth.Middleware,
				requestUtils *request.Utils,
				schemaGenerator *validation.SchemaGenerator,
				requestParser *AuthRequestParser,
				responseBuilder *AuthResponseBuilder,
				authService *AuthService,
				sanitizer sanitization.ServiceInterface,
			) (Handler, error) {
				return NewAuthHandler(
					base, authMiddleware, requestUtils, schemaGenerator,
					requestParser, responseBuilder, authService, sanitizer,
				)
			},
			fx.ResultTags(`group:"handlers"`),
		),

		fx.Annotate(
			func(base *BaseHandler, authMiddleware *auth.Middleware) (Handler, error) {
				return NewPageHandler(base, authMiddleware)
			},
			fx.ResultTags(`group:"handlers"`),
		),

		fx.Annotate(
			func(
				base *BaseHandler,
				formService form.Service,
				formValidator *validation.FormValidator,
				sanitizer sanitization.ServiceInterface,
			) (Handler, error) {
				return NewFormWebHandler(base, formService, formValidator, sanitizer), nil
			},
			fx.ResultTags(`group:"handlers"`),
		),

		fx.Annotate(
			func(
				base *BaseHandler,
				formService form.Service,
				accessManager *access.Manager,
				formValidator *validation.FormValidator,
				sanitizer sanitization.ServiceInterface,
			) (Handler, error) {
				return NewFormAPIHandler(base, formService, accessManager, formValidator, sanitizer), nil
			},
			fx.ResultTags(`group:"handlers"`),
		),

		fx.Annotate(
			func(base *BaseHandler, accessManager *access.Manager, authMiddleware *auth.Middleware) (Handler, error) {
				return NewDashboardHandler(base, accessManager, authMiddleware), nil
			},
			fx.ResultTags(`group:"handlers"`),
		),
	),

	fx.Invoke(fx.Annotate(
		func(lc fx.Lifecycle, handlers []Handler, logger logging.Logger) {
			lc.Append(fx.Hook{
				OnStart: func(ctx context.Context) error {
					for _, h := range handlers {
						if err := h.Start(ctx); err != nil {
							logger.Error("failed to start handler", "error", err)

							return fmt.Errorf("start handler: %w", err)
						}
					}

					return nil
				},
				OnStop: func(ctx context.Context) error {
					for _, h := range handlers {
						if err := h.Stop(ctx); err != nil {
							logger.Error("failed to stop handler", "error", err)

							return fmt.Errorf("stop handler: %w", err)
						}
					}

					return nil
				},
			})
		},
		fx.ParamTags(``, `group:"handlers"`),
	)),
)

Module provides web handler dependencies

Functions

func RegisterHandlers

func RegisterHandlers(
	e *echo.Echo,
	handlers []Handler,
	accessManager *access.Manager,
	logger logging.Logger,
)

RegisterHandlers registers all handlers with the Echo instance

Types

type AuthHandler

type AuthHandler struct {
	*BaseHandler
	AuthMiddleware  *auth.Middleware
	RequestUtils    *request.Utils
	SchemaGenerator *validation.SchemaGenerator
	RequestParser   *AuthRequestParser
	ResponseBuilder *AuthResponseBuilder
	AuthService     *AuthService
	Sanitizer       sanitization.ServiceInterface
}

AuthHandler handles authentication-related requests

func NewAuthHandler

func NewAuthHandler(
	base *BaseHandler,
	authMiddleware *auth.Middleware,
	requestUtils *request.Utils,
	schemaGenerator *validation.SchemaGenerator,
	requestParser *AuthRequestParser,
	responseBuilder *AuthResponseBuilder,
	authService *AuthService,
	sanitizer sanitization.ServiceInterface,
) (*AuthHandler, error)

NewAuthHandler creates a new auth handler

func (*AuthHandler) Login

func (h *AuthHandler) Login(c echo.Context) error

Login handles GET /login - displays the login form

func (*AuthHandler) LoginPost

func (h *AuthHandler) LoginPost(c echo.Context) error

LoginPost handles POST /login - processes the login form

This handler: 1. Validates user credentials 2. Creates a new session on success 3. Sets session cookie 4. Returns appropriate response based on request type:

  • JSON response for API requests
  • HTML response with error for regular requests
  • Redirect to dashboard on success

func (*AuthHandler) LoginValidation

func (h *AuthHandler) LoginValidation(c echo.Context) error

LoginValidation handles the login form validation schema request

func (*AuthHandler) Logout

func (h *AuthHandler) Logout(c echo.Context) error

Logout handles POST /logout - processes the logout request

func (*AuthHandler) Register

func (h *AuthHandler) Register(e *echo.Echo)

Register registers the auth handler routes Note: Routes are actually registered by RegisterHandlers in module.go

func (*AuthHandler) Signup

func (h *AuthHandler) Signup(c echo.Context) error

Signup handles GET /signup - displays the signup form

func (*AuthHandler) SignupPost

func (h *AuthHandler) SignupPost(c echo.Context) error

SignupPost handles the signup form submission

func (*AuthHandler) SignupValidation

func (h *AuthHandler) SignupValidation(c echo.Context) error

SignupValidation returns the validation schema for the signup form

func (*AuthHandler) Start

func (h *AuthHandler) Start(_ context.Context) error

Start initializes the auth handler. This is called during application startup.

func (*AuthHandler) Stop

func (h *AuthHandler) Stop(_ context.Context) error

Stop cleans up any resources used by the auth handler. This is called during application shutdown.

func (*AuthHandler) TestEndpoint

func (h *AuthHandler) TestEndpoint(c echo.Context) error

TestEndpoint is a simple test endpoint to verify JSON responses work

type AuthHelper

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

AuthHelper handles common authentication and authorization patterns

func NewAuthHelper

func NewAuthHelper(baseHandler *FormBaseHandler) *AuthHelper

NewAuthHelper creates a new AuthHelper instance

func (*AuthHelper) GetFormWithOwnership

func (h *AuthHelper) GetFormWithOwnership(c echo.Context) (*model.Form, error)

GetFormWithOwnership gets a form and verifies ownership in one call

func (*AuthHelper) RequireAuthenticatedUser

func (h *AuthHelper) RequireAuthenticatedUser(c echo.Context) (*entities.User, error)

RequireAuthenticatedUser ensures the user is authenticated and returns the user object

func (*AuthHelper) RequireFormOwnership

func (h *AuthHelper) RequireFormOwnership(c echo.Context, form *model.Form) error

RequireFormOwnership verifies the user owns the form

type AuthRequestParser

type AuthRequestParser struct{}

AuthRequestParser parses authentication requests.

func NewAuthRequestParser

func NewAuthRequestParser() *AuthRequestParser

NewAuthRequestParser creates a new AuthRequestParser.

func (*AuthRequestParser) ParseLogin

func (p *AuthRequestParser) ParseLogin(c echo.Context) (email, password string, err error)

ParseLogin parses login credentials from the request (JSON or form)

func (*AuthRequestParser) ParseSignup

func (p *AuthRequestParser) ParseSignup(c echo.Context) (user.Signup, error)

ParseSignup parses signup data from the request (JSON or form)

type AuthResponseBuilder

type AuthResponseBuilder struct {
	Renderer view.Renderer
}

AuthResponseBuilder handles authentication-related HTTP responses

func NewAuthResponseBuilder

func NewAuthResponseBuilder(renderer view.Renderer) *AuthResponseBuilder

NewAuthResponseBuilder creates a new AuthResponseBuilder

func (*AuthResponseBuilder) AJAXError

func (b *AuthResponseBuilder) AJAXError(c echo.Context, status int, message string) error

AJAXError returns a JSON error response for AJAX requests

func (*AuthResponseBuilder) HTMLFormError

func (b *AuthResponseBuilder) HTMLFormError(c echo.Context, page string, data *view.PageData, message string) error

HTMLFormError renders the form page with an error message

func (*AuthResponseBuilder) Redirect

func (b *AuthResponseBuilder) Redirect(c echo.Context, location string) error

Redirect returns a redirect response

type AuthService

type AuthService struct {
	UserService    user.Service
	SessionManager *session.Manager
}

AuthService provides authentication services.

func NewAuthService

func NewAuthService(userService user.Service, sessionManager *session.Manager) *AuthService

NewAuthService creates a new AuthService.

func (*AuthService) Login

func (s *AuthService) Login(ctx context.Context, email, password, userAgent string) (*entities.User, string, error)

Login authenticates a user and returns the user and session ID

func (*AuthService) Signup

func (s *AuthService) Signup(
	ctx context.Context,
	signup user.Signup,
	userAgent string,
) (*entities.User, string, error)

Signup creates a new user and session ID

type BaseHandler

type BaseHandler struct {
	Logger         logging.Logger
	Config         *config.Config
	UserService    user.Service
	FormService    form.Service
	Renderer       view.Renderer
	SessionManager *session.Manager
	ErrorHandler   response.ErrorHandlerInterface
	AssetManager   web.AssetManagerInterface // Use interface instead of concrete type
}

BaseHandler provides common functionality for all handlers

func NewBaseHandler

func NewBaseHandler(
	logger logging.Logger,
	cfg *config.Config,
	userService user.Service,
	formService form.Service,
	renderer view.Renderer,
	sessionManager *session.Manager,
	errorHandler response.ErrorHandlerInterface,
	assetManager web.AssetManagerInterface,
) *BaseHandler

NewBaseHandler creates a new base handler with common dependencies

func (*BaseHandler) GetAssetBaseURL

func (h *BaseHandler) GetAssetBaseURL() string

GetAssetBaseURL returns the base URL for assets (convenience method)

func (*BaseHandler) HandleError

func (h *BaseHandler) HandleError(c echo.Context, err error, message string) error

HandleError handles common error scenarios

func (*BaseHandler) HandleForbidden

func (h *BaseHandler) HandleForbidden(c echo.Context, message string) error

HandleForbidden handles forbidden access errors

func (*BaseHandler) HandleNotFound

func (h *BaseHandler) HandleNotFound(c echo.Context, message string) error

HandleNotFound handles not found errors

func (*BaseHandler) NewPageData

func (h *BaseHandler) NewPageData(c echo.Context, title string) *view.PageData

NewPageData creates page data with common fields

func (*BaseHandler) Register

func (h *BaseHandler) Register(_ *echo.Echo)

Register provides default route registration

func (*BaseHandler) RequireAuthenticatedUser

func (h *BaseHandler) RequireAuthenticatedUser(c echo.Context) (*entities.User, error)

RequireAuthenticatedUser ensures the user is authenticated and returns the user object

func (*BaseHandler) Start

func (h *BaseHandler) Start(_ context.Context) error

Start initializes the base handler. This is called during application startup.

func (*BaseHandler) Stop

func (h *BaseHandler) Stop(_ context.Context) error

Stop cleans up any resources used by the base handler. This is called during application shutdown.

func (*BaseHandler) ValidateAssetPath

func (h *BaseHandler) ValidateAssetPath(path string) error

ValidateAssetPath validates an asset path (convenience method)

type CreateFormRequest

type CreateFormRequest struct {
	Title       string
	Description string
	CorsOrigins model.JSON
}

CreateFormRequest represents a form creation request

type DashboardHandler

type DashboardHandler struct {
	*BaseHandler
	AccessManager  *access.Manager
	AuthMiddleware *auth.Middleware
}

DashboardHandler handles dashboard routes.

func NewDashboardHandler

func NewDashboardHandler(
	base *BaseHandler,
	accessManager *access.Manager,
	authMiddleware *auth.Middleware,
) *DashboardHandler

NewDashboardHandler creates a new DashboardHandler.

func (*DashboardHandler) Start

func (h *DashboardHandler) Start(_ context.Context) error

Start initializes the dashboard handler. This is called during application startup.

func (*DashboardHandler) Stop

Stop cleans up any resources used by the dashboard handler. This is called during application shutdown.

type FormAPIHandler

type FormAPIHandler struct {
	*FormBaseHandler
	AccessManager          *access.Manager
	RequestProcessor       FormRequestProcessor
	ResponseBuilder        FormResponseBuilder
	ErrorHandler           FormErrorHandler
	ComprehensiveValidator *validation.ComprehensiveValidator
}

FormAPIHandler handles API form operations

func NewFormAPIHandler

func NewFormAPIHandler(
	base *BaseHandler,
	formService formdomain.Service,
	accessManager *access.Manager,
	formValidator *validation.FormValidator,
	sanitizer sanitization.ServiceInterface,
) *FormAPIHandler

NewFormAPIHandler creates a new FormAPIHandler.

func (*FormAPIHandler) Register

func (h *FormAPIHandler) Register(_ *echo.Echo)

Register registers the FormAPIHandler with the Echo instance.

func (*FormAPIHandler) RegisterAuthenticatedRoutes

func (h *FormAPIHandler) RegisterAuthenticatedRoutes(formsAPI *echo.Group)

RegisterAuthenticatedRoutes registers routes that require authentication

func (*FormAPIHandler) RegisterPublicRoutes

func (h *FormAPIHandler) RegisterPublicRoutes(formsAPI *echo.Group)

RegisterPublicRoutes registers routes that don't require authentication

func (*FormAPIHandler) RegisterRoutes

func (h *FormAPIHandler) RegisterRoutes(e *echo.Echo)

RegisterRoutes registers API routes for forms.

func (*FormAPIHandler) Start

func (h *FormAPIHandler) Start(_ context.Context) error

Start initializes the form API handler. This is called during application startup.

func (*FormAPIHandler) Stop

func (h *FormAPIHandler) Stop(_ context.Context) error

Stop cleans up any resources used by the form API handler. This is called during application shutdown.

type FormBaseHandler

type FormBaseHandler struct {
	*BaseHandler
	FormService   formdomain.Service
	FormValidator *validation.FormValidator
}

FormBaseHandler extends BaseHandler with form-specific functionality

func NewFormBaseHandler

func NewFormBaseHandler(
	base *BaseHandler,
	formService formdomain.Service,
	formValidator *validation.FormValidator,
) *FormBaseHandler

NewFormBaseHandler creates a new form base handler

func (*FormBaseHandler) GetFormByID

func (h *FormBaseHandler) GetFormByID(c echo.Context) (*model.Form, error)

GetFormByID retrieves a form by ID without ownership verification

func (*FormBaseHandler) GetFormWithOwnership

func (h *FormBaseHandler) GetFormWithOwnership(c echo.Context) (*model.Form, error)

GetFormWithOwnership gets a form and verifies ownership in one call

func (*FormBaseHandler) RequireFormOwnership

func (h *FormBaseHandler) RequireFormOwnership(c echo.Context, form *model.Form) error

RequireFormOwnership verifies the user owns the form

type FormCreateRequest

type FormCreateRequest struct {
	Title string `json:"title"`
}

FormCreateRequest represents the data needed to create a form

type FormErrorHandler

type FormErrorHandler interface {
	HandleSchemaError(c echo.Context, err error) error
	HandleSubmissionError(c echo.Context, err error) error
	HandleError(c echo.Context, err error) error
	HandleOwnershipError(c echo.Context, err error) error
	HandleFormNotFoundError(c echo.Context, formID string) error
	HandleFormAccessError(c echo.Context, err error) error
}

FormErrorHandler interface for handling form-specific errors

func NewFormErrorHandler

func NewFormErrorHandler(responseBuilder FormResponseBuilder) FormErrorHandler

NewFormErrorHandler creates a new form error handler

type FormErrorHandlerImpl

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

FormErrorHandlerImpl handles form-specific error scenarios

func (*FormErrorHandlerImpl) HandleError

func (h *FormErrorHandlerImpl) HandleError(c echo.Context, err error) error

HandleError handles validation errors

func (*FormErrorHandlerImpl) HandleFormAccessError

func (h *FormErrorHandlerImpl) HandleFormAccessError(c echo.Context, err error) error

HandleFormAccessError handles form access errors

func (*FormErrorHandlerImpl) HandleFormNotFoundError

func (h *FormErrorHandlerImpl) HandleFormNotFoundError(c echo.Context, formID string) error

HandleFormNotFoundError handles form not found errors

func (*FormErrorHandlerImpl) HandleOwnershipError

func (h *FormErrorHandlerImpl) HandleOwnershipError(c echo.Context, err error) error

HandleOwnershipError handles ownership and authorization errors

func (*FormErrorHandlerImpl) HandleSchemaError

func (h *FormErrorHandlerImpl) HandleSchemaError(c echo.Context, err error) error

HandleSchemaError handles schema-related errors

func (*FormErrorHandlerImpl) HandleSubmissionError

func (h *FormErrorHandlerImpl) HandleSubmissionError(c echo.Context, err error) error

HandleSubmissionError handles form submission errors

type FormOwnershipValidator

type FormOwnershipValidator interface {
	RequireFormOwnership(c echo.Context, form *model.Form) error
}

FormOwnershipValidator interface for validating form ownership

type FormRequestParser

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

FormRequestParser handles parsing and sanitizing form requests

func NewFormRequestParser

func NewFormRequestParser(sanitizer sanitization.ServiceInterface) *FormRequestParser

NewFormRequestParser creates a new FormRequestParser

func (*FormRequestParser) ApplyUpdateToForm

func (p *FormRequestParser) ApplyUpdateToForm(form *model.Form, req *UpdateFormRequest)

ApplyUpdateToForm applies update request to an existing form

func (*FormRequestParser) CreateFormFromRequest

func (p *FormRequestParser) CreateFormFromRequest(userID string, req *CreateFormRequest) *model.Form

CreateFormFromRequest creates a form model from a create request

func (*FormRequestParser) ParseCreateFormRequest

func (p *FormRequestParser) ParseCreateFormRequest(c echo.Context) *CreateFormRequest

ParseCreateFormRequest parses and sanitizes a form creation request

func (*FormRequestParser) ParseUpdateFormRequest

func (p *FormRequestParser) ParseUpdateFormRequest(c echo.Context) *UpdateFormRequest

ParseUpdateFormRequest parses and sanitizes a form update request

type FormRequestProcessor

type FormRequestProcessor interface {
	ProcessCreateRequest(c echo.Context) (*FormCreateRequest, error)
	ProcessUpdateRequest(c echo.Context) (*FormUpdateRequest, error)
	ProcessSchemaUpdateRequest(c echo.Context) (model.JSON, error)
	ProcessSubmissionRequest(c echo.Context) (model.JSON, error)
}

FormRequestProcessor interface for processing form requests

func NewFormRequestProcessor

func NewFormRequestProcessor(
	sanitizer sanitization.ServiceInterface,
	validator *validation.FormValidator,
) FormRequestProcessor

NewFormRequestProcessor creates a new form request processor

type FormRequestProcessorImpl

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

FormRequestProcessorImpl implements FormRequestProcessor

func (*FormRequestProcessorImpl) ProcessCreateRequest

func (p *FormRequestProcessorImpl) ProcessCreateRequest(c echo.Context) (*FormCreateRequest, error)

ProcessCreateRequest processes form creation requests

func (*FormRequestProcessorImpl) ProcessSchemaUpdateRequest

func (p *FormRequestProcessorImpl) ProcessSchemaUpdateRequest(c echo.Context) (model.JSON, error)

ProcessSchemaUpdateRequest processes schema update requests

func (*FormRequestProcessorImpl) ProcessSubmissionRequest

func (p *FormRequestProcessorImpl) ProcessSubmissionRequest(c echo.Context) (model.JSON, error)

ProcessSubmissionRequest processes form submission requests

func (*FormRequestProcessorImpl) ProcessUpdateRequest

func (p *FormRequestProcessorImpl) ProcessUpdateRequest(c echo.Context) (*FormUpdateRequest, error)

ProcessUpdateRequest processes form update requests

type FormResponseBuilder

type FormResponseBuilder interface {
	BuildSuccessResponse(c echo.Context, message string, data map[string]any) error
	BuildErrorResponse(c echo.Context, statusCode int, message string) error
	BuildSchemaResponse(c echo.Context, schema model.JSON) error
	BuildSubmissionResponse(c echo.Context, submission *model.FormSubmission) error
	BuildFormResponse(c echo.Context, form *model.Form) error
	BuildFormListResponse(c echo.Context, forms []*model.Form) error
	BuildValidationErrorResponse(c echo.Context, field, message string) error
	BuildMultipleErrorResponse(c echo.Context, errors []validation.Error) error
}

FormResponseBuilder interface for building standardized responses

func NewFormResponseBuilder

func NewFormResponseBuilder() FormResponseBuilder

NewFormResponseBuilder creates a new form response builder

type FormResponseBuilderImpl

type FormResponseBuilderImpl struct{}

FormResponseBuilderImpl implements FormResponseBuilder

func (*FormResponseBuilderImpl) BuildErrorResponse

func (b *FormResponseBuilderImpl) BuildErrorResponse(c echo.Context, statusCode int, message string) error

BuildErrorResponse builds a standardized error response

func (*FormResponseBuilderImpl) BuildForbiddenResponse

func (b *FormResponseBuilderImpl) BuildForbiddenResponse(c echo.Context, message string) error

BuildForbiddenResponse builds a forbidden response

func (*FormResponseBuilderImpl) BuildFormListResponse

func (b *FormResponseBuilderImpl) BuildFormListResponse(c echo.Context, forms []*model.Form) error

BuildFormListResponse builds a form list response

func (*FormResponseBuilderImpl) BuildFormResponse

func (b *FormResponseBuilderImpl) BuildFormResponse(c echo.Context, form *model.Form) error

BuildFormResponse builds a form response

func (*FormResponseBuilderImpl) BuildMultipleErrorResponse

func (b *FormResponseBuilderImpl) BuildMultipleErrorResponse(
	c echo.Context,
	errors []validation.Error,
) error

BuildMultipleErrorResponse builds a response for multiple validation errors

func (*FormResponseBuilderImpl) BuildNotFoundResponse

func (b *FormResponseBuilderImpl) BuildNotFoundResponse(c echo.Context, resource string) error

BuildNotFoundResponse builds a not found response

func (*FormResponseBuilderImpl) BuildSchemaResponse

func (b *FormResponseBuilderImpl) BuildSchemaResponse(c echo.Context, schema model.JSON) error

BuildSchemaResponse builds a schema response

func (*FormResponseBuilderImpl) BuildSubmissionListResponse

func (b *FormResponseBuilderImpl) BuildSubmissionListResponse(
	c echo.Context,
	submissions []*model.FormSubmission,
) error

BuildSubmissionListResponse builds a response for form submission lists

func (*FormResponseBuilderImpl) BuildSubmissionResponse

func (b *FormResponseBuilderImpl) BuildSubmissionResponse(c echo.Context, submission *model.FormSubmission) error

BuildSubmissionResponse builds a submission response

func (*FormResponseBuilderImpl) BuildSuccessResponse

func (b *FormResponseBuilderImpl) BuildSuccessResponse(c echo.Context, message string, data map[string]any) error

BuildSuccessResponse builds a standardized success response

func (*FormResponseBuilderImpl) BuildValidationErrorResponse

func (b *FormResponseBuilderImpl) BuildValidationErrorResponse(c echo.Context, field, message string) error

BuildValidationErrorResponse builds a validation error response

type FormResponseHelper

type FormResponseHelper struct{}

FormResponseHelper handles form-related HTTP responses

func NewFormResponseHelper

func NewFormResponseHelper() *FormResponseHelper

NewFormResponseHelper creates a new FormResponseHelper

func (*FormResponseHelper) HandleCreateFormError

func (r *FormResponseHelper) HandleCreateFormError(c echo.Context, err error) error

HandleCreateFormError handles errors from form creation

func (*FormResponseHelper) SendCreateFormSuccess

func (r *FormResponseHelper) SendCreateFormSuccess(c echo.Context, formID string) error

SendCreateFormSuccess sends a successful form creation response

func (*FormResponseHelper) SendDeleteFormSuccess

func (r *FormResponseHelper) SendDeleteFormSuccess(c echo.Context) error

SendDeleteFormSuccess sends a successful form deletion response

func (*FormResponseHelper) SendUpdateFormSuccess

func (r *FormResponseHelper) SendUpdateFormSuccess(c echo.Context, formID string) error

SendUpdateFormSuccess sends a successful form update response

type FormRetriever

type FormRetriever interface {
	GetFormByID(c echo.Context) (*model.Form, error)
	GetFormWithOwnership(c echo.Context) (*model.Form, error)
}

FormRetriever interface for retrieving forms

type FormService

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

FormService handles form-related business logic

func NewFormService

func NewFormService(formService formdomain.Service, logger logging.Logger) *FormService

NewFormService creates a new FormService instance

func (*FormService) CreateForm

func (s *FormService) CreateForm(ctx context.Context, userID string, req *FormCreateRequest) (*model.Form, error)

CreateForm creates a new form with the given request data

func (*FormService) DeleteForm

func (s *FormService) DeleteForm(ctx context.Context, formID string) error

DeleteForm deletes a form by ID

func (*FormService) GetFormSubmissions

func (s *FormService) GetFormSubmissions(ctx context.Context, formID string) ([]*model.FormSubmission, error)

GetFormSubmissions retrieves submissions for a form

func (*FormService) LogFormAccess

func (s *FormService) LogFormAccess(form *model.Form)

LogFormAccess logs form access for debugging

func (*FormService) UpdateForm

func (s *FormService) UpdateForm(ctx context.Context, form *model.Form, req *FormUpdateRequest) error

UpdateForm updates an existing form with the given request data

type FormUpdateRequest

type FormUpdateRequest struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	Status      string `json:"status"`
	CorsOrigins string `json:"cors_origins"`
}

FormUpdateRequest represents the data needed to update a form

type FormWebHandler

type FormWebHandler struct {
	*FormBaseHandler
	Sanitizer        sanitization.ServiceInterface
	RequestProcessor FormRequestProcessor
	ResponseBuilder  FormResponseBuilder
	ErrorHandler     FormErrorHandler
	FormService      *FormService
	AuthHelper       *AuthHelper
}

FormWebHandler handles web UI form operations

func NewFormWebHandler

func NewFormWebHandler(
	base *BaseHandler,
	formService formdomain.Service,
	formValidator *validation.FormValidator,
	sanitizer sanitization.ServiceInterface,
) *FormWebHandler

NewFormWebHandler creates a new FormWebHandler instance

func (*FormWebHandler) Register

func (h *FormWebHandler) Register(_ *echo.Echo)

Register satisfies the Handler interface

func (*FormWebHandler) RegisterRoutes

func (h *FormWebHandler) RegisterRoutes(e *echo.Echo, accessManager *access.Manager)

RegisterRoutes registers all form-related routes

func (*FormWebHandler) Start

func (h *FormWebHandler) Start(_ context.Context) error

Start initializes the form web handler.

func (*FormWebHandler) Stop

func (h *FormWebHandler) Stop(_ context.Context) error

Stop cleans up any resources used by the form web handler.

type Handler

type Handler interface {
	// Register registers the handler's routes with the Echo instance.
	// This method should be called by the RegisterHandlers function in module.go.
	// The handler should not apply middleware directly - this is handled by RegisterHandlers.
	// Routes should be grouped logically and follow RESTful patterns where appropriate.
	Register(e *echo.Echo)

	// Start initializes the handler and any required resources.
	// This is called during application startup.
	Start(ctx context.Context) error

	// Stop cleans up any resources used by the handler.
	// This is called during application shutdown.
	Stop(ctx context.Context) error
}

Handler defines the interface for web handlers. Each handler is responsible for a specific set of related routes. Handlers should: 1. Be focused on a single domain area (e.g., forms, auth, dashboard) 2. Use the HandlerDeps struct for common dependencies 3. Implement proper error handling and logging 4. Follow consistent route naming patterns 5. Use the context helpers for user data access

type HandlerDeps

type HandlerDeps struct {
	// Logger provides logging capabilities for structured logging
	Logger logging.Logger
	// Config provides application configuration and settings
	Config *config.Config
	// SessionManager handles user sessions and authentication state
	SessionManager *session.Manager
	// MiddlewareManager manages middleware configuration and setup
	MiddlewareManager *middleware.Manager
	// Renderer handles view rendering and template management
	Renderer view.Renderer
	// UserService provides user-related operations and business logic
	UserService user.Service
	// FormService provides form-related operations and business logic
	FormService form.Service
}

HandlerDeps contains dependencies for web handlers. This struct is embedded in each handler to provide access to these dependencies. All handlers should use these dependencies through this struct rather than accessing them directly or creating their own instances.

func NewHandlerDeps

func NewHandlerDeps(params *HandlerParams) (*HandlerDeps, error)

NewHandlerDeps creates a new HandlerDeps instance. This factory function ensures that all dependencies are properly initialized and validated before being used by a handler.

func (*HandlerDeps) Start

func (d *HandlerDeps) Start(_ context.Context) error

Start initializes the handler dependencies.

func (*HandlerDeps) Stop

func (d *HandlerDeps) Stop(_ context.Context) error

Stop cleans up any resources used by the handler dependencies.

func (*HandlerDeps) Validate

func (d *HandlerDeps) Validate() error

Validate checks if all required dependencies are present. This should be called when creating a new handler to ensure all required dependencies are properly initialized.

type HandlerParams

type HandlerParams struct {
	UserService       user.Service
	FormService       form.Service
	Logger            logging.Logger
	Config            *config.Config
	SessionManager    *session.Manager
	MiddlewareManager *middleware.Manager
	Renderer          view.Renderer
}

HandlerParams contains parameters for creating a handler. This struct is used to pass dependencies to NewHandlerDeps in a type-safe and explicit way.

type PageHandler

type PageHandler struct {
	*BaseHandler
	AuthMiddleware *auth.Middleware
}

PageHandler handles web page requests

func NewPageHandler

func NewPageHandler(base *BaseHandler, authMiddleware *auth.Middleware) (*PageHandler, error)

NewPageHandler creates a new web handler using BaseHandler

func (*PageHandler) Register

func (h *PageHandler) Register(e *echo.Echo)

Register registers the web routes

func (*PageHandler) Start

func (h *PageHandler) Start(_ context.Context) error

Start initializes the page handler. This is called during application startup.

func (*PageHandler) Stop

func (h *PageHandler) Stop(_ context.Context) error

Stop cleans up any resources used by the page handler. This is called during application shutdown.

type RouteRegistrar

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

RouteRegistrar handles route registration for all handlers

func NewRouteRegistrar

func NewRouteRegistrar(
	handlers []Handler,
	accessManager *access.Manager,
	logger logging.Logger,
) *RouteRegistrar

NewRouteRegistrar creates a new route registrar

func (*RouteRegistrar) RegisterAll

func (rr *RouteRegistrar) RegisterAll(e *echo.Echo)

RegisterAll registers all handler routes

type UpdateFormRequest

type UpdateFormRequest struct {
	Title       string
	Description string
	Status      string
	CorsOrigins model.JSON
}

UpdateFormRequest represents a form update request

Jump to

Keyboard shortcuts

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