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
use crate::permissions::{AuthDetails, PermissionsCheck};
use actix_web::dev::RequestHead;
use actix_web::guard::Guard;

/// Implementation of Guard trait for validate permissions
/// ```
/// use actix_web::dev::ServiceRequest;
/// use actix_web::{web, App, Error, HttpResponse, HttpServer};
///
/// use actix_web_grants::{GrantsMiddleware, PermissionGuard};
/// use std::sync::Arc;
///
/// fn main() {
///     HttpServer::new(|| {
///         App::new()
///             .wrap(GrantsMiddleware::with_extractor(extract))
///             .service(web::resource("/admin")
///                     .to(|| async { HttpResponse::Ok().finish() })
///                     .guard(PermissionGuard::new("ROLE_ADMIN".to_string())))
///     });
/// }
///
/// async fn extract(_req: &ServiceRequest) -> Result<Vec<String>, Error> {
///    // Here is a place for your code to get user permissions/grants/permissions from a request
///    // For example from a token or database
///
///    // Stub example
///    Ok(vec!["ROLE_ADMIN".to_string()])
/// }
/// ```
pub struct PermissionGuard {
    allow_permission: String,
}

impl PermissionGuard {
    pub fn new(allow_permission: String) -> PermissionGuard {
        PermissionGuard { allow_permission }
    }
}

impl Guard for PermissionGuard {
    fn check(&self, request: &RequestHead) -> bool {
        request
            .extensions()
            .get::<AuthDetails>()
            .filter(|details| details.has_permission(self.allow_permission.as_str()))
            .is_some()
    }
}