fastauth_plugin_admin/
roles.rs1use fastauth_core::plugin_prelude::*;
4use fastauth_core::prelude::SessionData;
5
6use crate::{Admin, AdminUser};
7
8pub trait Role: Send + Sync + 'static {
11 const NAME: &'static str;
13
14 fn held_by(admin: &Admin, user_id: &Id, role: Option<&str>) -> bool {
17 admin.has_role(user_id, role, Self::NAME)
18 }
19}
20
21pub mod role {
23 #[derive(Clone, Copy, Debug)]
26 pub struct Admin;
27
28 #[derive(Clone, Copy, Debug)]
30 pub struct User;
31
32 impl super::Role for Admin {
33 const NAME: &'static str = "admin";
34
35 fn held_by(admin: &crate::Admin, user_id: &super::Id, role: Option<&str>) -> bool {
38 admin.is_admin(user_id, role)
39 }
40 }
41
42 impl super::Role for User {
43 const NAME: &'static str = "user";
44 }
45
46 #[macro_export]
52 macro_rules! role {
53 ($(#[$meta:meta])* $vis:vis $name:ident = $role:literal) => {
54 $(#[$meta])*
55 #[derive(Clone, Copy, Debug)]
56 $vis struct $name;
57
58 impl $crate::Role for $name {
59 const NAME: &'static str = $role;
60 }
61 };
62 }
63
64 pub use role;
65}
66
67pub(crate) fn require<R: Role, A: AuthInstance>(
70 auth: &A,
71 session: &SessionData<A::UserFields, A::Plugins>,
72) -> Result<(), AuthError> {
73 let user = &session.view().user;
74 let role = user
75 .fields::<AdminUser>()
76 .map_err(AuthError::internal)?
77 .role;
78 let plugin = auth
79 .try_plugin::<Admin>()
80 .ok_or_else(|| AuthError::internal("RequireRole needs the admin plugin registered"))?;
81 if !R::held_by(plugin, &user.id, role.as_deref()) {
82 return Err(AuthError::forbidden());
83 }
84 Ok(())
85}