fastauth_plugin_admin/
axum.rs1use std::marker::PhantomData;
4use std::ops::Deref;
5
6use axum::extract::{FromRef, FromRequestParts};
7use axum::http::request::Parts;
8use fastauth_axum::Session;
9use fastauth_core::plugin_prelude::*;
10
11use crate::{Admin, AdminUser};
12
13pub trait Role: Send + Sync + 'static {
16 const NAME: &'static str;
18
19 fn held_by(admin: &Admin, user_id: &Id, role: Option<&str>) -> bool {
22 admin.has_role(user_id, role, Self::NAME)
23 }
24}
25
26pub mod role {
28 #[derive(Clone, Copy, Debug)]
31 pub struct Admin;
32
33 #[derive(Clone, Copy, Debug)]
35 pub struct User;
36
37 impl super::Role for Admin {
38 const NAME: &'static str = "admin";
39
40 fn held_by(admin: &crate::Admin, user_id: &super::Id, role: Option<&str>) -> bool {
43 admin.is_admin(user_id, role)
44 }
45 }
46
47 impl super::Role for User {
48 const NAME: &'static str = "user";
49 }
50
51 #[macro_export]
57 macro_rules! role {
58 ($(#[$meta:meta])* $vis:vis $name:ident = $role:literal) => {
59 $(#[$meta])*
60 #[derive(Clone, Copy, Debug)]
61 $vis struct $name;
62
63 impl $crate::Role for $name {
64 const NAME: &'static str = $role;
65 }
66 };
67 }
68
69 pub use role;
70}
71
72pub struct RequireRole<A: AuthInstance, R>(Session<A>, PhantomData<fn() -> R>);
85
86impl<A: AuthInstance, R> RequireRole<A, R> {
87 pub fn into_session(self) -> Session<A> {
89 self.0
90 }
91}
92
93impl<A: AuthInstance, R> Clone for RequireRole<A, R> {
94 fn clone(&self) -> Self {
95 Self(self.0.clone(), PhantomData)
96 }
97}
98
99impl<A: AuthInstance, R> Deref for RequireRole<A, R> {
100 type Target = Session<A>;
101
102 fn deref(&self) -> &Session<A> {
103 &self.0
104 }
105}
106
107impl<A, R, S> FromRequestParts<S> for RequireRole<A, R>
108where
109 A: AuthInstance + FromRef<S>,
110 R: Role,
111 S: Send + Sync,
112{
113 type Rejection = AuthError;
114
115 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, AuthError> {
116 let session = Session::<A>::from_request_parts(parts, state).await?;
117 let user = &session.view().user;
118 let role = user
119 .fields::<AdminUser>()
120 .map_err(AuthError::internal)?
121 .role;
122 let auth = A::from_ref(state);
123 let plugin = auth
124 .try_plugin::<Admin>()
125 .ok_or_else(|| AuthError::internal("RequireRole needs the admin plugin registered"))?;
126 if !R::held_by(plugin, &user.id, role.as_deref()) {
127 return Err(AuthError::forbidden());
128 }
129 Ok(Self(session, PhantomData))
130 }
131}