1mod 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#[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 pub fn new() -> Self {
108 Self::default()
109 }
110
111 pub fn default_role(mut self, role: impl Into<String>) -> Self {
113 self.default_role = role.into();
114 self
115 }
116
117 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 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 pub fn impersonation_session_duration(mut self, duration: Duration) -> Self {
134 self.impersonation_session_duration = duration;
135 self
136 }
137
138 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 pub fn default_ban_expires_in(mut self, duration: Duration) -> Self {
146 self.default_ban_expires_in = Some(duration);
147 self
148 }
149
150 pub fn banned_user_message(mut self, message: impl Into<String>) -> Self {
152 self.banned_user_message = message.into();
153 self
154 }
155
156 pub fn role(mut self, name: impl Into<String>, permissions: Permissions) -> Self {
158 self.roles.insert(name.into(), permissions);
159 self
160 }
161
162 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 pub fn has_role_defined(&self, role: &str) -> bool {
173 self.roles.contains_key(role)
174 }
175
176 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 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 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
314pub 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
329pub 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 pub async fn create_user(&self, input: CreateUserInput) -> Result<UserView, AuthError> {
352 Ok(self.run(CreateUser(self.caller()), input).await?.user)
353 }
354
355 pub async fn list_users(&self, query: ListUsersQuery) -> Result<UserList, AuthError> {
357 self.run(ListUsers(self.caller()), query).await
358 }
359
360 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 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 pub async fn ban(&self, input: BanUserInput) -> Result<UserView, AuthError> {
381 Ok(self.run(BanUser(self.caller()), input).await?.user)
382 }
383
384 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 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 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 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 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 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 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 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 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 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}