Spaces:
Sleeping
Ain El Aql Backend - Comprehensive Technical Documentation
1) Purpose and Scope
This document is the single-source technical overview for the Ain El Aql backend.
It covers:
- System architecture
- Authentication and authorization
- Role model and access scope
- Endpoint catalog and contracts
- End-to-end data flow
- Database model and relationships
- Validation, errors, and operational behavior
- Production readiness guidance
Primary implementation file:
API.py
Supporting documentation:
docs/API_REFERENCE.mddocs/BACKEND_ARCHITECTURE.mddocs/ENVIRONMENT_VARIABLES.md
2) System Architecture
The backend is a FastAPI monolith that combines:
- AI inference orchestration (local YOLO or remote model service)
- Supabase-backed auth, profile, data persistence, and storage
- Parking/session lifecycle and event feeds
- Pricing and occupancy engines
- Gate/payment decision logic
Runtime Components
- API framework: FastAPI
- CV/ML runtime: OpenCV, NumPy, Ultralytics YOLO
- Data/auth/storage backend: Supabase (Auth + PostgREST + Storage)
- Payment provider: Paymob (optional)
Inference Modes
MODEL_INFERENCE_PROVIDER=local- Inference executed in this service.
MODEL_INFERENCE_PROVIDER=remote- Backend calls external model runtime using
MODEL_SERVICE_URL.
- Backend calls external model runtime using
3) Authentication and Authorization
The backend supports two authentication paths:
- Supabase JWT bearer token
- Barrier/device static token
3.1 Supabase Token Auth
- Header:
Authorization: Bearer <supabase_access_token> - Validation endpoint: Supabase
GET /auth/v1/user - On successful verification:
- backend derives user id/email
- backend auto-creates a minimal
profilesrow when missing (best effort)
Why auto-provision profile rows:
- Prevent FK failures on writes referencing
profiles.id. - Reduce silent persistence failures when auth users exist but profile rows do not.
3.2 Barrier/Device Token Auth
- Header:
Authorization: Bearer <barrier_token> - Token sources:
BARRIER_API_TOKEN(single token)BARRIER_API_TOKENS(comma-separated tokens)
- Comparison uses constant-time matching (
hmac.compare_digest). - Returns synthetic auth context:
id = BARRIER_SYNTHETIC_USER_ID(defaultbarrier-device)role = barrierauth_type = barrier_token
Important:
- Barrier auth is intended for machine integrations (camera/barrier clients).
- Barrier auth is not a substitute for end-user mobile/web sessions.
4) Role Model and Access Scope
Roles in runtime behavior:
useradminsecuritydeveloperbarrier(synthetic API role)
4.1 Scope Rules
- User scope:
- Own records only
- Staff scope (
admin,security):- Global records
- optional
for_user_idfiltering on feed/history endpoints
- Barrier scope (
barrier):- Global read scope for operational feeds/history and gate decision checks
- Not treated as staff for privileged maintenance/payment confirmations
- Developer scope (
developer):- Access to developer endpoints (
/developer/*)
- Access to developer endpoints (
5) Endpoint Catalog
5.1 Public/Utility
GET /GET /healthGET /supabase/healthGET /models
5.2 Developer
GET /developer/modelsPOST /developer/predict
5.3 Authentication
POST /auth/registerPOST /auth/loginPOST /auth/otp/requestPOST /auth/otp/verifyPOST /auth/forgot-passwordPOST /auth/reset-password/resolve-tokenPOST /auth/reset-passwordGET /auth/reset-password-pageGET /auth/reset-password-bridge
5.4 Profile and Vehicles
PUT /profile/updatePOST /vehicles/addGET /vehicles/myPUT /vehicles/{vehicle_id}DELETE /vehicles/{vehicle_id}POST /vehicles/verify
5.5 Notifications
POST /notifications/fcm-tokenGET /notifications/my
5.6 Inference and Model Runtime
POST /predictPOST /model/infer
5.7 Parking/Events/History
GET /parking/locationsGET /parking/occupancyGET /events/entered-carsGET /events/leaving-cars-within-5-minutesGET /events/new-carsGET /events/left-carsGET /events/inside-carsGET /parking/history
5.8 Payments and Gate
POST /payments/paymob/createPOST /payments/paymob/webhookPOST /payments/manual/cash-confirmPOST /gate/decision
5.9 Maintenance
POST /admin/maintenance/weekly-refresh
6) End-to-End Data Flow
6.1 Predict Request Flow (POST /predict)
- Authenticate request (Supabase token or barrier token).
- Validate optional inputs:
event_typein{entry, exit, ocr_scan}parking_locationpatterncamera_sourcepattern
- Run inference pipeline (local or remote).
- Build normalized plate payload.
- Persist output to Supabase:
- upload raw and processed images to storage buckets
- resolve vehicle from OCR plate
- resolve/create session depending on event type
- create
car_eventsrow - optionally emit notification events
- Compute and return:
payment_statuspricinggate_decision- persistence metadata
6.2 Vehicle Resolution Logic
The backend now matches OCR plates using both formats:
- Arabic plate fields:
plate_letters_ar + plate_numbers_ar - English plate fields:
plate_letters_en + plate_numbers_en
Matching order:
- Owner-scoped lookup (when authenticated Supabase user id is available)
- Global lookup fallback
Effect:
- Reduces false negatives where OCR returns one language format but not the other.
6.3 Session Lifecycle
entry- create or reuse open session
exit- use open session
- if paid and within 5 minutes: close session (
status=exited) - if paid but grace expired: keep open with
status=overstayed - if unpaid: keep open (gate deny path)
ocr_scan- read context only, no session state transition
6.4 Unmatched Fallback Flow
When a plate is detected but not linked to a registered vehicle/session:
- Event is still stored in
car_events(with nullablevehicle_id/session_id). - Backend builds inferred unmatched rows from entry/exit event streams by plate key.
- Inferred rows are merged into:
GET /parking/locationsGET /parking/occupancyGET /events/inside-carsGET /parking/history
Response markers for inferred rows:
inferred_unmatched=trueplateobject (key/arabic/english)event_count
Occupancy responses also include source breakdown:
inside_from_registered_sessionsinside_from_inferred_unmatched
7) Database Model (Supabase)
Core relational tables:
profiles- user identity/profile metadata
- role and staff metadata
vehicles- vehicle registration and ownership
parking_sessions- parking lifecycle state
car_events- entry/exit/scan event stream
payment_transactions- payment ledger for paymob/manual cash
Notifications and app links:
notification_device_tokensnotification_eventsapp_links
Key Relationships
profiles.id->auth.users.idvehicles.owner_id->profiles.idparking_sessions.vehicle_id->vehicles.idcar_events.session_id->parking_sessions.id(nullable)car_events.vehicle_id->vehicles.id(nullable)
Storage Buckets
SUPABASE_RAW_BUCKET(raw uploads)SUPABASE_PROCESSED_BUCKET(split/admin images)
8) Security and Data Integrity
8.1 RLS and Role Design
- Supabase RLS is enabled for core business tables.
- Backend writes are performed via service role credentials.
- Client-facing authorization is enforced in API layer by user role/scope.
8.2 Notification Event Hardening
Current model:
- Notification content is server-owned.
- Authenticated users can read own notifications.
- Authenticated users can only mark own notifications as read.
- Client-side insert/delete/content edits are blocked.
8.3 Created-By FK Protection
For persistence writes:
created_byis now populated only for Supabase-authenticated users.- Barrier-auth requests do not inject synthetic ids into FK-backed columns.
This prevents FK violations and silent persistence drop scenarios.
9) Validation and Error Contract
Common input validations:
- Auth header format (
Bearer ...) event_typeallowed values- parking location format
- camera source format
- file type and non-empty uploads
- payment amount positive integer rules
Common error statuses:
400invalid input401auth missing/invalid/expired403role or scope violation404missing session/resource502upstream integration failure503missing critical configuration
10) Production Readiness Checklist
10.1 Required Environment
SUPABASE_URLSUPABASE_ANON_KEYSUPABASE_SERVICE_ROLE_KEYSUPABASE_ENFORCE_AUTH=true(recommended)- model runtime config (
MODEL_INFERENCE_PROVIDER+ remote/local settings)
Optional but recommended:
PASSWORD_RESET_REDIRECT_URLBARRIER_API_TOKENorBARRIER_API_TOKENS(if device auth is needed)- pricing/capacity config
- paymob config if card payments enabled
10.2 Database Migration Baseline
Ensure latest SQL is applied, including:
supabase/04_auth_profile_vehicle_upgrade.sqlsupabase/05_multi_vehicle_auth_notifications.sqlsupabase/06_profile_name_parts_upgrade.sql
10.3 Smoke Tests
GET /healthGET /supabase/health- Auth login/register flow
POST /predict(entry + exit)GET /parking/locationsGET /events/inside-carsGET /parking/history- Gate decision endpoint
- Password reset flow (bridge + page + resolver)
10.4 Operational Guardrails
- Rotate service secrets and barrier tokens regularly.
- Keep
SUPABASE_SERVICE_ROLE_KEYbackend-only. - Monitor
response.supabase.savedfrom/predictintegrations. - Alert on repeated
saved=falseresponses and 5xx spikes.
11) Troubleshooting Guide
Symptom: feeds/history are empty
Checks:
- Confirm requests are authenticated and role scope is correct.
- Verify
/predictresponses includesupabase.saved=true. - Verify vehicle resolution fields (Arabic/English plate matching).
- Confirm sessions are being created (
parking_sessions) and linked to events. - If traffic is mostly unregistered, verify inferred rows are visible (
inferred_unmatched=true).
Symptom: barrier token rejected
Checks:
- Token present as Bearer token
BARRIER_API_TOKENorBARRIER_API_TOKENSset in deployment env- No hidden whitespace in configured token
Symptom: auth user exists but no data persists
Checks:
- Confirm
profilesrow exists for that auth user id. - Confirm Supabase service role key is valid and backend can write tables.
- Inspect backend logs for persistence exceptions.
12) Notes on Backward Compatibility
- Existing Supabase auth clients continue to work unchanged.
- Barrier token support is additive.
- Feed/history response shape is preserved.
- Added optional inferred markers and source-breakdown fields.
- Role checks remain strict for maintenance and payment confirmation endpoints.
13) Recommended Next Improvements
- Add structured audit logs for auth path used (
supabasevsbarrier). - Add metrics counters for vehicle-match source (
arabic,english, fallback). - Add integration tests for:
- missing-profile auto-provision
- barrier gate decision authorization
- plate matching variants (Arabic-only, English-only, mixed)
- Add a migration to introduce an explicit persistent
barrierapp role if database-level modeling is desired.