1mod 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#[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 pub fn new() -> Self {
104 Self::default()
105 }
106
107 pub fn default_role(mut self, role: impl Into<String>) -> Self {
109 self.default_role = role.into();
110 self
111 }
112
113 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 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 pub fn impersonation_session_duration(mut self, duration: Duration) -> Self {
130 self.impersonation_session_duration = duration;
131 self
132 }
133
134 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 pub fn default_ban_expires_in(mut self, duration: Duration) -> Self {
142 self.default_ban_expires_in = Some(duration);
143 self
144 }
145
146 pub fn banned_user_message(mut self, message: impl Into<String>) -> Self {
148 self.banned_user_message = message.into();
149 self
150 }
151
152 pub fn role(mut self, name: impl Into<String>, permissions: Permissions) -> Self {
154 self.roles.insert(name.into(), permissions);
155 self
156 }
157
158 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 pub fn has_role_defined(&self, role: &str) -> bool {
169 self.roles.contains_key(role)
170 }
171
172 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 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 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
285pub 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
300pub 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 pub async fn create_user(&self, input: CreateUserInput) -> Result<UserView, AuthError> {
323 Ok(self.run(CreateUser(self.caller()), input).await?.user)
324 }
325
326 pub async fn list_users(&self, query: ListUsersQuery) -> Result<UserList, AuthError> {
328 self.run(ListUsers(self.caller()), query).await
329 }
330
331 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 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 pub async fn ban(&self, input: BanUserInput) -> Result<UserView, AuthError> {
352 Ok(self.run(BanUser(self.caller()), input).await?.user)
353 }
354
355 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 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 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 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 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 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 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 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 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 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}