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::{Admin, AdminUser};
pub trait Role: Send + Sync + 'static {
const NAME: &'static str;
fn held_by(admin: &Admin, user_id: &Id, role: Option<&str>) -> bool {
admin.has_role(user_id, role, Self::NAME)
}
}
pub mod role {
#[derive(Clone, Copy, Debug)]
pub struct Admin;
#[derive(Clone, Copy, Debug)]
pub struct User;
impl super::Role for Admin {
const NAME: &'static str = "admin";
fn held_by(admin: &crate::Admin, user_id: &super::Id, role: Option<&str>) -> bool {
admin.is_admin(user_id, role)
}
}
impl super::Role for User {
const NAME: &'static str = "user";
}
#[macro_export]
macro_rules! role {
($(#[$meta:meta])* $vis:vis $name:ident = $role:literal) => {
$(#[$meta])*
#[derive(Clone, Copy, Debug)]
$vis struct $name;
impl $crate::Role for $name {
const NAME: &'static str = $role;
}
};
}
pub use 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?;
let user = &session.view().user;
let role = user
.fields::<AdminUser>()
.map_err(AuthError::internal)?
.role;
let auth = A::from_ref(state);
let plugin = auth
.try_plugin::<Admin>()
.ok_or_else(|| AuthError::internal("RequireRole needs the admin plugin registered"))?;
if !R::held_by(plugin, &user.id, role.as_deref()) {
return Err(AuthError::forbidden());
}
Ok(Self(session, PhantomData))
}
}