# Authentication & roles

> Add 19+ sign-in providers and server-enforced user roles so every screen, API route, and database query checks who is asking.

- Canonical: https://exaspark.ai/docs/authentication-and-roles/

## Authentication vs authorization

Building secure user accounts requires two distinct layers working together. Treating them as one feature is the single most common source of data leaks in production web apps.

**Authentication** answers *who are you?* It verifies identity through a password, one-time magic link, or third-party provider such as Google or Apple, then issues a signed session tied to that account.

**Authorization** answers *what are you allowed to do?* Even after a customer signs in, your server must check their **role** (Member, Staff, Admin) and **ownership** (is this their own booking or someone else's?) before returning private rows or running a write action.

*Figure: Configure 19+ sign-in providers, inspect user accounts and roles, and verify isolated Preview vs Live sessions inside the Cloud panel.*

## Choosing from 19+ sign-in providers

ExaSpark supports **19+ sign-in providers**, including email and password, passwordless magic links, Google, Apple, GitHub, Microsoft, and over a dozen additional identity providers.

Offering more buttons does not automatically improve conversion. Too many login choices create decision friction and cause returning users to accidentally register duplicate accounts under different providers. Match two or three providers to how your audience already works.

| Audience or app type | Recommended providers | Why it fits | Key UX detail |
| --- | --- | --- | --- |
| **Consumer apps & local services** | Google, Apple, Email + magic link | One-tap mobile sign-in eliminates forgotten passwords | Offer Apple alongside Google for iPhone Safari users |
| **B2B SaaS & team workspaces** | Google Workspace, Microsoft, Email + password | Matches company email policies and enterprise laptops | Support email verification before joining a workspace |
| **Developer tools & technical SaaS** | GitHub, Google, Email + password | Developers expect single-click GitHub identity | Let users link email recovery if GitHub handles change |
| **Low-friction booking or store** | Guest checkout + optional magic link | Removes sign-up walls before the first purchase | Auto-attach past orders by verified email when they sign in later |

### Account linking and email verification

Require email verification before granting sensitive actions — such as posting public reviews, inviting teammates, or viewing billing invoices. Unverified email/password sign-ups let bots register addresses they do not own.

When offering both email/password and OAuth (like Google), ensure ExaSpark links accounts only when the provider returns a verified email address. That keeps one person from hijacking another user's account simply by registering an unverified matching email.

## How sessions and protected routes work

Once a visitor authenticates, your server establishes an encrypted, HTTP-only session cookie in the browser. Every subsequent page load and API request automatically presents that cookie so your backend knows the verified `user.id` and `user.role`.

- **Protected routes redirect cleanly.** If a signed-out visitor opens `/account/bookings`, redirect them to `/login?next=/account/bookings` and return them to their original destination immediately after sign-in.
- **Session expiry and sign-out.** Clicking **Sign out** invalidates the session on the server and clears the cookie. Sensitive changes (updating an email or deleting an account) should re-verify the active session.
- **No sensitive tokens in browser storage.** Keeping session credentials in HTTP-only cookies prevents client-side scripts from reading or stealing active login tokens.

### Why hiding a UI button is never security

A frequent mistake in early prototypes is hiding an **Admin** tab or **Delete** button in the browser UI while leaving the underlying server endpoint unprotected.

Remember that browser code is always public. Anyone can open DevTools, read API paths, and send a direct HTTP request with their own member cookie.

Every private read, write, CSV export, and refund endpoint must verify both the active session and the caller's role **on the server** — returning HTTP `401 Unauthorized` when signed out and `403 Forbidden` when lacking permission.

## Designing role-based access control (RBAC)

Role-based access control groups permissions into clear operational tiers rather than inventing ad-hoc rules on every screen. Most production ExaSpark apps start cleanly with four roles.

| Role | Public catalog | Own profile & records | Other users' records | Schedules & operations | Billing, roles & settings |
| --- | --- | --- | --- | --- | --- |
| **Guest** | Read | None | None | None | None |
| **Member** | Read | Read & update | None | Book / cancel own slots | Manage own subscription |
| **Staff** | Read | Read & update | Read assigned roster | Check-in clients & edit schedule | None |
| **Admin** | Full read & write | Full read & write | Full read & write | Full control | Manage roles, pricing & exports |

### Row-level ownership vs global roles

Role checks alone are not enough for multi-user apps. Two signed-in customers share the exact same `member` role, yet Member A must never read or cancel Member B's order.

Combine **role checks** (for global staff/admin powers) with **row-level ownership checks** (matching `record.user_id === session.user.id`) on every member route. Writing an explicit permission table in your prompt eliminates ambiguity.

```text
ROUTE                          REQUIRED AUTH     SERVER AUTHORIZATION RULE
---------------------------------------------------------------------------------------
GET  /api/classes              Guest allowed     Return public active classes only
POST /api/bookings             Signed-in user    Derive user_id strictly from session
GET  /api/bookings/:id         Signed-in user    booking.user_id == session.user.id OR role IN ('staff','admin')
PATCH /api/bookings/:id/cancel Signed-in user    booking.user_id == session.user.id (24h window) OR role == 'admin'
GET  /api/admin/roster         Staff or Admin    Require role IN ('staff', 'admin')
PATCH /api/admin/users/:id     Admin only        Require role == 'admin'; prevent removing last admin
```

### Promoting the first admin safely

Never put a "Sign up as Admin" checkbox on a public registration form — anyone on the internet could grant themselves full control of your Live database.

Instead, default every new registration strictly to `member` on the server. Promote your own account to `admin` directly inside the **Cloud** tab (or configure an explicit owner allowlist), then let admins invite or upgrade teammates from an admin-only screen.

> **Example prompt (App):** Add Google and email/password sign-in with email verification. Enforce four roles server-side — Guest, Member, Staff, and Admin. Guests browse classes; Members book slots and view or cancel only their own bookings; Staff view the daily check-in roster and mark attendance; Admins manage classes, pricing, CSV exports, and user roles. Default every new sign-up to Member and return 403 on unauthorized API calls.

## Common authorization mistakes to avoid

Before publishing any app that holds private customer data, scan your flows for these four real-world authorization bugs.

- **Trusting client-supplied identity fields.** Never accept `user_id` or `role` from a form submission or JSON body when creating a booking or profile. Always read the caller's ID from the verified server session.
- **Missing ownership checks on detail routes (IDOR).** Securing `/api/bookings` (list view) while forgetting to check ownership on `/api/bookings/:id` lets any signed-in user swap an ID in the URL and read another customer's record.
- **Mass-assignment privilege escalation.** If a profile update endpoint blindly saves every key sent in the request payload, an attacker could submit `{"full_name": "Alex", "role": "admin"}` and elevate themselves. Whitelist strictly editable profile fields (`full_name`, `phone`, `avatar_url`).
- **Leaking private fields in public lists.** A public review or directory endpoint should select only safe display fields (`display_name`, `avatar_url`) — never full user rows containing `email`, `phone`, or `stripe_customer_id`.

## Testing permission boundaries in Preview

Because **Preview** runs an isolated database and separate user accounts from **Live**, you can probe every authorization rule thoroughly without touching real customers.

1. **Create three distinct Preview accounts** — Register `member-a@example.com`, `member-b@example.com`, and one admin account (promoted via **Cloud → Preview**).
2. **Verify happy paths first** — Confirm Guests can browse public pages, Member A can create and view their own booking, and Admin can open the management dashboard.
3. **Test cross-user isolation** — Copy a booking or invoice detail URL created by Member B, paste it into a browser session signed in as Member A, and confirm the server rejects access cleanly with no leaked data.
4. **Probe admin routes as a Member** — While signed in as Member A, navigate directly to `/admin` and try triggering an admin-only export or edit. Confirm both the UI redirect and server `403` enforcement hold firm.

> **Note:** **Authentication emails work out of the box.** Sign-up verification, password resets, and magic links use ExaSpark's managed email service automatically — including up to 100 auth emails/month on Free. See [Branded email & delivery](https://exaspark.ai/docs/branded-email/) to send from your own domain.

## Next steps

- [Database & data modeling](https://exaspark.ai/docs/accounts-and-data/) — Link user IDs cleanly to bookings, orders, and team workspaces.
- [File storage & uploads](https://exaspark.ai/docs/file-storage/) — Tie private PDF and receipt downloads directly to your user roles.
- [Branded email & delivery](https://exaspark.ai/docs/branded-email/) — Send verification links and password resets from your own domain.

## From the blog

- [How sign-in works](https://exaspark.ai/blog/how-sign-in-works/) — Authentication, sessions, and OAuth explained in plain English.
- [User roles and permissions](https://exaspark.ai/blog/user-roles-and-permissions/) — Practical blueprints for member, staff, and admin access rules.
- [App security basics](https://exaspark.ai/blog/app-security-checklist/) — Essential security checks before launching an AI-built web app.
