1mod 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#[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 pub fn new() -> Self {
115 Self::default()
116 }
117
118 pub fn default_role(mut self, role: impl Into<String>) -> Self {
120 self.default_role = role.into();
121 self
122 }
123
124 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 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 pub fn impersonation_session_duration(mut self, duration: Duration) -> Self {
141 self.impersonation_session_duration = duration;
142 self
143 }
144
145 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 pub fn default_ban_expires_in(mut self, duration: Duration) -> Self {
153 self.default_ban_expires_in = Some(duration);
154 self
155 }
156
157 pub fn banned_user_message(mut self, message: impl Into<String>) -> Self {
159 self.banned_user_message = message.into();
160 self
161 }
162
163 pub fn role(mut self, name: impl Into<String>, permissions: Permissions) -> Self {
165 self.roles.insert(name.into(), permissions);
166 self
167 }
168
169 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 pub fn has_role_defined(&self, role: &str) -> bool {
180 self.roles.contains_key(role)
181 }
182
183 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 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 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
321pub 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
336pub 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 pub async fn create_user(&self, input: CreateUserInput) -> Result<UserView, AuthError> {
359 Ok(self.run(CreateUser(self.caller()), input).await?.user)
360 }
361
362 pub async fn list_users(&self, query: ListUsersQuery) -> Result<UserList, AuthError> {
364 self.run(ListUsers(self.caller()), query).await
365 }
366
367 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 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 pub async fn ban(&self, input: BanUserInput) -> Result<UserView, AuthError> {
388 Ok(self.run(BanUser(self.caller()), input).await?.user)
389 }
390
391 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 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 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 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 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 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 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 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 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 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}