# Users and app roles
Source: https://sovaria.in/docs/users-and-roles

See, add, invite, ban and delete your app’s users, give them app roles your rules check, manage them from your server, and test your rules as one of them.

Your app’s users live in the project, separate from your team’s console accounts and from other projects. This page covers seeing and managing them, giving them **app roles** that your rules check, and testing as one of them.

## The Users page

The **Users** page lists your app users with their sign-in method, last sign-in and status. Open a user to assign roles, reset their MFA, ban or unban them, delete them, or start a test session.

## Add and invite users

Most users sign themselves up. To add someone yourself, use **Invite user**: give an email and a name, and either email them a magic link to get in (they choose how to sign in later) or set a password and mark the email as confirmed. From your server, the same is one request:

cURL:
```bash
curl -X POST "https://<project-ref>.sovarias.in/api/v1/auth/product-users" \
  -H "Authorization: Bearer $SOVARIA_SERVICE_ROLE_KEY" -H "Content-Type: application/json" \
  -d '{"name": "Ada Lovelace", "email": "ada@example.com",
       "roles": ["EDITOR"], "send_magic_link": true}'
```

| Field | Meaning |
|---|---|
| `name`, `email` | Required. |
| `password` | Optional, at least 8 characters. Leave it out to have the user sign in by magic link or a provider. |
| `roles` | App roles to give them straight away. |
| `send_magic_link` | Email them a sign-in link now (the `invite_user` email). |
| `email_confirm` | Mark the email as confirmed, skipping the confirmation email. |
| `temporary_password` | `true`: the server makes a strong password, returns it once in the reply (`temporary_password`, not cached, never logged) and the user must change it at first sign-in. Not with `password` or `send_magic_link`. |

### Users for your roles, with temporary passwords

**Add users for roles** (on the Users page, next to Invite user) lists your app roles: type one or more email addresses for each. Every account is made with a temporary password that is shown to you once, with a copy button and a CSV download, and the person must choose their own at first sign-in (until then the server answers `403 PASSWORD_CHANGE_REQUIRED` to everything else). The same form appears after a template's **Set up backend** and in Sovariq's **First users** card, which it shows when it creates an app's roles. Sovariq only learns who was created, never a password.

## App roles

> **When a role change takes effect:** A role you give or take applies to the user's requests at once — at most 20 seconds later — even with the token they already hold (whose `app_roles` claim is from sign-in): every request is checked against the user's current roles. Open realtime connections re-check within about 15 seconds. Changing roles also signs the user out everywhere, so their next token lists the new roles too.

App roles are labels you define for your product, such as `STAFF`, `EDITOR` or `SUPPORT`. Define them under **Users › Roles**, assign them to users on the Users page or through the API, then check them in your rules. They are separate from your team’s console roles.

SQL (row-level security):
```sql
create policy "editors update articles" on articles
  for update to authenticated
  using (auth.has_role('EDITOR'))
  with check (auth.has_role('EDITOR'));
```

Policy (SPL):
```bash
# One statement per policy. Staff may change the catalogue; everyone signed in may read it:
ALLOW IF "STAFF" IN ctx.actor.roles OR (ctx.actor.is_anonymous == False AND ctx.action == "SELECT")
```

cURL (assign):
```bash
# Replace the user's app roles
curl -X PUT "https://<project-ref>.sovarias.in/api/v1/auth/product-users/<user-id>/roles" \
  -H "Authorization: Bearer $SOVARIA_SERVICE_ROLE_KEY" -H "Content-Type: application/json" \
  -d '{"roles": ["EDITOR", "SUPPORT"]}'
```

### What each role may use

Open a role under **Users › Roles** to tick what it may do on each table, collection and function, then **Save changes** (nothing applies until you save). The section headers have quick picks (None, Read only, Read & write, Everything) and a box per column that ticks it for every item; the box at the start of a row ticks everything on that item. Sovaria turns the grid into access rules and refuses the save if they can’t be applied, so what you see is what is enforced.

| Resource | Actions |
|---|---|
| Tables | **Read** (select), **Create** (insert), **Update**, **Delete**: each one separately |
| Collections | **Read** (get and query), **Write** (create and change documents), **Delete** |
| Functions | **Call**: once any role is given a function, only those roles (and your team and server keys) may call it; other signed-in users get `403 FUNCTION_ROLE_REQUIRED` |

