Skip to main content

fastauth_plugin_admin/
roles.rs

1//! Role markers for the `RequireRole` extractors (features `axum` and `actix`).
2
3use fastauth_core::plugin_prelude::*;
4use fastauth_core::prelude::SessionData;
5
6use crate::{Admin, AdminUser};
7
8/// A role a route can require, named as it is stored in `user.role`. Implement it with
9/// [`role!`](crate::role!).
10pub trait Role: Send + Sync + 'static {
11    /// The role's name: `"admin"`, `"support"`.
12    const NAME: &'static str;
13
14    /// Whether a user with this id and `user.role` value holds the role. Default:
15    /// [`Admin::has_role`] with [`NAME`](Self::NAME).
16    fn held_by(admin: &Admin, user_id: &Id, role: Option<&str>) -> bool {
17        admin.has_role(user_id, role, Self::NAME)
18    }
19}
20
21/// The built-in roles, plus [`role!`](crate::role!) for your own.
22pub mod role {
23    /// Any admin: a holder of one of the configured admin roles, or a user in
24    /// `admin_user_ids`.
25    #[derive(Clone, Copy, Debug)]
26    pub struct Admin;
27
28    /// Holders of the `user` role, which every user gets by default.
29    #[derive(Clone, Copy, Debug)]
30    pub struct User;
31
32    impl super::Role for Admin {
33        const NAME: &'static str = "admin";
34
35        /// [`Admin::is_admin`](crate::Admin::is_admin), the check the admin endpoints use
36        /// too: whatever the configured admin roles are called.
37        fn held_by(admin: &crate::Admin, user_id: &super::Id, role: Option<&str>) -> bool {
38            admin.is_admin(user_id, role)
39        }
40    }
41
42    impl super::Role for User {
43        const NAME: &'static str = "user";
44    }
45
46    /// Declares a role marker for the `RequireRole` extractors:
47    ///
48    /// ```
49    /// fastauth_plugin_admin::role!(pub Support = "support");
50    /// ```
51    #[macro_export]
52    macro_rules! role {
53        ($(#[$meta:meta])* $vis:vis $name:ident = $role:literal) => {
54            $(#[$meta])*
55            #[derive(Clone, Copy, Debug)]
56            $vis struct $name;
57
58            impl $crate::Role for $name {
59                const NAME: &'static str = $role;
60            }
61        };
62    }
63
64    pub use role;
65}
66
67/// `Ok` when the session's user holds role `R`, else `403 FORBIDDEN`. Both integrations'
68/// `RequireRole` end here.
69pub(crate) fn require<R: Role, A: AuthInstance>(
70    auth: &A,
71    session: &SessionData<A::UserFields, A::Plugins>,
72) -> Result<(), AuthError> {
73    let user = &session.view().user;
74    let role = user
75        .fields::<AdminUser>()
76        .map_err(AuthError::internal)?
77        .role;
78    let plugin = auth
79        .try_plugin::<Admin>()
80        .ok_or_else(|| AuthError::internal("RequireRole needs the admin plugin registered"))?;
81    if !R::held_by(plugin, &user.id, role.as_deref()) {
82        return Err(AuthError::forbidden());
83    }
84    Ok(())
85}