Skip to main content

fastauth_plugin_organization/
extract.rs

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