create_rust_app/auth/extractors/
auth.rs

1use std::collections::HashSet;
2
3use crate::auth::{Permission, ID};
4
5#[allow(clippy::module_name_repetitions)]
6#[derive(Debug, Clone)]
7/// roles and permissions available to a User
8///
9/// use to control what users are and are not allowed to do
10pub struct Auth {
11    pub user_id: ID,
12    pub roles: HashSet<String>,
13    pub permissions: HashSet<Permission>,
14}
15
16impl Auth {
17    /// does the user with the id [`self.user_id`](`ID`) have the given `permission`
18    #[must_use]
19    pub fn has_permission(&self, permission: String) -> bool {
20        self.permissions.contains(&Permission {
21            permission,
22            from_role: String::new(),
23        })
24    }
25
26    /// does the user with the id [`self.user_id`](`ID`) have all of the given `perms`
27    #[must_use]
28    pub fn has_all_permissions(&self, perms: impl AsRef<[String]>) -> bool {
29        perms
30            .as_ref()
31            .iter()
32            .all(|p| self.has_permission(p.to_string()))
33    }
34
35    /// does the user with the id [`self.user_id`](`ID`) have any of the given `perms`
36    #[must_use]
37    pub fn has_any_permission(&self, perms: impl AsRef<[String]>) -> bool {
38        perms
39            .as_ref()
40            .iter()
41            .any(|p| self.has_permission(p.to_string()))
42    }
43
44    /// does the user with the id [`self.user_id`](`ID`) have the given `role`
45    #[must_use]
46    pub fn has_role(&self, role: impl AsRef<str>) -> bool {
47        self.roles.contains(role.as_ref())
48    }
49
50    /// does the user with the id [`self.user_id`](`ID`) have all of the given `roles`
51    #[must_use]
52    pub fn has_all_roles(&self, roles: impl AsRef<[String]>) -> bool {
53        roles.as_ref().iter().all(|r| self.has_role(r))
54    }
55
56    /// does the user with the id [`self.user_id`](`ID`) have any of the given `roles`
57    pub fn has_any_roles(&self, roles: impl AsRef<[String]>) -> bool {
58        roles.as_ref().iter().any(|r| self.has_role(r))
59    }
60}