Skip to main content

fastauth_plugin_organization/
extract.rs

1//! axum extractors for organization membership and permissions (feature `axum`).
2//!
3//! ```
4//! use fastauth_core::prelude::*;
5//! use fastauth_plugin_organization::extract::{ActiveMember, FromPath, OrgMember, RequirePermission};
6//! use fastauth_plugin_organization::{Organization, access::MemberDelete, path_param};
7//!
8//! type AppAuth = Auth<MemoryAdapter, (), plugins![Organization]>;
9//!
10//! path_param!(pub OrgId = "org_id");
11//!
12//! // The session's active organization; 403 without one or without a membership.
13//! async fn dashboard(member: ActiveMember<AppAuth>) -> String {
14//!     member.role.clone()
15//! }
16//!
17//! // `/orgs/{org_id}/...`: the membership in the organization the path names.
18//! async fn org_page(member: OrgMember<AppAuth, FromPath<OrgId>>) -> String {
19//!     member.organization_id.to_string()
20//! }
21//!
22//! // 403 unless the member's role grants `member: [delete]`.
23//! async fn remove(member: RequirePermission<AppAuth, MemberDelete>) -> String {
24//!     member.user_id.to_string()
25//! }
26//!
27//! let _app: axum::Router<AppAuth> = axum::Router::new()
28//!     .route("/dashboard", axum::routing::get(dashboard))
29//!     .route("/orgs/{org_id}", axum::routing::get(org_page))
30//!     .route("/members", axum::routing::delete(remove));
31//! ```
32//!
33//! `OrgMember<A, FromPath<"org_id">>` would need `&str` const generics, which stable Rust
34//! doesn't have, so the parameter name is a type implementing [`PathParam`], written with
35//! [`path_param!`](crate::path_param).
36//!
37//! Each extractor reads the session through `fastauth_axum::Session`, so it shares that
38//! request's single session lookup. It then loads the membership with one query and checks
39//! permissions with the plugin's configured roles (`AuthInstance::try_plugin`), through the
40//! same function as the endpoints, [`Roles::allows`](crate::Roles::allows).
41
42use std::future::Future;
43use std::marker::PhantomData;
44use std::ops::Deref;
45
46use ::axum::extract::{FromRef, FromRequestParts, RawPathParams};
47use ::axum::http::StatusCode;
48use ::axum::http::request::Parts;
49use fastauth_axum::Session;
50use fastauth_core::value::Id;
51use fastauth_core::{AuthError, AuthInstance};
52
53use crate::model::{Member, OrganizationSession};
54use crate::{Organization, OrganizationError, Permission};
55
56/// Where an extractor finds the organization.
57pub trait OrgSource: Send + Sync + 'static {
58    /// The organization id, or `None` for the session's active organization.
59    fn organization_id(
60        parts: &mut Parts,
61    ) -> impl Future<Output = Result<Option<Id>, AuthError>> + Send;
62}
63
64/// The session's active organization, set with `/organization/set-active`.
65#[derive(Debug)]
66pub struct Active;
67
68impl OrgSource for Active {
69    async fn organization_id(_parts: &mut Parts) -> Result<Option<Id>, AuthError> {
70        Ok(None)
71    }
72}
73
74/// Names a route's path parameter for [`FromPath`]. Write one with
75/// [`path_param!`](crate::path_param).
76pub trait PathParam: Send + Sync + 'static {
77    const NAME: &'static str;
78}
79
80/// Declares a [`PathParam`] type: `path_param!(pub OrgId = "org_id");`.
81#[macro_export]
82macro_rules! path_param {
83    ($vis:vis $name:ident = $param:literal) => {
84        #[derive(Debug)]
85        $vis struct $name;
86
87        impl $crate::extract::PathParam for $name {
88            const NAME: &'static str = $param;
89        }
90    };
91}
92
93/// The organization id in the path parameter `P::NAME`. A route without that parameter is
94/// a programming error and answers 500.
95pub struct FromPath<P>(PhantomData<fn() -> P>);
96
97impl<P: PathParam> OrgSource for FromPath<P> {
98    async fn organization_id(parts: &mut Parts) -> Result<Option<Id>, AuthError> {
99        let params = RawPathParams::from_request_parts(parts, &())
100            .await
101            .map_err(AuthError::internal)?;
102        params
103            .iter()
104            .find(|(name, _)| *name == P::NAME)
105            .map(|(_, value)| Some(Id::from(value)))
106            .ok_or_else(|| {
107                AuthError::internal(format!("the route has no `{{{}}}` parameter", P::NAME))
108            })
109    }
110}
111
112async fn resolve<A, S, St>(
113    parts: &mut Parts,
114    state: &St,
115    permission: Option<(&'static str, &'static [&'static str])>,
116) -> Result<Member, AuthError>
117where
118    A: AuthInstance + FromRef<St>,
119    S: OrgSource,
120    St: Send + Sync,
121{
122    let session = Session::<A>::from_request_parts(parts, state).await?;
123    let organization_id = match S::organization_id(parts).await? {
124        Some(id) => id,
125        None => session
126            .view()
127            .fields::<OrganizationSession>()
128            .map_err(AuthError::internal)?
129            .active_organization_id
130            .ok_or_else(|| {
131                OrganizationError::NoActiveOrganization.with_status(StatusCode::FORBIDDEN)
132            })?,
133    };
134    let auth = A::from_ref(state);
135    let plugin = auth
136        .try_plugin::<Organization>()
137        .ok_or_else(|| AuthError::internal("the Organization plugin is not registered"))?;
138    let member = auth
139        .api()
140        .db()
141        .find::<Member>(
142            Member::ORGANIZATION_ID
143                .eq(&organization_id)
144                .and(Member::USER_ID.eq(&session.user.id)),
145        )
146        .one()
147        .await?
148        .ok_or(OrganizationError::YouAreNotAMemberOfThisOrganization)?;
149    if let Some((resource, actions)) = permission
150        && !plugin.roles.allows(&member.role, &[(resource, actions)])
151    {
152        return Err(OrganizationError::PermissionDenied {
153            permission: format!("{resource}: [{}]", actions.join(", ")),
154        }
155        .into());
156    }
157    Ok(member)
158}
159
160/// The signed-in user's membership in the organization `S` names. Rejects with 401 without
161/// a session, 403 `NO_ACTIVE_ORGANIZATION` when `S` is [`Active`] and none is set, and 403
162/// `YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION`. Derefs to [`Member`].
163pub struct OrgMember<A, S = Active> {
164    member: Member,
165    _marker: PhantomData<fn() -> (A, S)>,
166}
167
168/// The membership in the session's active organization.
169pub type ActiveMember<A> = OrgMember<A, Active>;
170
171impl<A, S> OrgMember<A, S> {
172    pub fn into_inner(self) -> Member {
173        self.member
174    }
175}
176
177impl<A, S> Deref for OrgMember<A, S> {
178    type Target = Member;
179
180    fn deref(&self) -> &Member {
181        &self.member
182    }
183}
184
185impl<A, S, St> FromRequestParts<St> for OrgMember<A, S>
186where
187    A: AuthInstance + FromRef<St>,
188    S: OrgSource,
189    St: Send + Sync,
190{
191    type Rejection = AuthError;
192
193    async fn from_request_parts(parts: &mut Parts, state: &St) -> Result<Self, AuthError> {
194        Ok(Self {
195            member: resolve::<A, S, St>(parts, state, None).await?,
196            _marker: PhantomData,
197        })
198    }
199}
200
201/// Like [`OrgMember`], and also 403 `PERMISSION_DENIED` unless the member's role grants
202/// permission `P`.
203pub struct RequirePermission<A, P, S = Active> {
204    member: Member,
205    #[allow(clippy::type_complexity)]
206    _marker: PhantomData<fn() -> (A, P, S)>,
207}
208
209impl<A, P, S> RequirePermission<A, P, S> {
210    pub fn into_inner(self) -> Member {
211        self.member
212    }
213}
214
215impl<A, P, S> Deref for RequirePermission<A, P, S> {
216    type Target = Member;
217
218    fn deref(&self) -> &Member {
219        &self.member
220    }
221}
222
223impl<A, P, S, St> FromRequestParts<St> for RequirePermission<A, P, S>
224where
225    A: AuthInstance + FromRef<St>,
226    P: Permission,
227    S: OrgSource,
228    St: Send + Sync,
229{
230    type Rejection = AuthError;
231
232    async fn from_request_parts(parts: &mut Parts, state: &St) -> Result<Self, AuthError> {
233        Ok(Self {
234            member: resolve::<A, S, St>(parts, state, Some((P::RESOURCE, P::ACTIONS))).await?,
235            _marker: PhantomData,
236        })
237    }
238}