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