# `authentication/emi_auth.py` ## Overview This file provides the primary authentication middleware (`EMICheckoutMiddleware`) used to secure the core API endpoints (`/api/*`) in the EMI Checkout application. ## Class: `EMICheckoutMiddleware` ### `main(cls, func)` (Decorator) This decorator is applied to Flask routes to enforce authentication before the route logic is executed. - **Workflow**: 1. Checks if the `HTTP_AUTHORIZATION` header is present. 2. If a Bearer token is provided, it extracts the token and decodes it using `jwt_decode`. 3. Extracts `user_id` and `vendor_id` from the decoded token payload. 4. Calls `AuthMiddleware('Database').main(user_id, vendor_id)` (an external library/module) to validate the credentials against the database. 5. If no token is provided, it attempts a fallback authentication `AuthMiddleware('Database').main()`, which likely inspects basic auth headers (Client ID/Secret) mapped in the database. 6. On successful validation, it injects the `vendor_id` into the `request.environ` for downstream usage. 7. Returns an `auth_failure_response` if authentication fails or an exception occurs. ### `jwt_decode(token)` (Static Method) - Simply decodes the provided JWT token to extract its payload. - **Note**: It uses `options={"verify_signature": False}` because it appears the actual validation of the user/vendor mapping is done via the database call afterward. ## Dependencies - `flask` (`request`, `g`) - `jwt` (PyJWT) - `bugsnag` - `AuthMiddleware` (from `auth_middleware`) - `auth_failure_response` (from `response_templates.response_builders`)