Skip to main content

fastauth_plugin_admin/
axum.rs

1//! `RequireRole<A, R>`: an axum extractor that lets a route through only for a role.
2
3use std::marker::PhantomData;
4use std::ops::Deref;
5
6use axum::extract::{FromRef, FromRequestParts};
7use axum::http::request::Parts;
8use fastauth_axum::Session;
9use fastauth_core::plugin_prelude::*;
10
11use crate::{Admin, AdminUser};
12
13/// A role a route can require, named as it is stored in `user.role`. Implement it with
14/// [`role!`](crate::role!).
15pub trait Role: Send + Sync + 'static {
16    /// The role's name: `"admin"`, `"support"`.
17    const NAME: &'static str;
18
19    /// Whether a user with this id and `user.role` value holds the role. Default:
20    /// [`Admin::has_role`] with [`NAME`](Self::NAME).
21    fn held_by(admin: &Admin, user_id: &Id, role: Option<&str>) -> bool {
22        admin.has_role(user_id, role, Self::NAME)
23    }
24}
25
26/// The built-in roles, plus [`role!`](crate::role!) for your own.
27pub mod role {
28    /// Any admin: a holder of one of the configured admin roles, or a user in
29    /// `admin_user_ids`.
30    #[derive(Clone, Copy, Debug)]
31    pub struct Admin;
32
33    /// Holders of the `user` role, which every user gets by default.
34    #[derive(Clone, Copy, Debug)]
35    pub struct User;
36
37    impl super::Role for Admin {
38        const NAME: &'static str = "admin";
39
40        /// [`Admin::is_admin`](crate::Admin::is_admin), the check the admin endpoints use
41        /// too: whatever the configured admin roles are called.
42        fn held_by(admin: &crate::Admin, user_id: &super::Id, role: Option<&str>) -> bool {
43            admin.is_admin(user_id, role)
44        }
45    }
46
47    impl super::Role for User {
48        const NAME: &'static str = "user";
49    }
50
51    /// Declares a role marker for [`RequireRole`](crate::RequireRole):
52    ///
53    /// ```
54    /// fastauth_plugin_admin::role!(pub Support = "support");
55    /// ```
56    #[macro_export]
57    macro_rules! role {
58        ($(#[$meta:meta])* $vis:vis $name:ident = $role:literal) => {
59            $(#[$meta])*
60            #[derive(Clone, Copy, Debug)]
61            $vis struct $name;
62
63            impl $crate::Role for $name {
64                const NAME: &'static str = $role;
65            }
66        };
67    }
68
69    pub use role;
70}
71
72/// The signed-in session of a user who holds role `R`. Rejects with `401 UNAUTHORIZED`
73/// without a session and `403 FORBIDDEN` without the role. A user holds every role in
74/// their comma-separated `user.role` (the default role while it is empty); admins hold every
75/// configured admin role, so `RequireRole<A, role::Admin>` also lets `admin_user_ids` in.
76///
77/// ```ignore
78/// async fn dashboard(admin: RequireRole<AppAuth, role::Admin>) -> String {
79///     format!("hello {}", admin.user.email)
80/// }
81/// ```
82///
83/// Derefs to the [`Session`].
84pub struct RequireRole<A: AuthInstance, R>(Session<A>, PhantomData<fn() -> R>);
85
86impl<A: AuthInstance, R> RequireRole<A, R> {
87    /// The session.
88    pub fn into_session(self) -> Session<A> {
89        self.0
90    }
91}
92
93impl<A: AuthInstance, R> Clone for RequireRole<A, R> {
94    fn clone(&self) -> Self {
95        Self(self.0.clone(), PhantomData)
96    }
97}
98
99impl<A: AuthInstance, R> Deref for RequireRole<A, R> {
100    type Target = Session<A>;
101
102    fn deref(&self) -> &Session<A> {
103        &self.0
104    }
105}
106
107impl<A, R, S> FromRequestParts<S> for RequireRole<A, R>
108where
109    A: AuthInstance + FromRef<S>,
110    R: Role,
111    S: Send + Sync,
112{
113    type Rejection = AuthError;
114
115    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, AuthError> {
116        let session = Session::<A>::from_request_parts(parts, state).await?;
117        let user = &session.view().user;
118        let role = user
119            .fields::<AdminUser>()
120            .map_err(AuthError::internal)?
121            .role;
122        let auth = A::from_ref(state);
123        let plugin = auth
124            .try_plugin::<Admin>()
125            .ok_or_else(|| AuthError::internal("RequireRole needs the admin plugin registered"))?;
126        if !R::held_by(plugin, &user.id, role.as_deref()) {
127            return Err(AuthError::forbidden());
128        }
129        Ok(Self(session, PhantomData))
130    }
131}