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
use actix_web::dev::ServiceRequest;
use actix_web::Error;
use std::future::Future;

pub trait PermissionsExtractor<'a, Req, Type> {
    type Future: Future<Output = Result<Vec<Type>, Error>>;

    fn extract(&self, request: &'a mut ServiceRequest) -> Self::Future;
}

impl<'a, F, O, Type> PermissionsExtractor<'a, &ServiceRequest, Type> for F
where
    F: Fn(&'a ServiceRequest) -> O,
    O: Future<Output = Result<Vec<Type>, Error>>,
    Type: PartialEq + Clone + 'static,
{
    type Future = O;

    fn extract(&self, req: &'a mut ServiceRequest) -> Self::Future {
        (self)(req)
    }
}

impl<'a, F, O, Type> PermissionsExtractor<'a, &mut ServiceRequest, Type> for F
where
    F: Fn(&'a mut ServiceRequest) -> O,
    O: Future<Output = Result<Vec<Type>, Error>>,
    Type: PartialEq + Clone + 'static,
{
    type Future = O;

    fn extract(&self, req: &'a mut ServiceRequest) -> Self::Future {
        (self)(req)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::dev::ServiceRequest;
    use actix_web::test;

    async fn extract(_req: &ServiceRequest) -> Result<Vec<String>, Error> {
        Ok(vec!["TEST_PERMISSION".to_string()])
    }

    #[actix_rt::test]
    async fn test_fn_extractor_impl() {
        let mut req = test::TestRequest::get().to_srv_request();
        let permissions = extract.extract(&mut req).await;

        permissions
            .unwrap()
            .iter()
            .for_each(|perm| assert_eq!("TEST_PERMISSION", perm.as_str()));
    }

    async fn mut_extract(_req: &mut ServiceRequest) -> Result<Vec<String>, Error> {
        Ok(vec!["TEST_PERMISSION".to_string()])
    }

    #[actix_rt::test]
    async fn test_fn_mut_extractor_impl() {
        let mut req = test::TestRequest::get().to_srv_request();
        let permissions = mut_extract.extract(&mut req).await;

        permissions
            .unwrap()
            .iter()
            .for_each(|perm| assert_eq!("TEST_PERMISSION", perm.as_str()));
    }
}