package middleware import ( "strings" "apskel-pos-be/internal/constants" "apskel-pos-be/internal/contract" "apskel-pos-be/internal/util" "github.com/gin-gonic/gin" ) type SelfOrderAuthMiddleware struct { selfOrderJWTSecret string } func NewSelfOrderAuthMiddleware(selfOrderJWTSecret string) *SelfOrderAuthMiddleware { return &SelfOrderAuthMiddleware{ selfOrderJWTSecret: selfOrderJWTSecret, } } func (m *SelfOrderAuthMiddleware) ValidateSelfOrderToken() gin.HandlerFunc { return func(c *gin.Context) { authHeader := c.GetHeader("Authorization") if authHeader == "" { util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Authorization header is required"), }), "SelfOrderAuthMiddleware::ValidateSelfOrderToken") c.Abort() return } if !strings.HasPrefix(authHeader, "Bearer ") { util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Invalid authorization header format"), }), "SelfOrderAuthMiddleware::ValidateSelfOrderToken") c.Abort() return } tokenString := strings.TrimPrefix(authHeader, "Bearer ") if tokenString == "" { util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Token is required"), }), "SelfOrderAuthMiddleware::ValidateSelfOrderToken") c.Abort() return } claims, err := util.ValidateSelfOrderToken(tokenString, m.selfOrderJWTSecret) if err != nil { util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "Invalid token: "+err.Error()), }), "SelfOrderAuthMiddleware::ValidateSelfOrderToken") c.Abort() return } tableID, ok := claims["table_id"].(string) if !ok || tableID == "" { util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "table_id not found in token"), }), "SelfOrderAuthMiddleware::ValidateSelfOrderToken") c.Abort() return } customerName, ok := claims["customer_name"].(string) if !ok || customerName == "" { util.HandleResponse(c.Writer, c.Request, contract.BuildErrorResponse([]*contract.ResponseError{ contract.NewResponseError(constants.ValidationErrorCode, constants.AuthHandlerEntity, "customer_name not found in token"), }), "SelfOrderAuthMiddleware::ValidateSelfOrderToken") c.Abort() return } phone, _ := claims["phone"].(string) c.Set("self_order_table_id", tableID) c.Set("self_order_customer_name", customerName) c.Set("self_order_phone", phone) c.Next() } }