# Backend Service

# Backend Service (Port 8000) {#backend-service-port-8000}


The **backend** service is the core API gateway for MQUAD. It handles authentication, user management, tenant administration, RBAC, and Stripe billing.


## Database {#database}


**Database:** `appdb`

| Table | Purpose |
|-------|---------|
| `users` | User accounts |
| `tenants` | Multi-tenant organizations |
| `user_tenants` | User-Tenant associations |
| `roles` | RBAC role definitions |
| `permissions` | Permission definitions |
| `user_passkeys` | WebAuthn/FIDO2 credentials |
| `user_magic_links` | Magic link tokens for passwordless login |
| `user_password_resets` | Password reset tokens |
| `subscription_plans` | Subscription plan definitions |
| `stripe_settings` | Stripe integration config |
| `notification_settings` | Notification preferences |


## Authentication Flow {#authentication-flow}


The backend supports three primary authentication methods:


### 1. Password-based {#1-password-based}
Standard email/password login using BCrypt for password hashing.


### 2. Magic Links (Passwordless) {#2-magic-links-passwordless}
1. User enters email at `/api/v1/account/login/magic-link`.
2. Backend generates a signed token and creates a `user_magic_links` record.
3. Celery task sends an email via `notification-service`.
4. User clicks link, which is validated by the backend to issue a JWT.


### 3. Passkeys (WebAuthn) {#3-passkeys-webauthn}
- Supports FIDO2/WebAuthn for biometric or hardware key authentication.
- Credentials stored in `user_passkeys` linked to the user.


## RBAC System {#rbac-system}


Access Control is strictly permission-based. The standard check involves looking for specific permission strings in the user's JWT payload:

```python
from common.rbac_helpers import is_super_admin, is_host_admin

# Super Admin: has "super:admin" or "full:access"
if is_super_admin(user.permissions):
    # Grant platform-wide access
    pass

# Host Admin: has "host:manage_tenants"
if is_host_admin(user.permissions):
    # Grant tenant management access
    pass
```


## Stripe Integration {#stripe-integration}


Manages the lifecycle of tenant subscriptions:
- `POST /api/v1/checkout/tenant/subscription` — Starts the Stripe Checkout flow.
- `POST /api/v1/stripe/webhook` — Listens for `customer.subscription.updated` and `invoice.paid` events to sync local state.


## Celery Tasks {#celery-tasks}


Managed via `uv run celery`:
- `send_email_task` — Dispatches notifications.
- `post_tenant_creation_task` — Sets up default roles/permissions for new tenants.
- `check_expired_trials` — Runs hourly to manage trial access.


## Migrations {#migrations}


Uses Alembic for database migrations managed by `uv`:

```bash
uv run alembic upgrade head
```
