Enhance company context handling in customer middleware and routing
continuous-integration/drone/push Build is passing

- Introduced CompanyContextMiddleware to resolve the active company context for customer requests, ensuring that tender recommendations and company-scoped APIs remain in sync with the database.
- Updated public routes to utilize the new CompanyContextMiddleware alongside the existing AuthMiddleware, improving the handling of company-specific requests.
- Added unit tests for the pickActiveCompanyID function to validate the logic for selecting the appropriate company context based on customer assignments and requested company IDs.

This update enhances the accuracy and reliability of company context management in the application, improving user experience and data consistency.
This commit is contained in:
Mazyar
2026-06-30 22:30:28 +03:30
parent addd616d59
commit 50c018af62
5 changed files with 197 additions and 28 deletions
+34
View File
@@ -1,6 +1,7 @@
package customer
import (
"errors"
"net/http"
"strings"
"tm/pkg/audit"
@@ -61,6 +62,39 @@ func (h *Handler) AuthMiddleware() echo.MiddlewareFunc {
}
}
// CompanyContextMiddleware resolves company_id from current customer assignments.
// JWT company_id can be stale after admin reassigns companies; this keeps tender
// recommendations and other company-scoped APIs in sync with the database.
func (h *Handler) CompanyContextMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
customerID, err := GetCustomerIDFromContext(c)
if err != nil {
return response.Unauthorized(c, "User not authenticated")
}
tokenCompanyID, _ := c.Get("company_id").(string)
requestedCompanyID := strings.TrimSpace(c.QueryParam("company_id"))
companyID, err := h.service.ResolveActiveCompanyID(
c.Request().Context(),
customerID,
tokenCompanyID,
requestedCompanyID,
)
if err != nil {
if errors.Is(err, errCompanyNotAssigned) {
return response.Forbidden(c, "Company is not assigned to customer")
}
return response.Unauthorized(c, "User not authenticated")
}
c.Set("company_id", companyID)
return next(c)
}
}
}
// GetCustomerIDFromContext extracts customer ID from Echo context
func GetCustomerIDFromContext(c echo.Context) (string, error) {
customerID, ok := c.Get("customer_id").(string)