A role grants access; it never takes away what your other rules or row-level security allow. Delete a role from its row menu (⋯ or right-click): users who have it lose that access at once. Your plan sets how many custom roles a project may have (`auth.app_roles`); the four built-in roles (admin, editor, viewer, service) don’t count and can be deleted too. Only project owners and admins can change roles.

Roles travel in the user’s access token (`app_roles`), so a change takes effect when their token is next refreshed, at most one access-token lifetime later, or straight away if they sign in again ([Sessions and tokens](https://sovaria.in/docs/sessions-and-tokens)).

### Define and assign roles from code

The TypeScript and Python SDKs have a `roles` module over the same routes. Defining roles and assigning them is for the project team (a console session, or the service key on a server). `current()` and `has()` read the signed-in user's roles from their own token, for showing the right screens; the server still decides every call. To let your app's own admins re-role users with their own sign-in, use [Let your app's admins manage users (auth.users)](https://sovaria.in/docs/app-user-admins).

TypeScript:
```ts
// Project team or server (service key)
await sovaria.roles.create('MANAGER', ['read', 'write'])   // 409 ROLE_EXISTS if the name is taken
await sovaria.roles.update('MANAGER', ['read', 'write', 'delete'])
const roles = await sovaria.roles.list()                  // [{ name, permissions, builtIn }]
const { roles_used, roles_limit } = await sovaria.roles.status()

await sovaria.roles.assign(userId, 'MANAGER')             // keeps the roles they already have
await sovaria.roles.revoke(userId, 'REP')
await sovaria.roles.of(userId)                            // ['MANAGER']

// In your app, as the signed-in user (from their token; refresh to see a change)
if (sovaria.roles.has('manager')) showApprovals()
```

Python:
```python
await sovaria.roles.create("MANAGER", ["read", "write"])
await sovaria.roles.assign(user_id, "MANAGER")
await sovaria.roles.revoke(user_id, "REP")
print(await sovaria.roles.of(user_id))

sovaria.roles.current()          # the signed-in user's roles, from their token
sovaria.roles.has("manager")     # case-insensitive
```

CLI:
```bash
sov auth-product roles <user-id>
sov auth-product roles-add <user-id> MANAGER
sov auth-product roles-remove <user-id> REP
```

A new role counts toward your plan's `auth.app_roles`. Deleting a role takes it from everyone who had it, and row rules that test it then refuse them. The routes accept either id the API gives you for a user: the one `create` returned or the user's id in the users list.

## Manage users from your server

These are the routes the console uses. Call them from a server with the service role key, or as a project owner or admin; never from an app your users run ([Keys, tokens and credentials](https://sovaria.in/docs/credentials)).

| Action | Request |
|---|---|
| List users | `GET /api/v1/auth/product-users` |
| Create or invite a user | `POST /api/v1/auth/product-users` |
| Delete a user (everything about them: profile, roles, MFA, passkeys, consents) | `DELETE /api/v1/auth/product-users/{user_id}` |
| Ban or unban (toggles) | `POST /api/v1/auth/product-users/{user_id}/ban` |
| Read or replace app roles | `GET` / `PUT /api/v1/auth/product-users/{user_id}/roles` |
| Read or replace the role access grid (roles left out are deleted) | `GET` / `PUT /api/v1/roles/matrix` |
| Whether the saved grid is enforced, and your role allowance | `GET /api/v1/roles/matrix/status` |
| MFA status, reset MFA | `GET …/{user_id}/mfa`, `POST …/{user_id}/mfa/reset` |
| Test session | `POST …/{user_id}/test-session` |

Every request is scoped to the project you call (your project URL or `X-Sovaria-Project-ID`); a user from another project answers `404`. The full parameters are in the [HTTP API reference](https://sovaria.in/docs/rest-auth-admin).

## Test as a user

**Test session** on a user gives project owners and admins a short-lived access token for that user (15 minutes by default, up to 60), so you can run queries exactly as they would and check your rules. It is recorded in the audit log, works only for app users, never for console members, and can’t be refreshed.

## Ban and delete

- Banning signs the user out everywhere and blocks sign-in, magic links and password resets until you unban them. Their data stays.
- Deleting removes the account and its sessions. Rows they own in your tables stay until you delete them; use foreign keys with `on delete cascade` if they should go too.
- If a user lost their phone and backup codes, **Reset MFA** removes their second factors so they can sign in and enrol again. Check who they are first.
