protect_endpoints_core/
authorities.rs

1//! A set of traits and structures to check authorities.
2
3use std::collections::HashSet;
4use std::hash::Hash;
5use std::sync::Arc;
6
7mod attache;
8pub mod extractor;
9
10pub use attache::AttachAuthorities;
11
12/// Trait to check if the user has the required authorities.
13pub trait AuthoritiesCheck<T: Eq + Hash> {
14    fn has_authority(&self, authority: T) -> bool;
15    fn has_authorities(&self, authorities: &[T]) -> bool;
16    fn has_any_authority(&self, authorities: &[T]) -> bool;
17}
18
19/// Storage for user authorities to keep them as an extension of request.
20pub struct AuthDetails<T = String>
21where
22    T: Eq + Hash,
23{
24    pub authorities: Arc<HashSet<T>>,
25}
26
27impl<T: Eq + Hash> AuthDetails<T> {
28    pub fn new(authorities: impl IntoIterator<Item = T>) -> AuthDetails<T> {
29        AuthDetails {
30            authorities: Arc::new(authorities.into_iter().collect()),
31        }
32    }
33}
34
35impl<T: Eq + Hash> Clone for AuthDetails<T> {
36    fn clone(&self) -> Self {
37        Self {
38            authorities: self.authorities.clone(),
39        }
40    }
41}
42
43impl<T: Eq + Hash> AuthoritiesCheck<&T> for AuthDetails<T> {
44    fn has_authority(&self, authority: &T) -> bool {
45        self.authorities.contains(authority)
46    }
47
48    fn has_authorities(&self, authorities: &[&T]) -> bool {
49        authorities.iter().all(|auth| self.has_authority(auth))
50    }
51
52    fn has_any_authority(&self, authorities: &[&T]) -> bool {
53        authorities.iter().any(|auth| self.has_authority(auth))
54    }
55}
56
57impl AuthoritiesCheck<&str> for AuthDetails {
58    fn has_authority(&self, authority: &str) -> bool {
59        self.authorities.contains(authority)
60    }
61
62    fn has_authorities(&self, authorities: &[&str]) -> bool {
63        authorities.iter().all(|auth| self.has_authority(*auth))
64    }
65
66    fn has_any_authority(&self, authorities: &[&str]) -> bool {
67        authorities.iter().any(|auth| self.has_authority(*auth))
68    }
69}