shield_actix/
extract.rs

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
use actix_utils::future::{ready, Ready};
use actix_web::{
    dev::Payload, error::ErrorInternalServerError, Error, FromRequest, HttpMessage, HttpRequest,
};
use shield::{Session, Shield, User};

pub struct ExtractShield<U: User>(pub Shield<U>);

impl<U: User + Clone + 'static> FromRequest for ExtractShield<U> {
    type Error = Error;
    type Future = Ready<Result<Self, Self::Error>>;

    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
        ready(
            req.extensions()
                .get::<Shield<U>>()
                .cloned()
                .map(ExtractShield)
                .ok_or(ErrorInternalServerError(
                    "Can't extract Shield. Is `ShieldTransform` enabled?",
                )),
        )
    }
}

pub struct ExtractSession(pub Session);

impl FromRequest for ExtractSession {
    type Error = Error;
    type Future = Ready<Result<Self, Self::Error>>;

    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
        ready(
            req.extensions()
                .get::<Session>()
                .cloned()
                .map(ExtractSession)
                .ok_or(ErrorInternalServerError(
                    "Can't extract Shield session. Is `ShieldTransform` enabled?",
                )),
        )
    }
}

pub struct ExtractUser<U: User>(pub Option<U>);

impl<U: User + Clone + 'static> FromRequest for ExtractUser<U> {
    type Error = Error;
    type Future = Ready<Result<Self, Self::Error>>;

    fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
        ready(
            req.extensions()
                .get::<Option<U>>()
                .cloned()
                .map(ExtractUser)
                .ok_or(ErrorInternalServerError(
                    "Can't extract Shield user. Is `ShieldTransform` enabled?",
                )),
        )
    }
}