1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
//! A set of traits and structures for custom integration.
//!
//! Via [`PermissionsExtractor`] implementations, the library gets a user permissions from you.
//! The default implementation of the [`PermissionsExtractor`] is provided via a function.
//!
//! See [`GrantsMiddleware`] for more details.
//!
//! ## If you already have middleware authorization
//! You can integrate it with this library using [`AttachPermissions`]
//!
//!
//! [`PermissionsExtractor`]: PermissionsExtractor
//! [`AttachPermissions`]: AttachPermissions
//! [`GrantsMiddleware`]: actix_web_grants::GrantsMiddleware;

use actix_web::dev::Payload;
use actix_web::error::ErrorUnauthorized;
use actix_web::{Error, FromRequest, HttpMessage, HttpRequest};
use std::future::Future;
use std::pin::Pin;

mod attache;
mod extractors;

pub use attache::AttachPermissions;
pub use extractors::*;

#[derive(Clone)]
pub struct AuthDetails<T = String>
where
    T: PartialEq,
{
    pub permissions: Vec<T>,
}

impl<T> AuthDetails<T>
where
    T: PartialEq + Clone,
{
    pub fn new(permissions: Vec<T>) -> AuthDetails<T> {
        AuthDetails { permissions }
    }
}

pub trait PermissionsCheck<T: PartialEq> {
    fn has_permission(&self, permission: T) -> bool;
    fn has_permissions(&self, permissions: &[T]) -> bool;
    fn has_any_permission(&self, permissions: &[T]) -> bool;
}

impl<T: PartialEq + Clone> PermissionsCheck<&T> for AuthDetails<T> {
    fn has_permission(&self, permission: &T) -> bool {
        self.permissions.iter().any(|auth| auth == permission)
    }

    fn has_permissions(&self, permissions: &[&T]) -> bool {
        permissions.iter().all(|auth| self.has_permission(auth))
    }

    fn has_any_permission(&self, permissions: &[&T]) -> bool {
        permissions.iter().any(|auth| self.has_permission(auth))
    }
}

impl PermissionsCheck<&str> for AuthDetails {
    fn has_permission(&self, permission: &str) -> bool {
        self.permissions
            .iter()
            .any(|auth| auth.as_str() == permission)
    }

    fn has_permissions(&self, permissions: &[&str]) -> bool {
        permissions.iter().all(|auth| self.has_permission(*auth))
    }

    fn has_any_permission(&self, permissions: &[&str]) -> bool {
        permissions.iter().any(|auth| self.has_permission(*auth))
    }
}

pub trait RolesCheck<T> {
    fn has_role(&self, permission: T) -> bool;
    fn has_roles(&self, permissions: &[T]) -> bool;
    fn has_any_role(&self, permissions: &[T]) -> bool;
}

pub(crate) const ROLE_PREFIX: &str = "ROLE_";

impl RolesCheck<&str> for AuthDetails {
    fn has_role(&self, permission: &str) -> bool {
        let permission = format!("{}{}", ROLE_PREFIX, permission);

        self.permissions.iter().any(|auth| auth == &permission)
    }

    fn has_roles(&self, permissions: &[&str]) -> bool {
        permissions.iter().all(|auth| self.has_role(*auth))
    }

    fn has_any_role(&self, permissions: &[&str]) -> bool {
        permissions.iter().any(|auth| self.has_role(*auth))
    }
}

impl<T: PartialEq + Clone> RolesCheck<&T> for AuthDetails<T> {
    fn has_role(&self, permission: &T) -> bool {
        self.permissions.iter().any(|auth| auth == permission)
    }

    fn has_roles(&self, permissions: &[&T]) -> bool {
        permissions.iter().all(|auth| self.has_role(auth))
    }

    fn has_any_role(&self, permissions: &[&T]) -> bool {
        permissions.iter().any(|auth| self.has_role(auth))
    }
}

impl<T: PartialEq + Clone + 'static> FromRequest for AuthDetails<T> {
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self, Error>>>>;

    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
        let req = req.clone();

        Box::pin(async move {
            req.extensions()
                .get::<AuthDetails<T>>()
                .map(AuthDetails::clone)
                .ok_or_else(|| ErrorUnauthorized("User unauthorized!"))
        })
    }
}