1use actix_utils::future::{Ready, ready};
2use actix_web::{
3 Error, FromRequest, HttpMessage, HttpRequest, dev::Payload, error::ErrorInternalServerError,
4};
5use shield::{Session, Shield, User};
6
7pub struct ExtractShield<U: User>(pub Shield<U>);
8
9impl<U: User + Clone + 'static> FromRequest for ExtractShield<U> {
10 type Error = Error;
11 type Future = Ready<Result<Self, Self::Error>>;
12
13 fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
14 ready(
15 req.extensions()
16 .get::<Shield<U>>()
17 .cloned()
18 .map(ExtractShield)
19 .ok_or(ErrorInternalServerError(
20 "Can't extract Shield. Is `ShieldTransform` enabled?",
21 )),
22 )
23 }
24}
25
26pub struct ExtractSession(pub Session);
27
28impl FromRequest for ExtractSession {
29 type Error = Error;
30 type Future = Ready<Result<Self, Self::Error>>;
31
32 fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
33 ready(
34 req.extensions()
35 .get::<Session>()
36 .cloned()
37 .map(ExtractSession)
38 .ok_or(ErrorInternalServerError(
39 "Can't extract Shield session. Is `ShieldTransform` enabled?",
40 )),
41 )
42 }
43}
44
45pub struct ExtractUser<U: User>(pub Option<U>);
46
47impl<U: User + Clone + 'static> FromRequest for ExtractUser<U> {
48 type Error = Error;
49 type Future = Ready<Result<Self, Self::Error>>;
50
51 fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
52 ready(
53 req.extensions()
54 .get::<Option<U>>()
55 .cloned()
56 .map(ExtractUser)
57 .ok_or(ErrorInternalServerError(
58 "Can't extract Shield user. Is `ShieldTransform` enabled?",
59 )),
60 )
61 }
62}