fastauth_plugin_organization/
extract.rs1use 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
56pub trait OrgSource: Send + Sync + 'static {
58 fn organization_id(
60 parts: &mut Parts,
61 ) -> impl Future<Output = Result<Option<Id>, AuthError>> + Send;
62}
63
64#[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
74pub trait PathParam: Send + Sync + 'static {
77 const NAME: &'static str;
78}
79
80#[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
93pub 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
160pub struct OrgMember<A, S = Active> {
164 member: Member,
165 _marker: PhantomData<fn() -> (A, S)>,
166}
167
168pub 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
201pub 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}