Skip to main content

fastauth_plugin_admin/
endpoints.rs

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