Skip to main content

Crate fastauth_plugin_admin

Crate fastauth_plugin_admin 

Source
Expand description

The admin plugin for fastauth: roles and statement-based permissions, bans, impersonation and user management. The routes and JSON match Better Auth’s admin plugin, so its adminClient works unchanged.

use fastauth_core::prelude::*;
use fastauth_plugin_admin::{Admin, AdminExt, Permissions};

let auth: Auth<MemoryAdapter, (), plugins![Admin]> = FastAuth::builder()
    .secret(Secret::from_bytes(vec![1u8; 32]))
    .base_url("http://localhost:3000")
    .database(MemoryAdapter::new())
    .email_password(EmailPassword::default())
    .plugin(
        Admin::new()
            .role("support", Permissions::new().allow("user", ["list", "get"]))
            .impersonation_session_duration(Duration::minutes(30)),
    )
    .build()?;
let _admin = auth.admin();

It adds role, banned, ban_reason and ban_expires to user and impersonated_by to session, none of them client-settable, and serves /admin/create-user, list-users, get-user, set-role, ban-user, unban-user, update-user, set-user-password, remove-user, list-user-sessions, revoke-user-session, revoke-user-sessions, impersonate-user, stop-impersonating and has-permission. Each checks the caller’s roles against the action it performs and answers 403 with Better Auth’s code when they don’t allow it; auth.admin() runs the same operations from server code without a session.

A sign-in gate refuses banned users with 403 BANNED_USER for every sign-in method, and lifts expired bans. A session gate refuses them the same way on every request, whatever the session came from (cookie, cookie cache, bearer token, API key), and refuses impersonation sessions in endpoints that create credentials (403 NOT_ALLOWED_WHILE_IMPERSONATING). Admins without user:impersonate-admins can’t act on another admin’s account (403 YOU_CANNOT_MANAGE_ADMINS).

With the axum feature, RequireRole guards your own routes by role.

Modules§

role
The built-in roles, plus role! for your own.

Macros§

role
Declares a role marker for RequireRole:

Structs§

Admin
The admin plugin: .plugin(Admin::new()).
AdminApi
Runs admin operations from server code. Calls are trusted: they need no session and skip the permission checks, but run the same hooks and events as the HTTP routes. Impersonation acts for a signed-in admin, so it takes the request’s headers.
AdminSession
The column admin adds to session: who is impersonating through it.
AdminUser
The columns admin adds to user. None of them is client-settable; only admin endpoints and the server API change them. Apps read them with session.user.plugin::<Admin, _>().
BanUser
POST /admin/ban-user: needs user:ban. Revokes every session of the user.
BanUserInput
Body of /admin/ban-user.
CreateUser
POST /admin/create-user: needs user:create, plus user:set-role to pick a role and user:ban to set ban columns.
CreateUserInput
Body of /admin/create-user.
GetUser
GET /admin/get-user?id=..: needs user:get. Answers the user itself, unwrapped.
GetUserQuery
Query of /admin/get-user.
HasPermission
POST /admin/has-permission: whether the signed-in user (any user, not only admins) may do everything in permissions.
HasPermissionInput
Body of /admin/has-permission. Over HTTP the caller’s session decides; server calls name a user or a role.
ImpersonateUser
POST /admin/impersonate-user: needs user:impersonate, plus user:impersonate-admins when the target is an admin. Signs the browser in as the user with a short session marked impersonatedBy, and keeps the admin’s session token in a signed {prefix}.admin_session cookie for stop-impersonating. Impersonation sessions can’t impersonate, and banned users can’t be impersonated.
ListUserSessions
POST /admin/list-user-sessions: needs session:list. The user’s unexpired sessions.
ListUsers
GET /admin/list-users: needs user:list. Search, filters, sorting and paging all run in the database; total counts every match.
ListUsersQuery
Query of /admin/list-users.
PermissionOutput
{ "error": null, "success": true }.
Permissions
Actions per resource: { "user": ["list", "ban"] }. A role’s grants, or the actions a permission check asks for.
RemoveUser
POST /admin/remove-user: needs user:delete. Deletes the user’s sessions and accounts, then the user, and emits SessionRevoked (when they had sessions) and UserDeleted.
RequireRole
The signed-in session of a user who holds role R. Rejects with 401 UNAUTHORIZED without a session and 403 FORBIDDEN without the role. A user holds every role in their comma-separated user.role (the default role while it is empty); admins hold every configured admin role, so RequireRole<A, role::Admin> also lets admin_user_ids in.
RevokeUserSession
POST /admin/revoke-user-session: needs session:revoke. Succeeds when no session with that token is left, even if there never was one.
RevokeUserSessionInput
Body of /admin/revoke-user-session.
RevokeUserSessions
POST /admin/revoke-user-sessions: needs session:revoke.
SessionList
{ "sessions": [..] }.
SessionOutput
{ "session": {..}, "user": {..} }.
SetRole
POST /admin/set-role: needs user:set-role. Every role must be defined.
SetRoleInput
Body of /admin/set-role.
SetUserPassword
POST /admin/set-user-password: needs user:set-password. Checks the password policy, creates the credential account when the user has none, and emits PasswordChanged.
SetUserPasswordInput
Body of /admin/set-user-password.
StopImpersonating
POST /admin/stop-impersonating: ends the impersonation session and signs the browser back in as the admin from the admin_session cookie.
Success
{ "success": true }.
UnbanUser
POST /admin/unban-user: needs user:ban.
UpdateUser
POST /admin/update-user: needs user:update, plus user:set-role for role, user:ban for the ban columns and user:set-email for email and emailVerified. Answers the user itself, unwrapped. Setting banned: true revokes the user’s sessions.
UpdateUserInput
Body of /admin/update-user.
UserIdInput
Body of the endpoints that name one user.
UserList
{ "users": [..], "total": 42, "limit": 10, "offset": 0 }. total counts every match.
UserOutput
{ "user": {..} }.

Enums§

AdminError
Why an admin request failed. Codes, statuses and messages match Better Auth’s admin plugin; USER_NOT_FOUND, INVALID_EMAIL and USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL come from core.
Roles
One role or several: "admin" or ["admin", "support"]. Stored comma-separated.
SearchField
Which column searchValue matches.
SearchOperator
How searchValue matches. Case-sensitive.
SortDirection
asc or desc.
WhereOperator
How filterValue compares with filterField. in and not_in take a comma-separated list; the text operators are case-sensitive.

Constants§

STATEMENTS
Every resource and action the admin endpoints check, as Better Auth defines them.

Traits§

AdminExt
auth.admin(): the server API. Only compiles on an Auth with Admin registered.
Role
A role a route can require, named as it is stored in user.role. Implement it with role!.