axum_gate/authz/
access_scope.rs

1use super::AccessHierarchy;
2
3use tracing::debug;
4
5/// Contains information about the granted access scope.
6#[derive(Debug, Clone)]
7pub struct AccessScope<Role> {
8    /// The role attached to the scope.
9    pub role: Role,
10    /// Whether all supervisors are granted access.
11    pub allow_supervisor_access: bool,
12}
13
14impl<Role> AccessScope<Role>
15where
16    Role: AccessHierarchy + Eq + std::fmt::Display,
17{
18    /// Creates a new scope with the given role.
19    pub fn new(role: Role) -> Self {
20        Self {
21            role,
22            allow_supervisor_access: false,
23        }
24    }
25
26    /// Returns `true` if the given role matches the scope.
27    pub fn grants_role(&self, role: &Role) -> bool {
28        self.role.eq(role)
29    }
30
31    /// Returns `true` if the given role is the required role or a supervisor
32    /// (higher privilege according to the total ordering) of it.
33    ///
34    /// Ordering contract (enforced by AccessHierarchy marker):
35    /// Higher privilege > Lower privilege
36    /// So a supervisor (or same role) satisfies: user_role >= required_role
37    pub fn grants_supervisor(&self, role: &Role) -> bool {
38        if !self.allow_supervisor_access {
39            debug!(
40                "Scope for role {} does not allow supervisor access.",
41                self.role
42            );
43            return false;
44        }
45
46        if role >= &self.role {
47            debug!(
48                "Role {role} is same or supervisor of required role {} – access granted.",
49                self.role
50            );
51            true
52        } else {
53            debug!(
54                "Role {role} is NOT a supervisor of required role {} – access denied.",
55                self.role
56            );
57            false
58        }
59    }
60
61    /// Allows access to all supervisor of the role of the scope.
62    pub fn allow_supervisor(mut self) -> Self {
63        self.allow_supervisor_access = true;
64        self
65    }
66}