#[cfg(feature = "axum")]
use std::future::Future;
use std::marker::PhantomData;
use std::ops::Deref;
#[cfg(feature = "axum")]
use ::axum::extract::{FromRef, FromRequestParts, RawPathParams};
#[cfg(feature = "axum")]
use ::axum::http::request::Parts;
use fastauth_core::plugin_prelude::StatusCode;
use fastauth_core::prelude::SessionData;
use fastauth_core::value::Id;
use fastauth_core::{AuthError, AuthInstance};
#[cfg(feature = "axum")]
use crate::Permission;
use crate::model::{Member, OrganizationSession};
use crate::{Organization, OrganizationError};
#[cfg(feature = "axum")]
pub trait OrgSource: Send + Sync + 'static {
fn organization_id(
parts: &mut Parts,
) -> impl Future<Output = Result<Option<Id>, AuthError>> + Send;
}
#[derive(Debug)]
pub struct Active;
#[cfg(feature = "axum")]
impl OrgSource for Active {
async fn organization_id(_parts: &mut Parts) -> Result<Option<Id>, AuthError> {
Ok(None)
}
}
pub trait PathParam: Send + Sync + 'static {
const NAME: &'static str;
}
#[macro_export]
macro_rules! path_param {
($vis:vis $name:ident = $param:literal) => {
#[derive(Debug)]
$vis struct $name;
impl $crate::extract::PathParam for $name {
const NAME: &'static str = $param;
}
};
}
pub struct FromPath<P>(PhantomData<fn() -> P>);
#[cfg(feature = "axum")]
impl<P: PathParam> OrgSource for FromPath<P> {
async fn organization_id(parts: &mut Parts) -> Result<Option<Id>, AuthError> {
let params = RawPathParams::from_request_parts(parts, &())
.await
.map_err(AuthError::internal)?;
params
.iter()
.find(|(name, _)| *name == P::NAME)
.map(|(_, value)| Some(Id::from(value)))
.ok_or_else(|| {
AuthError::internal(format!("the route has no `{{{}}}` parameter", P::NAME))
})
}
}
#[cfg(feature = "axum")]
async fn resolve<A, S, St>(
parts: &mut Parts,
state: &St,
permission: Option<(&'static str, &'static [&'static str])>,
) -> Result<Member, AuthError>
where
A: AuthInstance + FromRef<St>,
S: OrgSource,
St: Send + Sync,
{
let session = fastauth_axum::Session::<A>::from_request_parts(parts, state).await?;
let organization_id = S::organization_id(parts).await?;
membership(&A::from_ref(state), &session, organization_id, permission).await
}
pub(crate) async fn membership<A: AuthInstance>(
auth: &A,
session: &SessionData<A::UserFields, A::Plugins>,
organization_id: Option<Id>,
permission: Option<(&'static str, &'static [&'static str])>,
) -> Result<Member, AuthError> {
let organization_id = match organization_id {
Some(id) => id,
None => session
.view()
.fields::<OrganizationSession>()
.map_err(AuthError::internal)?
.active_organization_id
.ok_or_else(|| {
OrganizationError::NoActiveOrganization.with_status(StatusCode::FORBIDDEN)
})?,
};
let plugin = auth
.try_plugin::<Organization>()
.ok_or_else(|| AuthError::internal("the Organization plugin is not registered"))?;
let member = auth
.api()
.db()
.find::<Member>(
Member::ORGANIZATION_ID
.eq(&organization_id)
.and(Member::USER_ID.eq(&session.user.id)),
)
.one()
.await?
.ok_or(OrganizationError::YouAreNotAMemberOfThisOrganization)?;
if let Some((resource, actions)) = permission
&& !plugin.roles.allows(&member.role, &[(resource, actions)])
{
return Err(OrganizationError::PermissionDenied {
permission: format!("{resource}: [{}]", actions.join(", ")),
}
.into());
}
Ok(member)
}
pub struct OrgMember<A, S = Active> {
member: Member,
_marker: PhantomData<fn() -> (A, S)>,
}
pub type ActiveMember<A> = OrgMember<A, Active>;
impl<A, S> OrgMember<A, S> {
pub(crate) fn new(member: Member) -> Self {
Self {
member,
_marker: PhantomData,
}
}
pub fn into_inner(self) -> Member {
self.member
}
}
impl<A, S> Deref for OrgMember<A, S> {
type Target = Member;
fn deref(&self) -> &Member {
&self.member
}
}
#[cfg(feature = "axum")]
impl<A, S, St> FromRequestParts<St> for OrgMember<A, S>
where
A: AuthInstance + FromRef<St>,
S: OrgSource,
St: Send + Sync,
{
type Rejection = AuthError;
async fn from_request_parts(parts: &mut Parts, state: &St) -> Result<Self, AuthError> {
Ok(Self::new(resolve::<A, S, St>(parts, state, None).await?))
}
}
pub struct RequirePermission<A, P, S = Active> {
member: Member,
#[allow(clippy::type_complexity)]
_marker: PhantomData<fn() -> (A, P, S)>,
}
impl<A, P, S> RequirePermission<A, P, S> {
pub(crate) fn new(member: Member) -> Self {
Self {
member,
_marker: PhantomData,
}
}
pub fn into_inner(self) -> Member {
self.member
}
}
impl<A, P, S> Deref for RequirePermission<A, P, S> {
type Target = Member;
fn deref(&self) -> &Member {
&self.member
}
}
#[cfg(feature = "axum")]
impl<A, P, S, St> FromRequestParts<St> for RequirePermission<A, P, S>
where
A: AuthInstance + FromRef<St>,
P: Permission,
S: OrgSource,
St: Send + Sync,
{
type Rejection = AuthError;
async fn from_request_parts(parts: &mut Parts, state: &St) -> Result<Self, AuthError> {
Ok(Self::new(
resolve::<A, S, St>(parts, state, Some((P::RESOURCE, P::ACTIONS))).await?,
))
}
}