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::Role;
12
13/// The signed-in session of a user who holds role `R`. Rejects with `401 UNAUTHORIZED`
14/// without a session and `403 FORBIDDEN` without the role. A user holds every role in
15/// their comma-separated `user.role` (the default role while it is empty); admins hold every
16/// configured admin role, so `RequireRole<A, role::Admin>` also lets `admin_user_ids` in.
17///
18/// ```ignore
19/// async fn dashboard(admin: RequireRole<AppAuth, role::Admin>) -> String {
20///     format!("hello {}", admin.user.email)
21/// }
22/// ```
23///
24/// Derefs to the [`Session`].
25pub struct RequireRole<A: AuthInstance, R>(Session<A>, PhantomData<fn() -> R>);
26
27impl<A: AuthInstance, R> RequireRole<A, R> {
28    /// The session.
29    pub fn into_session(self) -> Session<A> {
30        self.0
31    }
32}
33
34impl<A: AuthInstance, R> Clone for RequireRole<A, R> {
35    fn clone(&self) -> Self {
36        Self(self.0.clone(), PhantomData)
37    }
38}
39
40impl<A: AuthInstance, R> Deref for RequireRole<A, R> {
41    type Target = Session<A>;
42
43    fn deref(&self) -> &Session<A> {
44        &self.0
45    }
46}
47
48impl<A, R, S> FromRequestParts<S> for RequireRole<A, R>
49where
50    A: AuthInstance + FromRef<S>,
51    R: Role,
52    S: Send + Sync,
53{
54    type Rejection = AuthError;
55
56    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, AuthError> {
57        let session = Session::<A>::from_request_parts(parts, state).await?;
58        crate::roles::require::<R, A>(&A::from_ref(state), &session)?;
59        Ok(Self(session, PhantomData))
60    }
61}