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