> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gatojs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication and roles

> How GatoJS configures better-auth for sign-in, sign-up, invitations and password reset, and how global roles and organization roles control access.

GatoJS uses [better-auth](https://www.better-auth.com) for accounts and sessions, with two plugins: `admin` (global roles, banning, impersonation, `/admin/*` endpoints) and `organization` (organizations, members, invitations, `/organization/*` endpoints). Everything lives in your repo, in `src/shared/lib/auth/`.

This page covers the auth flows, the two levels of roles, who can open which page, and the guards that protect your data. It assumes you know the [organization context](https://docs.gatojs.com/concepts/organizations.md#organization-context-getorgcontext). The superadmin, impersonation and service mode have [their own page](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md).

## better-auth setup

There is one better-auth instance: `auth` in `src/shared/lib/auth/index.ts`. The route `src/app/api/auth/[...all]/route.ts` forwards every GET and POST under `/api/auth/*` to it. Browser components call those endpoints through `authClient` from `src/shared/lib/auth/client.ts`.

| Setting | Value | Effect |
| - | - | - |
| `secret` | `BETTER_AUTH_SECRET` | Signs cookies and tokens. At least 32 characters; must differ from `.env.example` in production. |
| `baseURL` | `APP_URL` | Base for links in emails and the only trusted origin by default. |
| `database` | `prismaAdapter(prisma, …)` | Accounts, sessions and tokens live in the same database as your data. |
| `emailAndPassword` | enabled, `autoSignIn: false`, reset token valid 48 h | Email and password sign-in. Sign-up does not create a session. |
| `session.cookieCache` | 5 minutes | Signed session copy in a cookie. [`getOrgContext()` bypasses it](https://docs.gatojs.com/concepts/organizations#session-read-from-the-database-not-the-cookie-cache). |
| `hooks.before` | one function, three branches | See below. |
| `databaseHooks` | `user.create.after`, `session.create.before`, `session.create.after` | Create the membership after sign-up, set the default active organization, record service-mode entry. |
| `admin` plugin | `defaultRole: "user"`, `adminRoles: ["admin", "superadmin"]` | Global role and `/admin/*` permissions. |
| `organization` plugin | `allowUserToCreateOrganization` returns `MULTI_ORG` | Users can create organizations only with `MULTI_ORG=true`. |
| `authPlugins` | from `src/modules.generated.ts` | Plugins contributed by modules' `auth.ts` files. See [Module registry](https://docs.gatojs.com/concepts/module-registry.md). |

The kit doesn't set a session lifetime, so better-auth's defaults apply: a session expires after 7 days and is extended on use once a day.

### The `before` hook

All rules GatoJS adds on top of better-auth sit in one `before` hook. It runs before every better-auth endpoint, including server-side `auth.api.*` calls, and throwing there ends the request before anything is written.

| Branch | Paths | What it checks |
| - | - | - |
| 1 | `/admin/create-user` and account-targeting `/admin/*` paths | Protection of superadmin accounts, granting `superadmin`, impersonation. See [Superadmin](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md#protecting-service-accounts). |
| 2 | Organization management endpoints, only when `MULTI_ORG=false` | Caller has global `admin` or `superadmin`. |
| 3 | `/sign-up/email` | The sign-up gate and which organization the new account joins. |

Every other endpoint passes through unchanged, and better-auth's own rules still apply.

## Flows

### Sign-in

1. `/sign-in` validates the form and calls `authClient.signIn.email`.
2. better-auth checks the password. The `admin` plugin rejects banned accounts (unless `banExpires` has passed).
3. The new session gets an active organization: the oldest membership's organization, or for a superadmin without memberships, the oldest organization in the database.
4. The form always redirects to `/dashboard`. If the account has no organization, the `(app)` layout sends it on to `/no-organization`.

### Sign-up

Sign-up is gated on the server, because `POST /api/auth/sign-up/email` is a public endpoint anyone can call directly. With `AUTH_PUBLIC_SIGNUP=false`, the `/sign-up` page redirects to `/sign-in` unless the URL carries an `invitationId`, but that's only a convenience. The hook decides who can create an account.

```mermaid theme={null}
sequenceDiagram
    autonumber
    participant F as SignUpForm
    participant H as before hook
    participant E as sign-up/email endpoint
    participant A as user.create.after
    participant D as Postgres

    F->>H: POST /api/auth/sign-up/email
    H->>D: enforce sign-up policy (look for matching invitation)
    H->>H: resolve membership: join or create
    H->>E: context with the decision
    E->>D: transaction: user with role "user" + password hash
    E->>A: after commit
    A->>D: membership (and invitation → accepted)
    E-->>F: success, no session
    F->>F: redirect to /sign-in
```

An invitation matches when its id equals `invitationId`, its email equals the form email (case-insensitive), its status is `pending` and `expiresAt` is in the future.

| Request | `AUTH_PUBLIC_SIGNUP=false` (default) | `AUTH_PUBLIC_SIGNUP=true` |
| - | - | - |
| No `invitationId` | 403, sign-up disabled. | `MULTI_ORG=false`: `member` of the oldest organization (500 if none exists yet). `MULTI_ORG=true`: new organization with the account as `owner`. |
| Matching invitation | Joins the invitation's organization with its role; invitation becomes `accepted`. | Same. |
| `invitationId` without a match | 403, sign-up disabled. | 403, invalid or expired invitation. |

Two things are easy to miss:

* **Existing email.** With `autoSignIn: false`, better-auth doesn't reveal that an email is taken: it creates nothing and responds as if it succeeded. The form shows the success message, no membership is created and the invitation stays `pending`.
* **Global role.** Sign-up always creates a `user`. A `role` field in the request is rejected with 400 because the `admin` plugin marks it `input: false`.

### Two kinds of invitations

| | **Invite user** | **Invite someone** |
| - | - | - |
| Where | Users page (`UsersManager`) | Members page (`OrganizationMembers`) |
| Who sees it | Global `admin` and `superadmin` | Org `owner` and `admin` with global role `user`, only with `MULTI_ORG=true` |
| Code | Kit command `inviteUserCommand`, through `useServiceModeAction().run` | `authClient.organization.inviteMember` (better-auth endpoint) |
| Account | Created immediately. Fails if the email already has an account. | Not created. The recipient signs up or signs in with an existing account. |
| Email | Welcome email with a **Set password** link | Invitation email with a link to `/accept-invitation/<id>` |
| Org role | `member` (default) or `admin` | `member` (default) or `admin` |
| Validity | 48 hours (invitation and password link) | 48 hours (better-auth default) |

**Invite user** creates the invitation in the active organization, registers the account through the same sign-up gate (so the membership and `accepted` status come from the regular flow), marks the email verified and sends the set-password email. If the email fails, the account still exists and the UI tells the admin to ask the user to reset their password.

**`/accept-invitation/<id>`** lives outside the `(app)` group, so it doesn't require an active organization. When the visitor is signed in, the page accepts the invitation on open and sets it as the active organization. Signed-out visitors see **Sign in** and **Create account**:

* **Create account** opens `/sign-up?invitationId=<id>`; signing up with the invited email joins the organization immediately.
* **Sign in** goes to plain `/sign-in`, which then redirects to `/dashboard` without accepting the invitation. After signing in, open the email link again.

### Passwords: set, reset and change

Setting a password after **Invite user** and resetting a forgotten password use the same better-auth mechanism: a single-use token in the `verifications` table, valid for 48 hours.

| Flow | Starts from | Form page | After saving |
| - | - | - | - |
| Set password | **Invite user** welcome email | `/set-password` | `/sign-in` |
| Reset password | **Forgot password?** on `/sign-in` → `/forgot-password` | `/reset-password` | `/sign-in` |

* The form requires at least 8 characters and a confirmation. An expired or missing token shows a "link expired" message with a link to request a new one.
* `/forgot-password` shows the same message whether or not the account exists, so it doesn't reveal which emails are registered. Email only goes to existing accounts.
* A reset doesn't sign out other sessions (`revokeSessionsOnPasswordReset` isn't enabled).

Changing a password happens on `/account` through `changePasswordCommand`, which keeps other sessions signed in (`revokeOtherSessions: false`).

## Two levels of roles

GatoJS has two independent role systems, because a client app has two kinds of administration: someone manages accounts across the whole app, and within each company someone else manages its members.

| | Global role | Organization role |
| - | - | - |
| Stored in | `users.role` (`admin` plugin) | `members.role` (`organization` plugin) |
| Values | `user`, `admin`, `superadmin` | `owner`, `admin`, `member` |
| Who has it | Every account; default `user` | Every membership; an account has a separate role in each organization |
| Granted by | `npm run admin:create`; `/admin/set-role`, `/admin/create-user`, `/admin/update-user` (no UI in the kit) | Sign-up, both invitation types, `admin:create` (`owner`), creating an organization (`owner`); role changes on the Members page with `MULTI_ORG=true` |
| Affects | Users page, `/admin/*` endpoints, access to every module, the `MULTI_ORG=false` guard, impersonation; for `superadmin` also [service mode](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md#service-mode) | `roles` and `multiOrgRoles` in module definitions, better-auth `organization` permissions |

> [!NOTE]
>
> `admin` exists at both levels. Say "global `admin`" or "organization `admin`" to avoid confusion.

Code reads roles through `src/shared/lib/auth/roles.ts`. Unknown values fall back to the lowest role, so a typo in the database never grants permissions:

```ts src/shared/lib/auth/roles.ts theme={null}
export function toUserRole(role: unknown): UserRole {
  return USER_ROLE_VALUES.includes(role) ? (role as UserRole) : USER_ROLES.USER;
}

export function isGlobalAdmin(role: unknown): boolean {
  return role === USER_ROLES.ADMIN || role === USER_ROLES.SUPERADMIN;
}
```

`toOrgRole` does the same for organization roles and falls back to `member`.

> [accordion] Multi-value roles such as admin,superadmin
>
> better-auth's `/admin/set-role` accepts an array of roles and stores it as a comma-separated string. The kit's UI never does this, but if such a value ends up in `users.role`, two readers disagree: `toUserRole` and `isGlobalAdmin` compare the whole string and treat it as `user`, while the `before` hook and `admin:create` use `roleFromStored`, which picks the highest role in the list. An `admin,superadmin` account is therefore protected like a superadmin but behaves like a regular user in the app and gets no service mode. Avoid multi-value roles.

## Access matrix

Page access and menu entries are decided by `canAccessModule(definition, { userRole, orgRole, multiOrg })` in `src/shared/lib/auth/permissions.ts`. Both `requireModuleAccess` (pages) and the sidebar navigation call it, so the menu shows exactly what you can open.

```ts src/shared/lib/auth/permissions.ts theme={null}
export function canAccessModule(moduleDef: ModuleDef, context: AccessContext): boolean {
  if (isGlobalAdmin(context.userRole) || moduleDef.public) {
    return true;
  }
  const { orgRole } = context;
  if (orgRole === null) {
    return false;
  }
  if (moduleDef.adminOnly) {
    return context.multiOrg && (moduleDef.multiOrgRoles ?? []).includes(orgRole);
  }
  return !moduleDef.roles || moduleDef.roles.includes(orgRole);
}
```

In short: global `admin` and `superadmin` can open every module; `public` modules are open to everyone; an `adminOnly` module opens for organization roles only with `MULTI_ORG=true` and only for roles listed in `multiOrgRoles`; otherwise the module's `roles` list applies (no list means every org role). See [Module registry](https://docs.gatojs.com/concepts/module-registry.md) for the fields.

The table below covers the core modules. It's backed by `src/shared/lib/auth/__tests__/access-matrix.test.ts`, which pins all 120 combinations.

| Module | Global role | `owner` | `admin` | `member` | No membership |
| - | - | - | - | - | - |
| `dashboard`, `account` | `user` | yes | yes | yes | `/no-organization` |
| `dashboard`, `account` | `admin`, `superadmin` | yes | yes | yes | yes¹ |
| `users`, `MULTI_ORG=false` | `user` | 404 | 404 | 404 | `/no-organization` |
| `users`, `MULTI_ORG=true` | `user` | yes | yes | 404 | `/no-organization` |
| `users` | `admin`, `superadmin` | yes | yes | yes | yes¹ |
| `auth`, `organizations` (public) | any | yes | yes | yes | yes |

¹ The global role grants access to the definition, but `getOrgContext()` throws `NoOrganizationError` first, so a global `admin` without membership lands on `/no-organization`. The exception is a superadmin in an existing organization: they get `orgRole: "owner"` in service mode.

The same `/users` page renders different views: global `admin` and `superadmin` get the list of all accounts (**Users**), while org `owner` / `admin` with global role `user` get the active organization's **Members**.

## Guards

Every place the browser can reach checks permissions itself. The layout protects neither pages nor server actions.

| Guard | File | Used in | On denial | Session source |
| - | - | - | - | - |
| `getOrgContext()` | `org-context.ts` | Layout, pages, queries, commands | Redirect to `/sign-in` or `NoOrganizationError` | Database |
| `requireModuleAccess(key)` | `require-module-access.ts` | `page.tsx` files, commands | `/sign-in`, `/no-organization` or 404 | Database (via `getOrgContext`) |
| `canAccessModule` | `permissions.ts` | `requireModuleAccess`, navigation | `false` | — |
| `requireUser`, `getAdminUserOrNull` | `helpers.ts` | Global-admin operations | `/sign-in`, then `null` | Cookie cache |
| `before` hook, `/admin/*` branch | `admin-guard.ts`, `admin-access.ts` | `admin` plugin endpoints | 403 | Database |
| `before` hook, single-org branch | `single-org-guard.ts` | Organization management endpoints | 403 | Cookie cache |
| Sign-up policy | `signup-gate.ts`, `signup-policy.ts` | `/sign-up/email` | 403 | — |
| `assertServiceModeConfirmed` | `service-mode.ts` | Commands on organization data | Error result | — |
| `canEnterOrganization` | `organization-access.ts` | `enterOrganizationCommand` | Error result | Database |

Guard files live in `src/shared/lib/auth/`, except the sign-up policy (`src/features/auth/services/`) and `organization-access.ts` (`src/features/organizations/services/`).

> [!WARNING]
>
> Helpers in `helpers.ts` read the global role from the 5-minute cookie cache. An account whose `admin` role was just revoked can still pass `getAdminUserOrNull()` until the cookie expires. For new role-based rules, read `context.userRole` or `context.orgRole` from `getOrgContext()` / `requireModuleAccess()`, which come from the database.

## Creating the first admin: `npm run admin:create`

The first account comes from a script, not a page, because with sign-up closed by default someone has to create an account and an organization before anyone can sign in. Run it from the project root:

```bash theme={null}
npm run admin:create -- --email you@example.com
```

| Option | Env variable | Meaning |
| - | - | - |
| `--email` | `ADMIN_EMAIL` | Account email. Required (one of the two). |
| `--password` | `ADMIN_PASSWORD` | Password for a **new** account. Without one (or with an empty value), a 20-character password is generated and printed once. |
| `--name` | — | Name for a new account. Defaults to the part of the email before `@`. |
| `--org-name` | — | Organization name, used only on an empty database. Defaults to `project.name` from `src/shared/config/project.ts`. |
| `--role` | — | `admin` (default) or `superadmin`. |
| `--yes` | — | Raise an existing account's role without asking. |

What it does:

1. Creates the account with the chosen role and a verified email, or, for an existing account, keeps its password and name and raises its role only after confirmation (or `--yes`). It never lowers a role.
2. On an empty database, creates an organization and makes the account its `owner`. Otherwise it adds an `owner` membership in the **oldest** organization, unless the account is already a member there.

The script is idempotent: running it again with the same options creates no second account, organization or membership and doesn't change the password. To recover a forgotten password, use **Forgot password?** on the sign-in page.

> [!TIP]
>
> To create a [superadmin](https://docs.gatojs.com/concepts/superadmin-and-service-mode.md) service account, pass `--role superadmin`. The script can do this because it calls `auth.api.createUser` from the server without request headers, which the `before` hook and the `admin` plugin's permission check skip.

## Environment variables

| Variable | Default | Effect |
| - | - | - |
| `BETTER_AUTH_SECRET` | — | Signing secret. At least 32 characters. |
| `APP_URL` | — | Full `http(s)` URL. Used in email links and as the trusted origin. |
| `AUTH_PUBLIC_SIGNUP` | `false` | `true` allows sign-up without an invitation. |
| `MULTI_ORG` | `false` | See [`MULTI_ORG` modes](https://docs.gatojs.com/concepts/organizations#multi_org-modes). |
| `ADMIN_IMPERSONATION` | `false` | `true` lets global `admin` impersonate `user` accounts. |
| `ADMIN_EMAIL`, `ADMIN_PASSWORD` | — | Defaults for `admin:create`. |

Flags accept only `true` or `false`; missing or empty means `false`. Full list: [Environment variables](https://docs.gatojs.com/configuration/environment-variables.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.