use fastauth_core::plugin_prelude::*;
use fastauth_core::prelude::SessionData;
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(crate) fn require<R: Role, A: AuthInstance>(
auth: &A,
session: &SessionData<A::UserFields, A::Plugins>,
) -> Result<(), AuthError> {
let user = &session.view().user;
let role = user
.fields::<AdminUser>()
.map_err(AuthError::internal)?
.role;
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(())
}