Skip to main content

fastauth_plugin_admin/
lib.rs

1//! The admin plugin for [fastauth](https://github.com/lassejlv/fastauth): roles and
2//! statement-based permissions, bans, impersonation and user management. The routes and
3//! JSON match Better Auth's admin plugin, so its `adminClient` works unchanged.
4//!
5//! ```
6//! use fastauth_core::prelude::*;
7//! use fastauth_plugin_admin::{Admin, AdminExt, Permissions};
8//!
9//! let auth: Auth<MemoryAdapter, (), plugins![Admin]> = FastAuth::builder()
10//!     .secret(Secret::from_bytes(vec![1u8; 32]))
11//!     .base_url("http://localhost:3000")
12//!     .database(MemoryAdapter::new())
13//!     .email_password(EmailPassword::default())
14//!     .plugin(
15//!         Admin::new()
16//!             .role("support", Permissions::new().allow("user", ["list", "get"]))
17//!             .impersonation_session_duration(Duration::minutes(30)),
18//!     )
19//!     .build()?;
20//! let _admin = auth.admin();
21//! # Ok::<(), BuildError>(())
22//! ```
23//!
24//! It adds `role`, `banned`, `ban_reason` and `ban_expires` to `user` and
25//! `impersonated_by` to `session`, none of them client-settable, and serves
26//! `/admin/create-user`, `list-users`, `get-user`, `set-role`, `ban-user`, `unban-user`,
27//! `update-user`, `set-user-password`, `remove-user`, `list-user-sessions`,
28//! `revoke-user-session`, `revoke-user-sessions`, `impersonate-user`, `stop-impersonating`
29//! and `has-permission`. Each checks the caller's roles against the action it performs
30//! and answers 403 with Better Auth's code when they don't allow it; `auth.admin()` runs
31//! the same operations from server code without a session.
32//!
33//! A sign-in gate refuses banned users with `403 BANNED_USER` for every sign-in method,
34//! and lifts expired bans. A session gate refuses them the same way on every request,
35//! whatever the session came from (cookie, cookie cache, bearer token, API key), and refuses
36//! impersonation sessions in endpoints that create credentials
37//! (`403 NOT_ALLOWED_WHILE_IMPERSONATING`). Admins without `user:impersonate-admins` can't
38//! act on another admin's account (`403 YOU_CANNOT_MANAGE_ADMINS`).
39//!
40//! With the `axum` feature, [`RequireRole`] guards your own routes by role.
41
42mod access;
43#[cfg(feature = "axum")]
44mod axum;
45mod endpoints;
46mod error;
47mod model;
48
49use std::collections::BTreeMap;
50
51use fastauth_core::ApiResponse;
52use fastauth_core::events::UserCreated;
53use fastauth_core::plugin_prelude::*;
54use fastauth_core::routes::ListSessions;
55use serde_json::{Map, Value as Json};
56
57pub use access::{Permissions, STATEMENTS};
58#[cfg(feature = "axum")]
59pub use axum::{RequireRole, Role, role};
60pub use endpoints::{
61    BanUser, BanUserInput, CreateUser, CreateUserInput, GetUser, GetUserQuery, HasPermission,
62    HasPermissionInput, ImpersonateUser, ListUserSessions, ListUsers, ListUsersQuery,
63    PermissionOutput, RemoveUser, RevokeUserSession, RevokeUserSessionInput, RevokeUserSessions,
64    Roles, SearchField, SearchOperator, SessionList, SessionOutput, SetRole, SetRoleInput,
65    SetUserPassword, SetUserPasswordInput, SortDirection, StopImpersonating, Success, UnbanUser,
66    UpdateUser, UpdateUserInput, UserIdInput, UserList, UserOutput, WhereOperator,
67};
68pub use error::AdminError;
69pub use model::{AdminSession, AdminUser};
70
71const DEFAULT_BANNED_MESSAGE: &str = "You have been banned from this application. Please contact support if you believe this is an error.";
72
73/// The admin plugin: `.plugin(Admin::new())`.
74#[derive(Clone, Debug)]
75pub struct Admin {
76    default_role: String,
77    admin_roles: Vec<String>,
78    admin_user_ids: Vec<Id>,
79    impersonation_session_duration: Duration,
80    default_ban_reason: Option<String>,
81    default_ban_expires_in: Option<Duration>,
82    banned_user_message: String,
83    roles: BTreeMap<String, Permissions>,
84}
85
86impl Default for Admin {
87    fn default() -> Self {
88        Self {
89            default_role: "user".to_owned(),
90            admin_roles: vec!["admin".to_owned()],
91            admin_user_ids: Vec::new(),
92            impersonation_session_duration: Duration::hours(1),
93            default_ban_reason: None,
94            default_ban_expires_in: None,
95            banned_user_message: DEFAULT_BANNED_MESSAGE.to_owned(),
96            roles: BTreeMap::from([
97                ("admin".to_owned(), Permissions::admin()),
98                ("user".to_owned(), Permissions::new()),
99            ]),
100        }
101    }
102}
103
104impl Admin {
105    /// The default config: roles `admin` (every admin action but impersonating admins) and
106    /// `user` (none), new users get `user`, and `admin` counts as an admin role.
107    pub fn new() -> Self {
108        Self::default()
109    }
110
111    /// The role new users get (default `"user"`).
112    pub fn default_role(mut self, role: impl Into<String>) -> Self {
113        self.default_role = role.into();
114        self
115    }
116
117    /// Roles whose holders count as admins (default `["admin"]`): they can't be impersonated
118    /// without `user:impersonate-admins`, and they pass `RequireRole<_, role::Admin>`. Each
119    /// must be a defined role; `.build()` panics otherwise, like Better Auth.
120    pub fn admin_roles(mut self, roles: impl IntoIterator<Item = impl Into<String>>) -> Self {
121        self.admin_roles = roles.into_iter().map(Into::into).collect();
122        self
123    }
124
125    /// Users who are admins whatever their role: every permission check passes for them,
126    /// and they pass `RequireRole<_, role::Admin>`.
127    pub fn admin_user_ids(mut self, ids: impl IntoIterator<Item = impl Into<Id>>) -> Self {
128        self.admin_user_ids = ids.into_iter().map(Into::into).collect();
129        self
130    }
131
132    /// How long an impersonation session lasts (default one hour).
133    pub fn impersonation_session_duration(mut self, duration: Duration) -> Self {
134        self.impersonation_session_duration = duration;
135        self
136    }
137
138    /// The reason stored when a ban gives none (default `"No reason"`).
139    pub fn default_ban_reason(mut self, reason: impl Into<String>) -> Self {
140        self.default_ban_reason = Some(reason.into());
141        self
142    }
143
144    /// How long bans last when the request gives no expiry (default: for good).
145    pub fn default_ban_expires_in(mut self, duration: Duration) -> Self {
146        self.default_ban_expires_in = Some(duration);
147        self
148    }
149
150    /// What a banned user's sign-in answers with, before the ban's reason.
151    pub fn banned_user_message(mut self, message: impl Into<String>) -> Self {
152        self.banned_user_message = message.into();
153        self
154    }
155
156    /// Defines a role, or replaces a built-in one (`admin`, `user`).
157    pub fn role(mut self, name: impl Into<String>, permissions: Permissions) -> Self {
158        self.roles.insert(name.into(), permissions);
159        self
160    }
161
162    /// The role names in a `user.role` value, or the default role when it is empty.
163    pub fn roles_of<'a>(&'a self, role: Option<&'a str>) -> impl Iterator<Item = &'a str> {
164        role.filter(|r| !r.trim().is_empty())
165            .unwrap_or(&self.default_role)
166            .split(',')
167            .map(str::trim)
168            .filter(|r| !r.is_empty())
169    }
170
171    /// Whether the role is defined.
172    pub fn has_role_defined(&self, role: &str) -> bool {
173        self.roles.contains_key(role)
174    }
175
176    /// Whether this user is an admin: listed in `admin_user_ids`, or holding an admin role.
177    pub fn is_admin(&self, user_id: &Id, role: Option<&str>) -> bool {
178        self.admin_user_ids.contains(user_id)
179            || self
180                .roles_of(role)
181                .any(|r| self.admin_roles.iter().any(|a| a == r))
182    }
183
184    /// Whether a user with this id and `user.role` value may do everything in
185    /// `permissions`: true for `admin_user_ids`, else when one of their roles grants it all.
186    pub fn has_permission(
187        &self,
188        user_id: &Id,
189        role: Option<&str>,
190        permissions: &Permissions,
191    ) -> bool {
192        self.admin_user_ids.contains(user_id)
193            || self
194                .roles_of(role)
195                .any(|r| self.roles.get(r).is_some_and(|p| p.authorize(permissions)))
196    }
197
198    /// Whether the user holds `name`, counting every admin as holding each admin role.
199    pub fn has_role(&self, user_id: &Id, role: Option<&str>, name: &str) -> bool {
200        self.roles_of(role).any(|r| r == name)
201            || (self.admin_roles.iter().any(|a| a == name) && self.is_admin(user_id, role))
202    }
203
204    fn banned_error(&self, reason: Option<&str>) -> AuthError {
205        let message = match reason {
206            Some(reason) if !reason.is_empty() => {
207                format!("{} Reason: {reason}", self.banned_user_message)
208            }
209            _ => self.banned_user_message.clone(),
210        };
211        AdminError::BannedUser { message }.into()
212    }
213}
214
215impl Plugin for Admin {
216    const ID: &'static str = "admin";
217    type Requires = ();
218    type UserFields = AdminUser;
219    type SessionFields = AdminSession;
220
221    fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
222        let undefined: Vec<&str> = self
223            .admin_roles
224            .iter()
225            .filter(|r| !self.roles.contains_key(r.as_str()))
226            .map(String::as_str)
227            .collect();
228        assert!(
229            undefined.is_empty(),
230            "invalid admin roles: {}; admin roles must be defined with `Admin::role`",
231            undefined.join(", ")
232        );
233        let caller = endpoints::Caller::http(self.clone());
234        app.endpoint(CreateUser(caller.clone()))
235            .endpoint(ListUsers(caller.clone()))
236            .endpoint(GetUser(caller.clone()))
237            .endpoint(SetRole(caller.clone()))
238            .endpoint(BanUser(caller.clone()))
239            .endpoint(UnbanUser(caller.clone()))
240            .endpoint(UpdateUser(caller.clone()))
241            .endpoint(SetUserPassword(caller.clone()))
242            .endpoint(RemoveUser(caller.clone()))
243            .endpoint(ListUserSessions(caller.clone()))
244            .endpoint(RevokeUserSession(caller.clone()))
245            .endpoint(RevokeUserSessions(caller.clone()))
246            .endpoint(HasPermission(caller))
247            .endpoint(ImpersonateUser(self.clone()))
248            .endpoint(StopImpersonating)
249            .errors::<AdminError>();
250
251        let plugin = self.clone();
252        app.sign_in_gate(move |ctx, attempt| {
253            let plugin = plugin.clone();
254            async move {
255                Ok(
256                    match endpoints::ban_error(&plugin, &ctx, &attempt.user).await? {
257                        Some(err) => Gate::Deny(err),
258                        None => Gate::Allow,
259                    },
260                )
261            }
262        });
263
264        app.fixed_session_expiry(|session| {
265            session
266                .fields::<AdminSession>()
267                .is_ok_and(|fields| fields.impersonated_by.is_some())
268        });
269
270        let plugin = self.clone();
271        app.session_gate(move |ctx, session, usage| {
272            let plugin = plugin.clone();
273            async move {
274                if let Some(err) = endpoints::ban_error(&plugin, &ctx, &session.user).await? {
275                    return Err(err);
276                }
277                let impersonating = session
278                    .fields::<AdminSession>()
279                    .map_err(AuthError::internal)?
280                    .impersonated_by
281                    .is_some();
282                if usage == SessionUse::Sensitive && impersonating {
283                    return Err(AdminError::NotAllowedWhileImpersonating.into());
284                }
285                Ok(())
286            }
287        });
288
289        let plugin = self.clone();
290        app.on(move |event: UserCreated, ctx: Ctx<D>| {
291            let default_role = plugin.default_role.clone();
292            async move {
293                ctx.db()
294                    .update::<User>(User::ID.eq(&event.user_id).and(AdminUser::ROLE.is_null()))
295                    .set(AdminUser::ROLE, Some(default_role))
296                    .exec()
297                    .await?;
298                Ok(())
299            }
300        });
301
302        app.hook::<ListSessions>()
303            .after(|_, sessions: Vec<Map<String, Json>>| async move {
304                Ok(After::Continue(
305                    sessions
306                        .into_iter()
307                        .filter(|s| s.get("impersonatedBy").is_none_or(Json::is_null))
308                        .collect(),
309                ))
310            });
311    }
312}
313
314/// `auth.admin()`: the server API. Only compiles on an `Auth` with `Admin` registered.
315pub trait AdminExt: AuthInstance + Sized {
316    fn admin<I>(&self) -> AdminApi<'_, Self>
317    where
318        Self: HasPlugin<Admin, I>,
319    {
320        AdminApi {
321            auth: self,
322            plugin: self.plugin_arc().clone(),
323        }
324    }
325}
326
327impl<A: AuthInstance> AdminExt for A {}
328
329/// Runs admin operations from server code. Calls are trusted: they need no session and skip
330/// the permission checks, but run the same hooks and events as the HTTP routes.
331/// Impersonation acts for a signed-in admin, so it takes the request's headers.
332pub struct AdminApi<'a, A> {
333    auth: &'a A,
334    plugin: Arc<Admin>,
335}
336
337impl<A: AuthInstance> AdminApi<'_, A> {
338    fn caller(&self) -> endpoints::Caller {
339        endpoints::Caller::server(self.plugin.clone())
340    }
341
342    async fn run<E: Endpoint<A::Db>>(
343        &self,
344        endpoint: E,
345        input: E::Input,
346    ) -> Result<E::Output, AuthError> {
347        Ok(self.auth.api().call(&endpoint, input).await?.data)
348    }
349
350    /// Creates a user with a role, a password and any user columns.
351    pub async fn create_user(&self, input: CreateUserInput) -> Result<UserView, AuthError> {
352        Ok(self.run(CreateUser(self.caller()), input).await?.user)
353    }
354
355    /// Lists users with search, filter, sort and pagination.
356    pub async fn list_users(&self, query: ListUsersQuery) -> Result<UserList, AuthError> {
357        self.run(ListUsers(self.caller()), query).await
358    }
359
360    /// One user by id.
361    pub async fn get_user(&self, id: &Id) -> Result<UserView, AuthError> {
362        self.run(GetUser(self.caller()), GetUserQuery { id: id.clone() })
363            .await
364    }
365
366    /// Replaces a user's roles.
367    pub async fn set_role(
368        &self,
369        user_id: &Id,
370        role: impl Into<Roles>,
371    ) -> Result<UserView, AuthError> {
372        let input = SetRoleInput {
373            user_id: user_id.clone(),
374            role: role.into(),
375        };
376        Ok(self.run(SetRole(self.caller()), input).await?.user)
377    }
378
379    /// Bans a user and revokes every session they have.
380    pub async fn ban(&self, input: BanUserInput) -> Result<UserView, AuthError> {
381        Ok(self.run(BanUser(self.caller()), input).await?.user)
382    }
383
384    /// Lifts a user's ban.
385    pub async fn unban(&self, user_id: &Id) -> Result<UserView, AuthError> {
386        let input = UserIdInput {
387            user_id: user_id.clone(),
388        };
389        Ok(self.run(UnbanUser(self.caller()), input).await?.user)
390    }
391
392    /// Updates user columns by camelCase name, as `/admin/update-user` does.
393    pub async fn update_user(
394        &self,
395        user_id: &Id,
396        data: Map<String, Json>,
397    ) -> Result<UserView, AuthError> {
398        let input = UpdateUserInput {
399            user_id: user_id.clone(),
400            data,
401        };
402        self.run(UpdateUser(self.caller()), input).await
403    }
404
405    /// Sets a user's password, creating their credential account if needed.
406    pub async fn set_user_password(
407        &self,
408        user_id: &Id,
409        new_password: &str,
410    ) -> Result<(), AuthError> {
411        let input = SetUserPasswordInput {
412            user_id: user_id.clone(),
413            new_password: new_password.to_owned(),
414        };
415        self.run(SetUserPassword(self.caller()), input).await?;
416        Ok(())
417    }
418
419    /// Deletes a user with their sessions and accounts.
420    pub async fn remove_user(&self, user_id: &Id) -> Result<(), AuthError> {
421        let input = UserIdInput {
422            user_id: user_id.clone(),
423        };
424        self.run(RemoveUser(self.caller()), input).await?;
425        Ok(())
426    }
427
428    /// A user's unexpired sessions, as client JSON.
429    pub async fn list_user_sessions(
430        &self,
431        user_id: &Id,
432    ) -> Result<Vec<Map<String, Json>>, AuthError> {
433        let input = UserIdInput {
434            user_id: user_id.clone(),
435        };
436        Ok(self
437            .run(ListUserSessions(self.caller()), input)
438            .await?
439            .sessions)
440    }
441
442    /// Revokes the session with this raw token.
443    pub async fn revoke_user_session(&self, session_token: &str) -> Result<(), AuthError> {
444        let input = RevokeUserSessionInput {
445            session_token: session_token.to_owned(),
446        };
447        self.run(RevokeUserSession(self.caller()), input).await?;
448        Ok(())
449    }
450
451    /// Revokes every session of a user.
452    pub async fn revoke_user_sessions(&self, user_id: &Id) -> Result<(), AuthError> {
453        let input = UserIdInput {
454            user_id: user_id.clone(),
455        };
456        self.run(RevokeUserSessions(self.caller()), input).await?;
457        Ok(())
458    }
459
460    /// Whether the user may do everything in `permissions`. Unknown users may do nothing.
461    pub async fn has_permission(
462        &self,
463        user_id: &Id,
464        permissions: Permissions,
465    ) -> Result<bool, AuthError> {
466        let input = HasPermissionInput {
467            user_id: Some(user_id.clone()),
468            permissions: Some(permissions),
469            ..HasPermissionInput::default()
470        };
471        match self.run(HasPermission(self.caller()), input).await {
472            Ok(output) => Ok(output.success),
473            Err(err) if err.status() == StatusCode::BAD_REQUEST => Ok(false),
474            Err(err) => Err(err),
475        }
476    }
477
478    /// `POST /admin/impersonate-user` as the admin whose session cookie is in `headers`.
479    /// The response's cookies switch the browser to the user.
480    pub async fn impersonate(
481        &self,
482        headers: &HeaderMap,
483        user_id: &Id,
484    ) -> Result<ApiResponse<SessionOutput>, AuthError> {
485        let input = UserIdInput {
486            user_id: user_id.clone(),
487        };
488        self.auth
489            .api()
490            .headers(headers)
491            .call(&ImpersonateUser(self.plugin.clone()), input)
492            .await
493    }
494
495    /// `POST /admin/stop-impersonating` for the impersonation session in `headers`.
496    pub async fn stop_impersonating(
497        &self,
498        headers: &HeaderMap,
499    ) -> Result<ApiResponse<SessionOutput>, AuthError> {
500        self.auth
501            .api()
502            .headers(headers)
503            .call(&StopImpersonating, Empty {})
504            .await
505    }
506}