new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Better Auth · Plugins · all subjects

admin plugin

40 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Revoke All Sessions for User endpoint

POST /admin/revoke-user-sessions revokes all sessions for a user. Parameter: userId (string, required).

Admin plugin installation

To use the Admin plugin, import it from 'better-auth/plugins' and add it to the plugins array in the auth config. Then run 'npx auth migrate' or 'npx auth generate' to add the necessary schema fields and tables to the database.

Admin client plugin installation

Add the adminClient plugin from 'better-auth/client/plugins' to the plugins array in the createAuthClient configuration.

Creating the first admin user

After adding the Admin plugin and applying the schema, run 'npx auth@latest create-admin --email admin@example.com --name "Admin" --role admin' to create the first admin user. Use --force or --yes to skip confirmation if users already exist. Use --no-email-verified to disable automatic email verification marking.

Admin user requirements

An admin is any user assigned the 'admin' role or any user whose ID is included in the adminUserIds option. Before performing any admin operations, the user must be authenticated with an admin account.

Create User endpoint

POST /admin/create-user allows an admin to create a new user. Parameters: email (string, required), password (string, required), name (string, required), role (string | string[], optional, defaults to 'user'), data (Record<string, any>, optional for custom fields).

List Users endpoint

GET /admin/list-users allows an admin to list all users. Optional parameters: searchValue (string), searchField ('email' | 'name', defaults to 'email'), searchOperator ('contains' | 'starts_with' | 'ends_with'), limit (number, defaults to 100), offset (number), sortBy (string), sortDirection ('asc' | 'desc'), filterField (string), filterValue (string | number | boolean | string[] | number[]), filterOperator ('eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'in' | 'not_in' | 'contains' | 'starts_with' | 'ends_with'). Returns object with users array, total count, limit, and offset.

List Users pagination response

The listUsers endpoint returns an object containing: users (User[] array of returned users), total (number, total users after filters/search), limit (number | undefined, limit from query), offset (number | undefined, offset from query). Total pages = Math.ceil(total / limit). Current page = (offset / limit) + 1. Next page offset = Math.min(offset + limit, (total - 1)). Previous page offset = Math.max(0, offset - limit).

Get User endpoint

GET /admin/get-user fetches a user's information. Parameter: id (string, required). Returns object with data (User | null) and error (null or object with message, status, statusText, code).

Set User Role endpoint

POST /admin/set-role changes a user's role. Parameters: userId (string, optional), role (string | string[], required).

Set User Password endpoint

POST /admin/set-user-password sets the password for a user. If the user doesn't already have a credential account, one is created. Parameters: newPassword (string, required), userId (string, required).

Update User endpoint

POST /admin/update-user updates a user's details. Parameters: userId (string, required), data (Record<string, any>, required, contains fields to update).

Ban User endpoint

POST /admin/ban-user bans a user, preventing sign-in and revoking all existing sessions. Parameters: userId (string, required), banReason (string, optional), banExpiresIn (number, optional, in seconds, defaults to never expire).

Unban User endpoint

POST /admin/unban-user removes a ban from a user. Parameter: userId (string, required).

List User Sessions endpoint

POST /admin/list-user-sessions lists all sessions for a user. Parameter: userId (string, required).

Revoke User Session endpoint

POST /admin/revoke-user-session revokes a specific session. Parameter: sessionToken (string, required).

Impersonate User endpoint

POST /admin/impersonate-user allows an admin to create a session mimicking the specified user. Parameter: userId (string, required). The session remains active until browser session ends or 1 hour passes. Duration can be changed with impersonationSessionDuration option. By default, admins cannot impersonate other admins unless granted 'impersonate-admins' permission.

Stop Impersonating endpoint

POST /admin/stop-impersonating allows an admin to stop impersonating a user and return to their own admin account. No parameters required.

Remove User endpoint

POST /admin/remove-user hard deletes a user from the database. Parameter: userId (string, required).

Default admin roles

By default, there are two roles: 'admin' (users with full control over other users) and 'user' (users with no control over other users). A user can have multiple roles, stored as comma-separated strings.

Default admin permissions

Default resources and permissions: 'user' resource has actions 'create', 'list', 'set-role', 'ban', 'impersonate', 'impersonate-admins', 'delete', 'set-password', 'set-email', 'get', 'update'. 'session' resource has actions 'list', 'revoke', 'delete'. Admin role has full control over all resources and actions. User role has no control over any actions.

Creating custom access control

Import createAccessControl from 'better-auth/plugins/access'. Define a statement object with resource names as keys and arrays of action strings as values using 'as const'. Call createAccessControl(statement) to create the access controller. Use 'better-auth/plugins/access' instead of 'better-auth/plugins' to keep bundle sizes small.

Creating custom roles

Call ac.newRole() with an object mapping resource names to arrays of allowed actions. To add existing permissions when creating custom roles, import defaultStatements and adminAc from 'better-auth/plugins/admin/access' and merge them with your new statement and role permissions.

Passing custom roles to plugins

Pass the access controller (ac) and roles object to both the server admin plugin and the adminClient plugin. On server: admin({ ac, roles: { admin, user, customRole } }). On client: adminClient({ ac, roles: { admin, user, customRole } }).

Impersonating admin users

By default, admins cannot impersonate other admin users. To allow this, define a custom role with 'impersonate-admins' permission: const superAdmin = ac.newRole({ ...adminAc.statements, user: ['impersonate-admins', ...adminAc.statements.user] }). The legacy allowImpersonatingAdmins option is deprecated.

Has Permission endpoint

POST /admin/has-permission checks a user's permissions. Parameters: userId (string, optional), role (string, optional, server-only), permission (Record<string, string[]>, optional, single permission check), permissions (Record<string, string[]>, optional, multiple permissions check). Either permission or permissions must be provided.

Client-side permission checking

Use authClient.admin.hasPermission({ permissions: { resource: ['action'] } }) to check if current user has permissions. Can check multiple resource permissions simultaneously. Returns promise with permission check result.

Server-side permission checking

Use auth.api.userHasPermission({ body: { userId: 'id', permissions: { resource: ['action'] } } }) or pass role instead of userId. Can check multiple resource permissions at once.

Check Role Permission client method

authClient.admin.checkRolePermission({ permissions: { resource: ['action'] }, role: 'admin' }) verifies if a given role has specific permissions. This function checks role permissions without contacting server, is synchronous (no await needed), and does not check current user's permissions directly.

Admin user table schema fields

The admin plugin adds four fields to the user table: role (string, optional, defaults to 'user'), banned (boolean, optional), banReason (string, optional), banExpires (date, optional).

Admin session table schema field

The admin plugin adds one field to the session table: impersonatedBy (string, optional, ID of admin impersonating this session).

Email enumeration protection with admin plugin

If using requireEmailVerification or autoSignIn: false, configure customSyntheticUser to include admin plugin fields in the fake sign-up response. Include role, banned, banReason, and banExpires fields in the returned object.

Admin plugin defaultRole option

The defaultRole option specifies the default role for a new user. Defaults to 'user'. Configure with admin({ defaultRole: 'regular' }).

Admin plugin adminRoles option

The adminRoles option specifies which roles are considered admin roles. Defaults to ['admin']. Custom roles must be defined in custom access control. When not using custom access control, only 'admin' and 'user' are valid roles; roles not in adminRoles list cannot perform admin operations.

Admin plugin adminUserIds option

Pass an array of userIds to adminUserIds option that should be considered as admins. Defaults to empty array. Users in this list can perform any admin operation.

Admin plugin impersonationSessionDuration option

The impersonationSessionDuration option sets the duration of impersonation sessions in seconds. Defaults to 1 hour (3600 seconds). Configure with admin({ impersonationSessionDuration: 60 * 60 * 24 }).

Admin plugin defaultBanReason option

The defaultBanReason option sets the default ban reason for users banned by admin. Defaults to 'No reason'. Configure with admin({ defaultBanReason: 'Spamming' }).

Admin plugin defaultBanExpiresIn option

The defaultBanExpiresIn option sets the default ban duration in seconds when admin bans a user. Defaults to undefined (ban never expires). Configure with admin({ defaultBanExpiresIn: 60 * 60 * 24 }).

Admin plugin bannedUserMessage option

The bannedUserMessage option sets the message shown when a banned user tries to sign in. Defaults to 'You have been banned from this application. Please contact support if you believe this is an error.' Configure with admin({ bannedUserMessage: 'Custom banned user message' }).

Admin plugin for user management

Better Auth includes an Admin plugin that provides administrative functions for user management.

Give your agent this brain