1use fastauth_core::events::{PasswordChanged, UserDeleted, UserUpdated};
4use fastauth_core::plugin_prelude::*;
5use fastauth_core::routes::Status;
6use fastauth_core::schema::ColumnDef;
7use serde_json::{Map, Value as Json};
8use time::format_description::well_known::Rfc3339;
9
10use crate::{Admin, AdminError, AdminSession, AdminUser, Permissions};
11
12const ADMIN_SESSION_COOKIE: &str = "admin_session";
13const SESSION_TOKEN_COOKIE: &str = "session_token";
14const DONT_REMEMBER_COOKIE: &str = "dont_remember";
15const SESSION_CACHE_COOKIE: &str = "session_data";
16const BAN_COLUMNS: [&str; 3] = ["banned", "banReason", "banExpires"];
17
18#[derive(Clone, Debug)]
21pub struct Caller {
22 plugin: Arc<Admin>,
23 server: bool,
24}
25
26impl Caller {
27 pub(crate) fn http(plugin: Arc<Admin>) -> Self {
28 Self {
29 plugin,
30 server: false,
31 }
32 }
33
34 pub(crate) fn server(plugin: Arc<Admin>) -> Self {
35 Self {
36 plugin,
37 server: true,
38 }
39 }
40
41 fn check<'c, D: Adapter>(
44 &self,
45 ctx: &'c Ctx<D, MaybeAuthenticated>,
46 resource: &str,
47 action: &str,
48 denied: AdminError,
49 ) -> Result<Option<&'c SessionView>, AuthError> {
50 if self.server {
51 return Ok(None);
52 }
53 let session = ctx.session().ok_or_else(AuthError::unauthorized)?;
54 if !may(&self.plugin, Some(session), resource, action)? {
55 return Err(denied.into());
56 }
57 Ok(Some(session))
58 }
59
60 fn also(
62 &self,
63 session: Option<&SessionView>,
64 resource: &str,
65 action: &str,
66 denied: AdminError,
67 ) -> Result<(), AuthError> {
68 if may(&self.plugin, session, resource, action)? {
69 Ok(())
70 } else {
71 Err(denied.into())
72 }
73 }
74}
75
76fn may(
78 plugin: &Admin,
79 session: Option<&SessionView>,
80 resource: &str,
81 action: &str,
82) -> Result<bool, AuthError> {
83 let Some(session) = session else {
84 return Ok(true);
85 };
86 let fields = admin_fields(&session.user)?;
87 Ok(plugin.has_permission(
88 &session.user.id,
89 fields.role.as_deref(),
90 &Permissions::new().allow(resource, [action]),
91 ))
92}
93
94fn check_target(
98 plugin: &Admin,
99 session: Option<&SessionView>,
100 target: &UserView,
101) -> Result<(), AuthError> {
102 let Some(session) = session.filter(|s| s.user.id != target.id) else {
103 return Ok(());
104 };
105 if plugin.is_admin(&target.id, admin_fields(target)?.role.as_deref())
106 && !may(plugin, Some(session), "user", "impersonate-admins")?
107 {
108 return Err(AdminError::YouCannotManageAdmins.into());
109 }
110 Ok(())
111}
112
113fn admin_fields(user: &UserView) -> Result<AdminUser, AuthError> {
114 user.fields().map_err(AuthError::internal)
115}
116
117pub(crate) async fn ban_error<D: Adapter, A>(
119 plugin: &Admin,
120 ctx: &Ctx<D, A>,
121 user: &UserView,
122) -> Result<Option<AuthError>, AuthError> {
123 let fields = admin_fields(user)?;
124 if !fields.banned {
125 return Ok(None);
126 }
127 if fields.ban_expires.is_some_and(|t| t <= ctx.now()) {
128 lift_ban(ctx, &user.id).await?;
129 return Ok(None);
130 }
131 Ok(Some(plugin.banned_error(fields.ban_reason.as_deref())))
132}
133
134async fn lift_ban<D: Adapter, A>(ctx: &Ctx<D, A>, user_id: &Id) -> Result<(), AuthError> {
135 ctx.db()
136 .update::<User>(User::ID.eq(user_id))
137 .set(AdminUser::BANNED, false)
138 .set(AdminUser::BAN_REASON, None::<String>)
139 .set(AdminUser::BAN_EXPIRES, None::<OffsetDateTime>)
140 .exec()
141 .await?;
142 Ok(())
143}
144
145async fn find_user<D: Adapter, A>(ctx: &Ctx<D, A>, id: &Id) -> Result<UserView, AuthError> {
146 ctx.internal()
147 .find_user_by_id(id)
148 .await?
149 .ok_or_else(user_not_found)
150}
151
152fn user_not_found() -> AuthError {
153 AuthError::new(
154 StatusCode::NOT_FOUND,
155 codes::USER_NOT_FOUND,
156 "User not found",
157 )
158}
159
160fn invalid_field(message: String) -> AuthError {
161 AuthError::bad_request(codes::INVALID_FIELD, message)
162}
163
164fn camel_case(snake: &str) -> String {
165 let mut out = String::with_capacity(snake.len());
166 let mut upper = false;
167 for ch in snake.chars() {
168 if ch == '_' {
169 upper = true;
170 } else if upper {
171 out.extend(ch.to_uppercase());
172 upper = false;
173 } else {
174 out.push(ch);
175 }
176 }
177 out
178}
179
180fn user_column<D: Adapter, A>(ctx: &Ctx<D, A>, key: &str) -> Result<ColumnDef, AuthError> {
182 ctx.schema()
183 .expect(User::TABLE)
184 .columns
185 .iter()
186 .find(|c| c.returned && camel_case(c.name) == key)
187 .copied()
188 .ok_or_else(|| invalid_field(format!("unknown field `{key}`")))
189}
190
191fn column_value(column: &ColumnDef, key: &str, json: &Json) -> Result<Value, AuthError> {
192 Value::from_json(column.ty, json)
193 .filter(|v| !v.is_null() || column.nullable)
194 .ok_or_else(|| invalid_field(format!("field `{key}` has the wrong type")))
195}
196
197fn normalize_email(email: &str) -> Result<String, AuthError> {
198 let email = email.trim().to_lowercase();
199 let valid = email.len() <= 254
200 && email.split_once('@').is_some_and(|(local, domain)| {
201 !local.is_empty() && domain.contains('.') && !domain.starts_with('.')
202 });
203 if !valid {
204 return Err(AuthError::bad_request(
205 codes::INVALID_EMAIL,
206 "Invalid email",
207 ));
208 }
209 Ok(email)
210}
211
212fn email_taken() -> AuthError {
213 AuthError::bad_request(
214 codes::USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL,
215 "User already exists. Use another email.",
216 )
217}
218
219#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
221#[serde(untagged)]
222pub enum Roles {
223 One(String),
224 Many(Vec<String>),
225}
226
227impl Roles {
228 fn names(&self) -> Vec<&str> {
229 let parts: Vec<&str> = match self {
230 Roles::One(role) => vec![role.as_str()],
231 Roles::Many(roles) => roles.iter().map(String::as_str).collect(),
232 };
233 parts
234 .into_iter()
235 .flat_map(|r| r.split(','))
236 .map(str::trim)
237 .filter(|r| !r.is_empty())
238 .collect()
239 }
240
241 fn stored(&self, plugin: &Admin) -> Result<String, AuthError> {
243 let names = self.names();
244 if names.is_empty() {
245 return Err(AdminError::InvalidRoleType.into());
246 }
247 if names.iter().any(|r| !plugin.has_role_defined(r)) {
248 return Err(AdminError::YouAreNotAllowedToSetNonExistentValue.into());
249 }
250 Ok(names.join(","))
251 }
252
253 fn from_json(json: &Json) -> Result<Self, AuthError> {
254 serde_json::from_value(json.clone()).map_err(|_| AdminError::InvalidRoleType.into())
255 }
256}
257
258impl From<&str> for Roles {
259 fn from(role: &str) -> Self {
260 Roles::One(role.to_owned())
261 }
262}
263
264impl From<String> for Roles {
265 fn from(role: String) -> Self {
266 Roles::One(role)
267 }
268}
269
270impl<const N: usize> From<[&str; N]> for Roles {
271 fn from(roles: [&str; N]) -> Self {
272 Roles::Many(roles.iter().map(|r| (*r).to_owned()).collect())
273 }
274}
275
276#[derive(Debug, Serialize)]
278pub struct UserOutput {
279 pub user: UserView,
280}
281
282#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
284pub struct Success {
285 pub success: bool,
286}
287
288#[derive(Clone, Debug, Deserialize)]
290#[serde(rename_all = "camelCase")]
291pub struct UserIdInput {
292 pub user_id: Id,
293}
294
295#[derive(Clone, Debug, Default, Deserialize)]
299#[serde(rename_all = "camelCase")]
300pub struct CreateUserInput {
301 pub email: String,
302 #[serde(default)]
304 pub password: Option<String>,
305 pub name: String,
306 #[serde(default)]
308 pub role: Option<Roles>,
309 #[serde(default)]
311 pub data: Map<String, Json>,
312}
313
314pub struct CreateUser(pub(crate) Caller);
317
318impl<D: Adapter> Endpoint<D> for CreateUser {
319 const METHOD: Method = Method::POST;
320 const PATH: &'static str = "/admin/create-user";
321 type Access = MaybeAuthenticated;
322 type Input = CreateUserInput;
323 type Output = UserOutput;
324
325 async fn call(
326 &self,
327 ctx: Ctx<D, MaybeAuthenticated>,
328 mut input: CreateUserInput,
329 ) -> Result<UserOutput, AuthError> {
330 let caller = &self.0;
331 let plugin = &caller.plugin;
332 let session = caller.check(
333 &ctx,
334 "user",
335 "create",
336 AdminError::YouAreNotAllowedToCreateUsers,
337 )?;
338 let data_role = input.data.remove("role");
339 let role = match (input.role, data_role) {
340 (Some(role), _) => Some(role),
341 (None, Some(json)) => Some(Roles::from_json(&json)?),
342 (None, None) => None,
343 };
344 let role = match role {
345 Some(role) => {
346 caller.also(
347 session,
348 "user",
349 "set-role",
350 AdminError::YouAreNotAllowedToChangeUsersRole,
351 )?;
352 role.stored(plugin)?
353 }
354 None => plugin.default_role.clone(),
355 };
356 if BAN_COLUMNS.iter().any(|k| input.data.contains_key(*k)) {
357 caller.also(
358 session,
359 "user",
360 "ban",
361 AdminError::YouAreNotAllowedToBanUsers,
362 )?;
363 }
364 let email = normalize_email(&input.email)?;
365 let internal = ctx.internal();
366 if let Some(password) = &input.password {
367 internal.validate_new_password(password)?;
368 }
369 if internal.find_user_by_email(&email).await?.is_some() {
370 return Err(email_taken());
371 }
372 let mut extra = vec![("role", Value::Text(role))];
373 for (key, json) in &input.data {
374 let column = user_column(&ctx, key)?;
375 if matches!(
376 column.name,
377 "id" | "email" | "name" | "created_at" | "updated_at"
378 ) {
379 return Err(invalid_field(format!("field `{key}` can't be set")));
380 }
381 extra.push((column.name, column_value(&column, key, json)?));
382 }
383 let missing = ctx.schema().expect(User::TABLE).columns.iter().find(|c| {
384 c.owner != "core"
385 && !c.nullable
386 && c.default.is_none()
387 && !extra.iter().any(|(name, _)| *name == c.name)
388 });
389 if let Some(column) = missing {
390 return Err(invalid_field(format!(
391 "field `{}` is required",
392 camel_case(column.name)
393 )));
394 }
395 let account = match &input.password {
396 Some(password) => Some(NewAccount::credential(
397 ctx.passwords()
398 .hash(password)
399 .await
400 .map_err(AuthError::internal)?,
401 )),
402 None => None,
403 };
404 let user = NewUser {
405 email,
406 name: input.name,
407 extra,
408 ..NewUser::default()
409 };
410 let user = internal.create_user(user, account).await?;
411 Ok(UserOutput { user })
412 }
413}
414
415#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
419#[serde(rename_all = "camelCase")]
420pub enum SearchField {
421 #[default]
422 Email,
423 Name,
424}
425
426#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
428#[serde(rename_all = "snake_case")]
429pub enum SearchOperator {
430 #[default]
431 Contains,
432 StartsWith,
433 EndsWith,
434}
435
436#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
438#[serde(rename_all = "lowercase")]
439pub enum SortDirection {
440 #[default]
441 Asc,
442 Desc,
443}
444
445#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
448#[serde(rename_all = "snake_case")]
449pub enum WhereOperator {
450 #[default]
451 Eq,
452 Ne,
453 Lt,
454 Lte,
455 Gt,
456 Gte,
457 In,
458 NotIn,
459 Contains,
460 StartsWith,
461 EndsWith,
462}
463
464#[derive(Clone, Debug, Default, Deserialize)]
466#[serde(rename_all = "camelCase")]
467pub struct ListUsersQuery {
468 pub search_value: Option<String>,
469 pub search_field: Option<SearchField>,
470 pub search_operator: Option<SearchOperator>,
471 pub limit: Option<u64>,
472 pub offset: Option<u64>,
473 pub sort_by: Option<String>,
475 pub sort_direction: Option<SortDirection>,
476 pub filter_field: Option<String>,
478 pub filter_value: Option<String>,
480 pub filter_operator: Option<WhereOperator>,
481}
482
483#[derive(Debug, Serialize)]
485pub struct UserList {
486 pub users: Vec<UserView>,
487 pub total: u64,
488 #[serde(skip_serializing_if = "Option::is_none")]
489 pub limit: Option<u64>,
490 #[serde(skip_serializing_if = "Option::is_none")]
491 pub offset: Option<u64>,
492}
493
494pub struct ListUsers(pub(crate) Caller);
497
498fn text_match(
500 column: &ColumnDef,
501 operator: WhereOperator,
502 value: &str,
503) -> Result<Where<User>, AuthError> {
504 use fastauth_core::schema::ColumnType;
505 if !matches!(column.ty, ColumnType::Text | ColumnType::Id) {
506 return Err(invalid_field(format!(
507 "`{}` isn't text",
508 camel_case(column.name)
509 )));
510 }
511 let col = Col::<User, String>::new(column.name);
512 Ok(match operator {
513 WhereOperator::StartsWith => col.starts_with(value),
514 WhereOperator::EndsWith => col.ends_with(value),
515 _ => col.contains(value),
516 })
517}
518
519fn parse_filter<T: ColumnValue>(
520 column: &'static str,
521 operator: WhereOperator,
522 raw: &str,
523 parse: impl Fn(&str) -> Option<T>,
524) -> Result<Where<User>, AuthError> {
525 let col = Col::<User, T>::new(column);
526 let one = || {
527 parse(raw.trim())
528 .ok_or_else(|| invalid_field(format!("can't compare `{column}` with `{raw}`")))
529 };
530 let many = || {
531 raw.split(',')
532 .map(|v| {
533 parse(v.trim())
534 .ok_or_else(|| invalid_field(format!("can't compare `{column}` with `{v}`")))
535 })
536 .collect::<Result<Vec<T>, AuthError>>()
537 };
538 Ok(match operator {
539 WhereOperator::Ne => col.ne(one()?),
540 WhereOperator::Lt => col.lt(one()?),
541 WhereOperator::Lte => col.lte(one()?),
542 WhereOperator::Gt => col.gt(one()?),
543 WhereOperator::Gte => col.gte(one()?),
544 WhereOperator::In => col.in_(many()?),
545 WhereOperator::NotIn => {
546 let mut values = many()?.into_iter();
547 let first = values
548 .next()
549 .ok_or_else(|| invalid_field("`not_in` needs a value".to_owned()))?;
550 values.fold(col.ne(first), |filter, v| filter.and(col.ne(v)))
551 }
552 _ => col.eq(one()?),
553 })
554}
555
556fn comparison(
557 column: &ColumnDef,
558 operator: WhereOperator,
559 raw: &str,
560) -> Result<Where<User>, AuthError> {
561 use fastauth_core::schema::ColumnType;
562 let name = column.name;
563 match column.ty {
564 ColumnType::Text | ColumnType::Id => {
565 parse_filter::<String>(name, operator, raw, |v| Some(v.to_owned()))
566 }
567 ColumnType::Bool => parse_filter::<bool>(name, operator, raw, |v| v.parse().ok()),
568 ColumnType::Int => parse_filter::<i64>(name, operator, raw, |v| v.parse().ok()),
569 ColumnType::Timestamp => parse_filter::<OffsetDateTime>(name, operator, raw, |v| {
570 OffsetDateTime::parse(v, &Rfc3339).ok()
571 }),
572 _ => Err(invalid_field(format!(
573 "`{}` can't be filtered",
574 camel_case(name)
575 ))),
576 }
577}
578
579impl<D: Adapter> Endpoint<D> for ListUsers {
580 const METHOD: Method = Method::GET;
581 const PATH: &'static str = "/admin/list-users";
582 type Access = MaybeAuthenticated;
583 type Input = ListUsersQuery;
584 type Output = UserList;
585
586 async fn call(
587 &self,
588 ctx: Ctx<D, MaybeAuthenticated>,
589 query: ListUsersQuery,
590 ) -> Result<UserList, AuthError> {
591 self.0.check(
592 &ctx,
593 "user",
594 "list",
595 AdminError::YouAreNotAllowedToListUsers,
596 )?;
597 let mut conditions = Vec::new();
598 if let Some(value) = query.search_value.as_deref().filter(|v| !v.is_empty()) {
599 let field = match query.search_field.unwrap_or_default() {
600 SearchField::Email => "email",
601 SearchField::Name => "name",
602 };
603 let operator = match query.search_operator.unwrap_or_default() {
604 SearchOperator::Contains => WhereOperator::Contains,
605 SearchOperator::StartsWith => WhereOperator::StartsWith,
606 SearchOperator::EndsWith => WhereOperator::EndsWith,
607 };
608 conditions.push(text_match(&user_column(&ctx, field)?, operator, value)?);
609 }
610 if let Some(value) = &query.filter_value {
611 let column = user_column(&ctx, query.filter_field.as_deref().unwrap_or("email"))?;
612 let operator = query.filter_operator.unwrap_or_default();
613 conditions.push(match operator {
614 WhereOperator::Contains | WhereOperator::StartsWith | WhereOperator::EndsWith => {
615 text_match(&column, operator, value)?
616 }
617 _ => comparison(&column, operator, value)?,
618 });
619 }
620 let filter = conditions
621 .into_iter()
622 .reduce(Where::and)
623 .unwrap_or_else(Where::all);
624 let mut find = ctx.db().find::<User>(filter.clone());
625 if let Some(sort_by) = &query.sort_by {
626 let column = user_column(&ctx, sort_by)?;
627 let col = Col::<User, String>::new(column.name);
628 find = find.order_by(match query.sort_direction.unwrap_or_default() {
629 SortDirection::Asc => col.asc(),
630 SortDirection::Desc => col.desc(),
631 });
632 }
633 let total = ctx.db().count::<User>(filter).await?;
634 if let Some(offset) = query.offset {
635 find = find.offset(offset);
636 }
637 if let Some(limit) = query.limit {
638 find = find.limit(limit);
639 }
640 let users = find
641 .all_rows()
642 .await?
643 .into_iter()
644 .map(UserView::from_row)
645 .collect::<Result<_, _>>()
646 .map_err(AuthError::internal)?;
647 Ok(UserList {
648 users,
649 total,
650 limit: query.limit,
651 offset: query.offset,
652 })
653 }
654}
655
656#[derive(Clone, Debug, Deserialize)]
660pub struct GetUserQuery {
661 pub id: Id,
662}
663
664pub struct GetUser(pub(crate) Caller);
666
667impl<D: Adapter> Endpoint<D> for GetUser {
668 const METHOD: Method = Method::GET;
669 const PATH: &'static str = "/admin/get-user";
670 type Access = MaybeAuthenticated;
671 type Input = GetUserQuery;
672 type Output = UserView;
673
674 async fn call(
675 &self,
676 ctx: Ctx<D, MaybeAuthenticated>,
677 query: GetUserQuery,
678 ) -> Result<UserView, AuthError> {
679 self.0
680 .check(&ctx, "user", "get", AdminError::YouAreNotAllowedToGetUser)?;
681 find_user(&ctx, &query.id).await
682 }
683}
684
685#[derive(Clone, Debug, Deserialize)]
689#[serde(rename_all = "camelCase")]
690pub struct SetRoleInput {
691 pub user_id: Id,
692 pub role: Roles,
693}
694
695pub struct SetRole(pub(crate) Caller);
697
698impl<D: Adapter> Endpoint<D> for SetRole {
699 const METHOD: Method = Method::POST;
700 const PATH: &'static str = "/admin/set-role";
701 type Access = MaybeAuthenticated;
702 type Input = SetRoleInput;
703 type Output = UserOutput;
704
705 async fn call(
706 &self,
707 ctx: Ctx<D, MaybeAuthenticated>,
708 input: SetRoleInput,
709 ) -> Result<UserOutput, AuthError> {
710 let session = self.0.check(
711 &ctx,
712 "user",
713 "set-role",
714 AdminError::YouAreNotAllowedToChangeUsersRole,
715 )?;
716 let role = input.role.stored(&self.0.plugin)?;
717 let target = find_user(&ctx, &input.user_id).await?;
718 check_target(&self.0.plugin, session, &target)?;
719 ctx.db()
720 .update::<User>(User::ID.eq(&input.user_id))
721 .set(AdminUser::ROLE, Some(role))
722 .exec()
723 .await?;
724 updated(&ctx, &input.user_id).await
725 }
726}
727
728async fn updated<D: Adapter, A>(ctx: &Ctx<D, A>, user_id: &Id) -> Result<UserOutput, AuthError> {
730 ctx.emit(UserUpdated {
731 user_id: user_id.clone(),
732 });
733 Ok(UserOutput {
734 user: find_user(ctx, user_id).await?,
735 })
736}
737
738#[derive(Clone, Debug, Deserialize)]
742#[serde(rename_all = "camelCase")]
743pub struct BanUserInput {
744 pub user_id: Id,
745 #[serde(default)]
747 pub ban_reason: Option<String>,
748 #[serde(default)]
750 pub ban_expires_in: Option<i64>,
751}
752
753impl BanUserInput {
754 pub fn new(user_id: impl Into<Id>) -> Self {
756 Self {
757 user_id: user_id.into(),
758 ban_reason: None,
759 ban_expires_in: None,
760 }
761 }
762
763 pub fn reason(mut self, reason: impl Into<String>) -> Self {
765 self.ban_reason = Some(reason.into());
766 self
767 }
768
769 pub fn expires_in(mut self, duration: Duration) -> Self {
771 self.ban_expires_in = Some(duration.whole_seconds());
772 self
773 }
774}
775
776pub struct BanUser(pub(crate) Caller);
778
779impl<D: Adapter> Endpoint<D> for BanUser {
780 const METHOD: Method = Method::POST;
781 const PATH: &'static str = "/admin/ban-user";
782 type Access = MaybeAuthenticated;
783 type Input = BanUserInput;
784 type Output = UserOutput;
785
786 async fn call(
787 &self,
788 ctx: Ctx<D, MaybeAuthenticated>,
789 input: BanUserInput,
790 ) -> Result<UserOutput, AuthError> {
791 let plugin = &self.0.plugin;
792 let session = self
793 .0
794 .check(&ctx, "user", "ban", AdminError::YouAreNotAllowedToBanUsers)?;
795 let target = find_user(&ctx, &input.user_id).await?;
796 if session.is_some_and(|s| s.user.id == input.user_id) {
797 return Err(AdminError::YouCannotBanYourself.into());
798 }
799 check_target(plugin, session, &target)?;
800 let reason = input
801 .ban_reason
802 .filter(|r| !r.is_empty())
803 .or_else(|| plugin.default_ban_reason.clone())
804 .unwrap_or_else(|| "No reason".to_owned());
805 let expires = input
806 .ban_expires_in
807 .filter(|s| *s != 0)
808 .map(Duration::seconds)
809 .or(plugin.default_ban_expires_in)
810 .map(|d| ctx.now() + d);
811 ctx.db()
812 .update::<User>(User::ID.eq(&input.user_id))
813 .set(AdminUser::BANNED, true)
814 .set(AdminUser::BAN_REASON, Some(reason))
815 .set(AdminUser::BAN_EXPIRES, expires)
816 .exec()
817 .await?;
818 ctx.internal()
819 .revoke_user_sessions(&input.user_id, None)
820 .await?;
821 updated(&ctx, &input.user_id).await
822 }
823}
824
825pub struct UnbanUser(pub(crate) Caller);
829
830impl<D: Adapter> Endpoint<D> for UnbanUser {
831 const METHOD: Method = Method::POST;
832 const PATH: &'static str = "/admin/unban-user";
833 type Access = MaybeAuthenticated;
834 type Input = UserIdInput;
835 type Output = UserOutput;
836
837 async fn call(
838 &self,
839 ctx: Ctx<D, MaybeAuthenticated>,
840 input: UserIdInput,
841 ) -> Result<UserOutput, AuthError> {
842 self.0
843 .check(&ctx, "user", "ban", AdminError::YouAreNotAllowedToBanUsers)?;
844 find_user(&ctx, &input.user_id).await?;
845 lift_ban(&ctx, &input.user_id).await?;
846 updated(&ctx, &input.user_id).await
847 }
848}
849
850#[derive(Clone, Debug, Deserialize)]
854#[serde(rename_all = "camelCase")]
855pub struct UpdateUserInput {
856 pub user_id: Id,
857 pub data: Map<String, Json>,
859}
860
861pub struct UpdateUser(pub(crate) Caller);
865
866impl<D: Adapter> Endpoint<D> for UpdateUser {
867 const METHOD: Method = Method::POST;
868 const PATH: &'static str = "/admin/update-user";
869 type Access = MaybeAuthenticated;
870 type Input = UpdateUserInput;
871 type Output = UserView;
872
873 async fn call(
874 &self,
875 ctx: Ctx<D, MaybeAuthenticated>,
876 input: UpdateUserInput,
877 ) -> Result<UserView, AuthError> {
878 let caller = &self.0;
879 let session = caller.check(
880 &ctx,
881 "user",
882 "update",
883 AdminError::YouAreNotAllowedToUpdateUsers,
884 )?;
885 let data = input.data;
886 if data.is_empty() {
887 return Err(AdminError::NoDataToUpdate.into());
888 }
889 if data.contains_key("password") {
890 return Err(AdminError::PasswordCannotBeUpdatedViaUpdateUser.into());
891 }
892 if data.contains_key("id") {
893 return Err(AdminError::UserIdCannotBeUpdated.into());
894 }
895 let mut set = Vec::new();
896 if let Some(role) = data.get("role") {
897 caller.also(
898 session,
899 "user",
900 "set-role",
901 AdminError::YouAreNotAllowedToChangeUsersRole,
902 )?;
903 let role = Roles::from_json(role)?.stored(&caller.plugin)?;
904 set.push(("role", Value::Text(role)));
905 }
906 let banning = data.get("banned") == Some(&Json::Bool(true));
907 if BAN_COLUMNS.iter().any(|k| data.contains_key(*k)) {
908 caller.also(
909 session,
910 "user",
911 "ban",
912 AdminError::YouAreNotAllowedToBanUsers,
913 )?;
914 if banning && session.is_some_and(|s| s.user.id == input.user_id) {
915 return Err(AdminError::YouCannotBanYourself.into());
916 }
917 }
918 if data.contains_key("email") || data.contains_key("emailVerified") {
919 caller.also(
920 session,
921 "user",
922 "set-email",
923 AdminError::YouAreNotAllowedToSetUsersEmail,
924 )?;
925 }
926 let target = find_user(&ctx, &input.user_id).await?;
927 check_target(&caller.plugin, session, &target)?;
928 if let Some(email) = data.get("email") {
929 let email = normalize_email(email.as_str().unwrap_or_default())?;
930 let existing = ctx.internal().find_user_by_email(&email).await?;
931 if existing.is_some_and(|u| u.id != input.user_id) {
932 return Err(email_taken());
933 }
934 set.push(("email", Value::Text(email)));
935 }
936 for (key, json) in &data {
937 if matches!(key.as_str(), "role" | "email") {
938 continue;
939 }
940 let column = user_column(&ctx, key)?;
941 if matches!(column.name, "created_at" | "updated_at") {
942 return Err(invalid_field(format!("field `{key}` can't be set")));
943 }
944 set.push((column.name, column_value(&column, key, json)?));
945 }
946 let mut update = ctx.db().update::<User>(User::ID.eq(&input.user_id));
947 for (column, value) in set {
948 update = update.set_raw(column, value);
949 }
950 update.exec().await?;
951 if banning {
952 ctx.internal()
953 .revoke_user_sessions(&input.user_id, None)
954 .await?;
955 }
956 Ok(updated(&ctx, &input.user_id).await?.user)
957 }
958}
959
960#[derive(Clone, Debug, Deserialize)]
964#[serde(rename_all = "camelCase")]
965pub struct SetUserPasswordInput {
966 pub new_password: String,
967 pub user_id: Id,
968}
969
970pub struct SetUserPassword(pub(crate) Caller);
973
974impl<D: Adapter> Endpoint<D> for SetUserPassword {
975 const METHOD: Method = Method::POST;
976 const PATH: &'static str = "/admin/set-user-password";
977 type Access = MaybeAuthenticated;
978 type Input = SetUserPasswordInput;
979 type Output = Status;
980
981 async fn call(
982 &self,
983 ctx: Ctx<D, MaybeAuthenticated>,
984 input: SetUserPasswordInput,
985 ) -> Result<Status, AuthError> {
986 let session = self.0.check(
987 &ctx,
988 "user",
989 "set-password",
990 AdminError::YouAreNotAllowedToSetUsersPassword,
991 )?;
992 let internal = ctx.internal();
993 internal.validate_new_password(&input.new_password)?;
994 let target = find_user(&ctx, &input.user_id).await?;
995 check_target(&self.0.plugin, session, &target)?;
996 internal
997 .set_password(&input.user_id, &input.new_password)
998 .await?;
999 ctx.emit(PasswordChanged {
1000 user_id: input.user_id,
1001 });
1002 Ok(Status { status: true })
1003 }
1004}
1005
1006pub struct RemoveUser(pub(crate) Caller);
1012
1013impl<D: Adapter> Endpoint<D> for RemoveUser {
1014 const METHOD: Method = Method::POST;
1015 const PATH: &'static str = "/admin/remove-user";
1016 type Access = MaybeAuthenticated;
1017 type Input = UserIdInput;
1018 type Output = Success;
1019
1020 async fn call(
1021 &self,
1022 ctx: Ctx<D, MaybeAuthenticated>,
1023 input: UserIdInput,
1024 ) -> Result<Success, AuthError> {
1025 let session = self.0.check(
1026 &ctx,
1027 "user",
1028 "delete",
1029 AdminError::YouAreNotAllowedToDeleteUsers,
1030 )?;
1031 if session.is_some_and(|s| s.user.id == input.user_id) {
1032 return Err(AdminError::YouCannotRemoveYourself.into());
1033 }
1034 let user = find_user(&ctx, &input.user_id).await?;
1035 check_target(&self.0.plugin, session, &user)?;
1036 ctx.internal()
1037 .revoke_user_sessions(&input.user_id, None)
1038 .await?;
1039 ctx.db()
1040 .delete::<Account>(Account::USER_ID.eq(&input.user_id))
1041 .await?;
1042 ctx.db().delete::<User>(User::ID.eq(&input.user_id)).await?;
1043 ctx.emit(UserDeleted {
1044 user_id: input.user_id,
1045 email: user.email.clone(),
1046 });
1047 Ok(Success { success: true })
1048 }
1049}
1050
1051#[derive(Debug, Serialize)]
1055pub struct SessionList {
1056 pub sessions: Vec<Map<String, Json>>,
1057}
1058
1059pub struct ListUserSessions(pub(crate) Caller);
1061
1062impl<D: Adapter> Endpoint<D> for ListUserSessions {
1063 const METHOD: Method = Method::POST;
1064 const PATH: &'static str = "/admin/list-user-sessions";
1065 type Access = MaybeAuthenticated;
1066 type Input = UserIdInput;
1067 type Output = SessionList;
1068
1069 async fn call(
1070 &self,
1071 ctx: Ctx<D, MaybeAuthenticated>,
1072 input: UserIdInput,
1073 ) -> Result<SessionList, AuthError> {
1074 self.0.check(
1075 &ctx,
1076 "session",
1077 "list",
1078 AdminError::YouAreNotAllowedToListUsersSessions,
1079 )?;
1080 let rows = ctx
1081 .db()
1082 .find::<Session>(
1083 Session::USER_ID
1084 .eq(&input.user_id)
1085 .and(Session::EXPIRES_AT.gt(ctx.now())),
1086 )
1087 .order_by(Session::CREATED_AT.desc())
1088 .all_rows()
1089 .await?;
1090 Ok(SessionList {
1091 sessions: rows.iter().map(Row::to_client_json).collect(),
1092 })
1093 }
1094}
1095
1096#[derive(Clone, Debug, Deserialize)]
1098#[serde(rename_all = "camelCase")]
1099pub struct RevokeUserSessionInput {
1100 pub session_token: String,
1101}
1102
1103pub struct RevokeUserSession(pub(crate) Caller);
1106
1107impl<D: Adapter> Endpoint<D> for RevokeUserSession {
1108 const METHOD: Method = Method::POST;
1109 const PATH: &'static str = "/admin/revoke-user-session";
1110 type Access = MaybeAuthenticated;
1111 type Input = RevokeUserSessionInput;
1112 type Output = Success;
1113
1114 async fn call(
1115 &self,
1116 ctx: Ctx<D, MaybeAuthenticated>,
1117 input: RevokeUserSessionInput,
1118 ) -> Result<Success, AuthError> {
1119 let caller = self.0.check(
1120 &ctx,
1121 "session",
1122 "revoke",
1123 AdminError::YouAreNotAllowedToRevokeUsersSessions,
1124 )?;
1125 let found = ctx
1126 .db()
1127 .find::<Session>(Session::TOKEN_HASH.eq(Hash::sha256(&input.session_token)))
1128 .one()
1129 .await?;
1130 if let Some(session) = found {
1131 if let Some(owner) = ctx.internal().find_user_by_id(&session.user_id).await? {
1132 check_target(&self.0.plugin, caller, &owner)?;
1133 }
1134 ctx.internal()
1135 .revoke_session(&session.user_id, &session.id)
1136 .await?;
1137 }
1138 Ok(Success { success: true })
1139 }
1140}
1141
1142pub struct RevokeUserSessions(pub(crate) Caller);
1144
1145impl<D: Adapter> Endpoint<D> for RevokeUserSessions {
1146 const METHOD: Method = Method::POST;
1147 const PATH: &'static str = "/admin/revoke-user-sessions";
1148 type Access = MaybeAuthenticated;
1149 type Input = UserIdInput;
1150 type Output = Success;
1151
1152 async fn call(
1153 &self,
1154 ctx: Ctx<D, MaybeAuthenticated>,
1155 input: UserIdInput,
1156 ) -> Result<Success, AuthError> {
1157 let session = self.0.check(
1158 &ctx,
1159 "session",
1160 "revoke",
1161 AdminError::YouAreNotAllowedToRevokeUsersSessions,
1162 )?;
1163 if let Some(target) = ctx.internal().find_user_by_id(&input.user_id).await? {
1164 check_target(&self.0.plugin, session, &target)?;
1165 }
1166 ctx.internal()
1167 .revoke_user_sessions(&input.user_id, None)
1168 .await?;
1169 Ok(Success { success: true })
1170 }
1171}
1172
1173#[derive(Debug, Serialize)]
1177pub struct SessionOutput {
1178 pub session: Map<String, Json>,
1179 pub user: UserView,
1180}
1181
1182pub struct ImpersonateUser(pub(crate) Arc<Admin>);
1188
1189impl<D: Adapter> Endpoint<D> for ImpersonateUser {
1190 const METHOD: Method = Method::POST;
1191 const PATH: &'static str = "/admin/impersonate-user";
1192 type Access = Authenticated;
1193 type Input = UserIdInput;
1194 type Output = SessionOutput;
1195
1196 async fn call(
1197 &self,
1198 ctx: Ctx<D, Authenticated>,
1199 input: UserIdInput,
1200 ) -> Result<SessionOutput, AuthError> {
1201 let plugin = &self.0;
1202 let admin = ctx.session();
1203 let denied = || AuthError::from(AdminError::YouAreNotAllowedToImpersonateUsers);
1204 if !may(plugin, Some(admin), "user", "impersonate")? {
1205 return Err(denied());
1206 }
1207 let impersonating = admin
1208 .fields::<AdminSession>()
1209 .map_err(AuthError::internal)?
1210 .impersonated_by
1211 .is_some();
1212 let Some(admin_token) = admin.token.as_deref().filter(|_| !impersonating) else {
1213 return Err(denied());
1214 };
1215 let target = find_user(&ctx, &input.user_id).await?;
1216 let target_role = admin_fields(&target)?.role;
1217 if plugin.is_admin(&target.id, target_role.as_deref())
1218 && !may(plugin, Some(admin), "user", "impersonate-admins")?
1219 {
1220 return Err(AdminError::YouCannotImpersonateAdmins.into());
1221 }
1222 if let Some(err) = ban_error(plugin, &ctx, &target).await? {
1223 return Err(err);
1224 }
1225
1226 let now = ctx.now();
1227 let dont_remember = ctx.signed_cookie(DONT_REMEMBER_COOKIE).is_some();
1228 let remaining = admin.session.expires_at - now;
1229 ctx.set_signed_cookie(
1230 ADMIN_SESSION_COOKIE,
1231 &format!("{admin_token}:{}", if dont_remember { "1" } else { "" }),
1232 (!dont_remember).then_some(remaining),
1233 );
1234 let session = ctx.internal().create_session(&target.id, false).await?;
1235 let expires_at = now + plugin.impersonation_session_duration;
1236 ctx.db()
1237 .update::<Session>(Session::ID.eq(&session.session.id))
1238 .set(AdminSession::IMPERSONATED_BY, Some(admin.user.id.clone()))
1239 .set(Session::EXPIRES_AT, expires_at)
1240 .exec()
1241 .await?;
1242 let mut json = session.to_json();
1243 json.insert(
1244 "impersonatedBy".into(),
1245 Json::String(admin.user.id.to_string()),
1246 );
1247 json.insert("expiresAt".into(), Value::Timestamp(expires_at).to_json());
1248 Ok(SessionOutput {
1249 session: json,
1250 user: target,
1251 })
1252 }
1253}
1254
1255pub struct StopImpersonating;
1258
1259impl<D: Adapter> Endpoint<D> for StopImpersonating {
1260 const METHOD: Method = Method::POST;
1261 const PATH: &'static str = "/admin/stop-impersonating";
1262 type Access = Authenticated;
1263 type Input = Empty;
1264 type Output = SessionOutput;
1265
1266 async fn call(&self, ctx: Ctx<D, Authenticated>, _: Empty) -> Result<SessionOutput, AuthError> {
1267 let current = ctx.session();
1268 let admin_id = current
1269 .fields::<AdminSession>()
1270 .map_err(AuthError::internal)?
1271 .impersonated_by
1272 .ok_or(AdminError::NotImpersonating)?;
1273 let missing = || AuthError::internal("failed to find the admin session");
1274 let cookie = ctx
1275 .signed_cookie(ADMIN_SESSION_COOKIE)
1276 .ok_or_else(missing)?;
1277 let (token, dont_remember) = cookie.split_once(':').ok_or_else(missing)?;
1278 let row = ctx
1279 .db()
1280 .find::<Session>(Session::TOKEN_HASH.eq(Hash::sha256(token)))
1281 .one_row()
1282 .await?
1283 .ok_or_else(missing)?;
1284 let admin_session = Session::decode(&row).map_err(AuthError::internal)?;
1285 let now = ctx.now();
1286 if admin_session.user_id != admin_id || admin_session.expires_at <= now {
1287 return Err(missing());
1288 }
1289 let admin = find_user(&ctx, &admin_id).await?;
1290 ctx.internal()
1291 .revoke_session(¤t.user.id, ¤t.session.id)
1292 .await?;
1293
1294 let dont_remember = !dont_remember.is_empty();
1295 ctx.set_signed_cookie(
1296 SESSION_TOKEN_COOKIE,
1297 token,
1298 (!dont_remember).then_some(admin_session.expires_at - now),
1299 );
1300 if dont_remember {
1301 ctx.set_signed_cookie(DONT_REMEMBER_COOKIE, "true", None);
1302 } else {
1303 ctx.delete_cookie(DONT_REMEMBER_COOKIE);
1304 }
1305 ctx.delete_cookie(SESSION_CACHE_COOKIE);
1306 ctx.delete_cookie(ADMIN_SESSION_COOKIE);
1307 let mut session = row.to_client_json();
1308 session.insert("token".into(), Json::String(token.to_owned()));
1309 Ok(SessionOutput {
1310 session,
1311 user: admin,
1312 })
1313 }
1314}
1315
1316#[derive(Clone, Debug, Default, Deserialize)]
1321#[serde(rename_all = "camelCase")]
1322pub struct HasPermissionInput {
1323 #[serde(default)]
1324 pub user_id: Option<Id>,
1325 #[serde(default)]
1326 pub role: Option<String>,
1327 #[serde(default)]
1329 pub permission: Option<Permissions>,
1330 #[serde(default)]
1331 pub permissions: Option<Permissions>,
1332}
1333
1334#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
1336pub struct PermissionOutput {
1337 pub error: Option<String>,
1338 pub success: bool,
1339}
1340
1341pub struct HasPermission(pub(crate) Caller);
1344
1345impl<D: Adapter> Endpoint<D> for HasPermission {
1346 const METHOD: Method = Method::POST;
1347 const PATH: &'static str = "/admin/has-permission";
1348 type Access = MaybeAuthenticated;
1349 type Input = HasPermissionInput;
1350 type Output = PermissionOutput;
1351
1352 async fn call(
1353 &self,
1354 ctx: Ctx<D, MaybeAuthenticated>,
1355 input: HasPermissionInput,
1356 ) -> Result<PermissionOutput, AuthError> {
1357 let Some(permissions) = input.permissions.or(input.permission) else {
1358 return Err(AuthError::bad_request(
1359 codes::INVALID_BODY,
1360 "invalid permission check. no permission(s) were passed.",
1361 ));
1362 };
1363 let session = match ctx.session() {
1364 Some(session) => Some(session),
1365 None if self.0.server => None,
1366 None => return Err(AuthError::unauthorized()),
1367 };
1368 let (user_id, role) = match (session, input.role, input.user_id) {
1369 (Some(session), _, _) => (session.user.id.clone(), admin_fields(&session.user)?.role),
1370 (None, Some(role), user_id) => (user_id.unwrap_or_else(|| Id::from("")), Some(role)),
1371 (None, None, Some(user_id)) => {
1372 let user = ctx
1373 .internal()
1374 .find_user_by_id(&user_id)
1375 .await?
1376 .ok_or_else(|| {
1377 AuthError::bad_request(codes::USER_NOT_FOUND, "user not found")
1378 })?;
1379 (user_id, admin_fields(&user)?.role)
1380 }
1381 (None, None, None) => {
1382 return Err(AuthError::bad_request(
1383 codes::INVALID_BODY,
1384 "user id or role is required",
1385 ));
1386 }
1387 };
1388 Ok(PermissionOutput {
1389 error: None,
1390 success: self
1391 .0
1392 .plugin
1393 .has_permission(&user_id, role.as_deref(), &permissions),
1394 })
1395 }
1396}