use std::marker::PhantomData;
use std::ops::Deref;
use axum::extract::{FromRef, FromRequestParts};
use axum::http::request::Parts;
use fastauth_axum::Session;
use fastauth_core::plugin_prelude::*;
use crate::Role;
pub struct RequireRole<A: AuthInstance, R>(Session<A>, PhantomData<fn() -> R>);
impl<A: AuthInstance, R> RequireRole<A, R> {
pub fn into_session(self) -> Session<A> {
self.0
}
}
impl<A: AuthInstance, R> Clone for RequireRole<A, R> {
fn clone(&self) -> Self {
Self(self.0.clone(), PhantomData)
}
}
impl<A: AuthInstance, R> Deref for RequireRole<A, R> {
type Target = Session<A>;
fn deref(&self) -> &Session<A> {
&self.0
}
}
impl<A, R, S> FromRequestParts<S> for RequireRole<A, R>
where
A: AuthInstance + FromRef<S>,
R: Role,
S: Send + Sync,
{
type Rejection = AuthError;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, AuthError> {
let session = Session::<A>::from_request_parts(parts, state).await?;
crate::roles::require::<R, A>(&A::from_ref(state), &session)?;
Ok(Self(session, PhantomData))
}
}