fastauth_plugin_organization/
extract.rs1#[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#[cfg(feature = "axum")]
76pub trait OrgSource: Send + Sync + 'static {
77 fn organization_id(
79 parts: &mut Parts,
80 ) -> impl Future<Output = Result<Option<Id>, AuthError>> + Send;
81}
82
83#[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
94pub trait PathParam: Send + Sync + 'static {
97 const NAME: &'static str;
98}
99
100#[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
113pub 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
149pub(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
193pub struct OrgMember<A, S = Active> {
197 member: Member,
198 _marker: PhantomData<fn() -> (A, S)>,
199}
200
201pub 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
239pub 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}