actix_web_grants/
guards.rs

1use crate::permissions::{AuthDetails, PermissionsCheck};
2use actix_web::guard::{Guard, GuardContext};
3
4/// Implementation of Guard trait for validate permissions
5/// ```
6/// use actix_web::dev::ServiceRequest;
7/// use actix_web::{web, App, Error, HttpResponse, HttpServer};
8///
9/// use actix_web_grants::{GrantsMiddleware, PermissionGuard};
10/// use std::sync::Arc;
11///
12/// fn main() {
13///     HttpServer::new(|| {
14///         App::new()
15///             .wrap(GrantsMiddleware::with_extractor(extract))
16///             .service(web::resource("/admin")
17///                     .to(|| async { HttpResponse::Ok().finish() })
18///                     .guard(PermissionGuard::new("ROLE_ADMIN".to_string())))
19///     });
20/// }
21///
22/// async fn extract(_req: &ServiceRequest) -> Result<Vec<String>, Error> {
23///    // Here is a place for your code to get user permissions/grants/permissions from a request
24///    // For example from a token or database
25///
26///    // Stub example
27///    Ok(vec!["ROLE_ADMIN".to_string()])
28/// }
29/// ```
30pub struct PermissionGuard<Type> {
31    allow_permission: Type,
32}
33
34impl<Type: PartialEq + Clone + 'static> PermissionGuard<Type> {
35    pub fn new(allow_permission: Type) -> PermissionGuard<Type> {
36        PermissionGuard { allow_permission }
37    }
38}
39
40impl<Type: PartialEq + Clone + 'static> Guard for PermissionGuard<Type> {
41    fn check(&self, request: &GuardContext) -> bool {
42        request
43            .req_data()
44            .get::<AuthDetails<Type>>()
45            .filter(|details| details.has_permission(&self.allow_permission))
46            .is_some()
47    }
48}