Security: - Replace all binding: tags with validate: + c.Validate() in admin handlers - Add rate limiting to auth endpoints (login, register, password reset) - Add security headers (HSTS, XSS protection, nosniff, frame options) - Wire Google Pub/Sub token verification into webhook handler - Replace ParseUnverified with proper OIDC/JWKS key verification - Verify inner Apple JWS signatures in webhook handler - Add io.LimitReader (1MB) to all webhook body reads - Add ownership verification to file deletion - Move hardcoded admin credentials to env vars - Add uniqueIndex to User.Email - Hide ConfirmationCode from JSON serialization - Mask confirmation codes in admin responses - Use http.DetectContentType for upload validation - Fix path traversal in storage service - Replace os.Getenv with Viper in stripe service - Sanitize Redis URLs before logging - Separate DEBUG_FIXED_CODES from DEBUG flag - Reject weak SECRET_KEY in production - Add host check on /_next/* proxy routes - Use explicit localhost CORS origins in debug mode - Replace err.Error() with generic messages in all admin error responses Critical fixes: - Rewrite FCM to HTTP v1 API with OAuth 2.0 service account auth - Fix user_customuser -> auth_user table names in raw SQL - Fix dashboard verified query to use UserProfile model - Add escapeLikeWildcards() to prevent SQL wildcard injection Bug fixes: - Add bounds checks for days/expiring_soon query params (1-3650) - Add receipt_data/transaction_id empty-check to RestoreSubscription - Change Active bool -> *bool in device handler - Check all unchecked GORM/FindByIDWithProfile errors - Add validation for notification hour fields (0-23) - Add max=10000 validation on task description updates Transactions & data integrity: - Wrap registration flow in transaction - Wrap QuickComplete in transaction - Move image creation inside completion transaction - Wrap SetSpecialties in transaction - Wrap GetOrCreateToken in transaction - Wrap completion+image deletion in transaction Performance: - Batch completion summaries (2 queries vs 2N) - Reuse single http.Client in IAP validation - Cache dashboard counts (30s TTL) - Batch COUNT queries in admin user list - Add Limit(500) to document queries - Add reminder_stage+due_date filters to reminder queries - Parse AllowedTypes once at init - In-memory user cache in auth middleware (30s TTL) - Timezone change detection cache - Optimize P95 with per-endpoint sorted buffers - Replace crypto/md5 with hash/fnv for ETags Code quality: - Add sync.Once to all monitoring Stop()/Close() methods - Replace 8 fmt.Printf with zerolog in auth service - Log previously discarded errors - Standardize delete response shapes - Route hardcoded English through i18n - Remove FileURL from DocumentResponse (keep MediaURL only) - Thread user timezone through kanban board responses - Initialize empty slices to prevent null JSON - Extract shared field map for task Update/UpdateTx - Delete unused SoftDeleteModel, min(), formatCron, legacy handlers Worker & jobs: - Wire Asynq email infrastructure into worker - Register HandleReminderLogCleanup with daily 3AM cron - Use per-user timezone in HandleSmartReminder - Replace direct DB queries with repository calls - Delete legacy reminder handlers (~200 lines) - Delete unused task type constants Dependencies: - Replace archived jung-kurt/gofpdf with go-pdf/fpdf - Replace unmaintained gomail.v2 with wneessen/go-mail - Add TODO for Echo jwt v3 transitive dep removal Test infrastructure: - Fix MakeRequest/SeedLookupData error handling - Replace os.Exit(0) with t.Skip() in scope/consistency tests - Add 11 new FCM v1 tests Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
381 lines
11 KiB
Go
381 lines
11 KiB
Go
package handlers
|
|
|
|
import (
|
|
"mime/multipart"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/shopspring/decimal"
|
|
|
|
"github.com/treytartt/honeydue-api/internal/apperrors"
|
|
"github.com/treytartt/honeydue-api/internal/dto/requests"
|
|
"github.com/treytartt/honeydue-api/internal/dto/responses"
|
|
"github.com/treytartt/honeydue-api/internal/i18n"
|
|
"github.com/treytartt/honeydue-api/internal/middleware"
|
|
"github.com/treytartt/honeydue-api/internal/models"
|
|
"github.com/treytartt/honeydue-api/internal/repositories"
|
|
"github.com/treytartt/honeydue-api/internal/services"
|
|
)
|
|
|
|
// DocumentHandler handles document-related HTTP requests
|
|
type DocumentHandler struct {
|
|
documentService *services.DocumentService
|
|
storageService *services.StorageService
|
|
}
|
|
|
|
// NewDocumentHandler creates a new document handler
|
|
func NewDocumentHandler(documentService *services.DocumentService, storageService *services.StorageService) *DocumentHandler {
|
|
return &DocumentHandler{
|
|
documentService: documentService,
|
|
storageService: storageService,
|
|
}
|
|
}
|
|
|
|
// ListDocuments handles GET /api/documents/
|
|
func (h *DocumentHandler) ListDocuments(c echo.Context) error {
|
|
user, err := middleware.MustGetAuthUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Build filter from supported query params.
|
|
var filter *repositories.DocumentFilter
|
|
if c.QueryParam("residence") != "" || c.QueryParam("document_type") != "" ||
|
|
c.QueryParam("is_active") != "" || c.QueryParam("expiring_soon") != "" ||
|
|
c.QueryParam("search") != "" {
|
|
filter = &repositories.DocumentFilter{
|
|
DocumentType: c.QueryParam("document_type"),
|
|
Search: c.QueryParam("search"),
|
|
}
|
|
if rid := c.QueryParam("residence"); rid != "" {
|
|
if parsed, err := strconv.ParseUint(rid, 10, 32); err == nil {
|
|
residenceID := uint(parsed)
|
|
filter.ResidenceID = &residenceID
|
|
}
|
|
}
|
|
if ia := c.QueryParam("is_active"); ia != "" {
|
|
isActive := ia == "true" || ia == "1"
|
|
filter.IsActive = &isActive
|
|
}
|
|
if es := c.QueryParam("expiring_soon"); es != "" {
|
|
if parsed, err := strconv.Atoi(es); err == nil {
|
|
if parsed < 1 || parsed > 3650 {
|
|
return apperrors.BadRequest("error.days_out_of_range")
|
|
}
|
|
filter.ExpiringSoon = &parsed
|
|
}
|
|
}
|
|
}
|
|
|
|
response, err := h.documentService.ListDocuments(user.ID, filter)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// GetDocument handles GET /api/documents/:id/
|
|
func (h *DocumentHandler) GetDocument(c echo.Context) error {
|
|
user, err := middleware.MustGetAuthUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
documentID, err := strconv.ParseUint(c.Param("id"), 10, 32)
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.invalid_document_id")
|
|
}
|
|
|
|
response, err := h.documentService.GetDocument(uint(documentID), user.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// ListWarranties handles GET /api/documents/warranties/
|
|
func (h *DocumentHandler) ListWarranties(c echo.Context) error {
|
|
user, err := middleware.MustGetAuthUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
response, err := h.documentService.ListWarranties(user.ID)
|
|
if err != nil {
|
|
return apperrors.Internal(err)
|
|
}
|
|
return c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// CreateDocument handles POST /api/documents/
|
|
// Supports both JSON and multipart form data (for file uploads)
|
|
func (h *DocumentHandler) CreateDocument(c echo.Context) error {
|
|
user, err := middleware.MustGetAuthUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var req requests.CreateDocumentRequest
|
|
|
|
contentType := c.Request().Header.Get("Content-Type")
|
|
|
|
// Check if this is a multipart form request (file upload)
|
|
if strings.HasPrefix(contentType, "multipart/form-data") {
|
|
// Parse multipart form
|
|
if err := c.Request().ParseMultipartForm(32 << 20); err != nil { // 32MB max
|
|
return apperrors.BadRequest("error.failed_to_parse_form")
|
|
}
|
|
|
|
// Parse residence_id (required)
|
|
residenceIDStr := c.FormValue("residence_id")
|
|
if residenceIDStr == "" {
|
|
return apperrors.BadRequest("error.residence_id_required")
|
|
}
|
|
residenceID, err := strconv.ParseUint(residenceIDStr, 10, 32)
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.invalid_residence_id")
|
|
}
|
|
req.ResidenceID = uint(residenceID)
|
|
|
|
// Parse title (required)
|
|
req.Title = c.FormValue("title")
|
|
if req.Title == "" {
|
|
return apperrors.BadRequest("error.title_required")
|
|
}
|
|
|
|
// Parse optional fields
|
|
req.Description = c.FormValue("description")
|
|
req.Vendor = c.FormValue("vendor")
|
|
req.SerialNumber = c.FormValue("serial_number")
|
|
req.ModelNumber = c.FormValue("model_number")
|
|
|
|
// Parse document_type
|
|
if docType := c.FormValue("document_type"); docType != "" {
|
|
dt := models.DocumentType(docType)
|
|
req.DocumentType = dt
|
|
}
|
|
|
|
// Parse task_id (optional)
|
|
if taskIDStr := c.FormValue("task_id"); taskIDStr != "" {
|
|
if taskID, err := strconv.ParseUint(taskIDStr, 10, 32); err == nil {
|
|
tid := uint(taskID)
|
|
req.TaskID = &tid
|
|
}
|
|
}
|
|
|
|
// Parse purchase_price (optional)
|
|
if priceStr := c.FormValue("purchase_price"); priceStr != "" {
|
|
if price, err := decimal.NewFromString(priceStr); err == nil {
|
|
req.PurchasePrice = &price
|
|
}
|
|
}
|
|
|
|
// Parse purchase_date (optional)
|
|
if dateStr := c.FormValue("purchase_date"); dateStr != "" {
|
|
if t, err := time.Parse(time.RFC3339, dateStr); err == nil {
|
|
req.PurchaseDate = &t
|
|
} else if t, err := time.Parse("2006-01-02", dateStr); err == nil {
|
|
req.PurchaseDate = &t
|
|
}
|
|
}
|
|
|
|
// Parse expiry_date (optional)
|
|
if dateStr := c.FormValue("expiry_date"); dateStr != "" {
|
|
if t, err := time.Parse(time.RFC3339, dateStr); err == nil {
|
|
req.ExpiryDate = &t
|
|
} else if t, err := time.Parse("2006-01-02", dateStr); err == nil {
|
|
req.ExpiryDate = &t
|
|
}
|
|
}
|
|
|
|
// Handle file upload (look for "file", "document", or "image" field)
|
|
var uploadedFile *multipart.FileHeader
|
|
for _, fieldName := range []string{"file", "document", "image", "images"} {
|
|
if file, err := c.FormFile(fieldName); err == nil {
|
|
uploadedFile = file
|
|
break
|
|
}
|
|
}
|
|
|
|
if uploadedFile != nil {
|
|
if h.storageService == nil {
|
|
return apperrors.Internal(nil)
|
|
}
|
|
result, err := h.storageService.Upload(uploadedFile, "documents")
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.failed_to_upload_file")
|
|
}
|
|
req.FileURL = result.URL
|
|
req.FileName = result.FileName
|
|
req.MimeType = result.MimeType
|
|
fileSize := result.FileSize
|
|
req.FileSize = &fileSize
|
|
}
|
|
} else {
|
|
// Standard JSON request
|
|
if err := c.Bind(&req); err != nil {
|
|
return apperrors.BadRequest("error.invalid_request")
|
|
}
|
|
}
|
|
|
|
if err := c.Validate(&req); err != nil {
|
|
return err
|
|
}
|
|
|
|
response, err := h.documentService.CreateDocument(&req, user.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.JSON(http.StatusCreated, response)
|
|
}
|
|
|
|
// UpdateDocument handles PUT/PATCH /api/documents/:id/
|
|
func (h *DocumentHandler) UpdateDocument(c echo.Context) error {
|
|
user, err := middleware.MustGetAuthUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
documentID, err := strconv.ParseUint(c.Param("id"), 10, 32)
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.invalid_document_id")
|
|
}
|
|
|
|
var req requests.UpdateDocumentRequest
|
|
if err := c.Bind(&req); err != nil {
|
|
return apperrors.BadRequest("error.invalid_request")
|
|
}
|
|
if err := c.Validate(&req); err != nil {
|
|
return err
|
|
}
|
|
|
|
response, err := h.documentService.UpdateDocument(uint(documentID), user.ID, &req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// DeleteDocument handles DELETE /api/documents/:id/
|
|
func (h *DocumentHandler) DeleteDocument(c echo.Context) error {
|
|
user, err := middleware.MustGetAuthUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
documentID, err := strconv.ParseUint(c.Param("id"), 10, 32)
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.invalid_document_id")
|
|
}
|
|
|
|
err = h.documentService.DeleteDocument(uint(documentID), user.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.JSON(http.StatusOK, responses.MessageResponse{Message: i18n.LocalizedMessage(c, "message.document_deleted")})
|
|
}
|
|
|
|
// ActivateDocument handles POST /api/documents/:id/activate/
|
|
func (h *DocumentHandler) ActivateDocument(c echo.Context) error {
|
|
user, err := middleware.MustGetAuthUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
documentID, err := strconv.ParseUint(c.Param("id"), 10, 32)
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.invalid_document_id")
|
|
}
|
|
|
|
response, err := h.documentService.ActivateDocument(uint(documentID), user.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// DeactivateDocument handles POST /api/documents/:id/deactivate/
|
|
func (h *DocumentHandler) DeactivateDocument(c echo.Context) error {
|
|
user, err := middleware.MustGetAuthUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
documentID, err := strconv.ParseUint(c.Param("id"), 10, 32)
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.invalid_document_id")
|
|
}
|
|
|
|
response, err := h.documentService.DeactivateDocument(uint(documentID), user.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// UploadDocumentImage handles POST /api/documents/:id/images/
|
|
func (h *DocumentHandler) UploadDocumentImage(c echo.Context) error {
|
|
user, err := middleware.MustGetAuthUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
documentID, err := strconv.ParseUint(c.Param("id"), 10, 32)
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.invalid_document_id")
|
|
}
|
|
|
|
// Parse multipart form
|
|
if err := c.Request().ParseMultipartForm(32 << 20); err != nil {
|
|
return apperrors.BadRequest("error.failed_to_parse_form")
|
|
}
|
|
|
|
// Look for file in common field names
|
|
var uploadedFile *multipart.FileHeader
|
|
for _, fieldName := range []string{"image", "file"} {
|
|
if file, err := c.FormFile(fieldName); err == nil {
|
|
uploadedFile = file
|
|
break
|
|
}
|
|
}
|
|
|
|
if uploadedFile == nil {
|
|
return apperrors.BadRequest("error.no_file_provided")
|
|
}
|
|
|
|
if h.storageService == nil {
|
|
return apperrors.Internal(nil)
|
|
}
|
|
|
|
result, err := h.storageService.Upload(uploadedFile, "images")
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.failed_to_upload_file")
|
|
}
|
|
|
|
caption := c.FormValue("caption")
|
|
|
|
response, err := h.documentService.UploadDocumentImage(uint(documentID), user.ID, result.URL, caption)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.JSON(http.StatusCreated, response)
|
|
}
|
|
|
|
// DeleteDocumentImage handles DELETE /api/documents/:id/images/:imageId/
|
|
func (h *DocumentHandler) DeleteDocumentImage(c echo.Context) error {
|
|
user, err := middleware.MustGetAuthUser(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
documentID, err := strconv.ParseUint(c.Param("id"), 10, 32)
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.invalid_document_id")
|
|
}
|
|
|
|
imageID, err := strconv.ParseUint(c.Param("imageId"), 10, 32)
|
|
if err != nil {
|
|
return apperrors.BadRequest("error.invalid_image_id")
|
|
}
|
|
|
|
response, err := h.documentService.DeleteDocumentImage(uint(documentID), uint(imageID), user.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.JSON(http.StatusOK, response)
|
|
}
|