# Authentication & Authorization

Turista uses a stateless token architecture built on Laravel Sanctum. Roles and permissions are managed by Spatie Laravel Permission.

## Authentication flow

1. **Registration.** A user creates an account as an owner or customer. The system creates a `User` record plus the matching profile (`Owner` or `Customer`) and sends an OTP.
2. **Verification.** The user submits the OTP. On success, `is_verified` is set to `true`.
3. **Login.** The user sends email/phone and password. If credentials are valid and the account is verified, a Sanctum personal access token is returned.
4. **Authenticated requests.** The client sends `Authorization: Bearer {token}` on subsequent requests.
5. **Logout.** The current token is deleted.

## Sanctum configuration

- Default guard: `api`
- Token expiration: 1 week (`60 * 24 * 7` minutes in `config/sanctum.php`)
- Stateful domains are read from `SANCTUM_STATEFUL_DOMAINS`.

## Roles

`RolesAndPermissionsSeeder` creates the following roles against the `api` guard:

- `super_admin`
- `admin`
- `owner`
- `employee`
- `customer`

## Permissions

Key permissions include:

- `manage_platform`
- `approve_buildings`
- `manage_employees`
- `manage_buildings`
- `manage_units`
- `view_reservations`
- `manage_reservations`
- `manage_customers`
- `apply_promo_codes`

Roles map to permissions in the seeder. Controllers and routes use role middleware (`role:owner`, `role:owner|employee`, etc.) for coarse access and policies for fine-grained authorization.

## Middleware

| Middleware | Alias | Purpose |
|------------|-------|---------|
| `EnsureUserIsVerified` | `verified` | Returns `403` if the authenticated user is not verified. |
| Spatie `RoleMiddleware` | `role` | Restricts routes by role. |
| Spatie `PermissionMiddleware` | `permission` | Restricts routes by permission. |
| Spatie `RoleOrPermissionMiddleware` | `role_or_permission` | Restricts by role or permission. |

## Super-admin bypass

`AppServiceProvider` registers a `Gate::before` callback that grants `super_admin` users access to every policy check. This is the only role that bypasses policies.

## Verified accounts

Several routes use both `auth:api` and `verified` middleware. Unverified users can register, verify OTP, and resend OTP, but cannot access protected resources.

## Owner approval

Owners have an additional `status` field (`pending`, `active`, `suspended`) and an `is_verified` flag on the `Owner` model. Admin users can verify owners via `POST /api/v1/owners/{owner}/verify`. Many owner actions require the owner to be approved (`status = active`).

## Employees

Employees belong to an `Owner` and optionally to a `Building`. Their `status` can be `active` or `suspended`. Active employees can perform owner-delegated actions such as managing reservations.
