      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
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171

    use std::rc::Rc;

    use actix_utils::future::{ready, Ready};
    use actix_web::{
        body::{EitherBody, MessageBody},
        dev::{Service, ServiceRequest, ServiceResponse, Transform},
        Error, HttpMessage, Result,
    };
    use futures_util::future::{FutureExt as _, LocalBoxFuture};

    use crate::{identity::IdentityItem, IdentityPolicy};

    /// Request identity middleware
    ///
    /// ```
    /// use actix_web::App;
    /// use actix_identity::{CookieIdentityPolicy, IdentityService};
    ///
    /// // create cookie identity backend
    /// let policy = CookieIdentityPolicy::new(&[0; 32])
    ///            .name("auth-cookie")
    ///            .secure(false);
    ///
    /// let app = App::new()
    ///     // wrap policy into identity middleware
    ///     .wrap(IdentityService::new(policy));
    /// ```
    pub struct IdentityService<T> {
        backend: Rc<T>,
    }

    impl<T> IdentityService<T> {
        /// Create new identity service with specified backend.
        pub fn new(backend: T) -> Self {
            IdentityService {
                backend: Rc::new(backend),
            }
        }
    }

    impl<S, T, B> Transform<S, ServiceRequest> for IdentityService<T>
    where
        S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
        S::Future: 'static,
        T: IdentityPolicy,
        B: MessageBody + 'static,
    {
        type Response = ServiceResponse<EitherBody<B>>;
        type Error = Error;
        type InitError = ();
        type Transform = IdentityServiceMiddleware<S, T>;
        type Future = Ready<Result<Self::Transform, Self::InitError>>;

        fn new_transform(&self, service: S) -> Self::Future {
            ready(Ok(IdentityServiceMiddleware {
                backend: self.backend.clone(),
                service: Rc::new(service),
            }))
        }
    }

    pub struct IdentityServiceMiddleware<S, T> {
        pub(crate) service: Rc<S>,
        pub(crate) backend: Rc<T>,
    }

    impl<S, T> Clone for IdentityServiceMiddleware<S, T> {
        fn clone(&self) -> Self {
            Self {
                backend: Rc::clone(&self.backend),
                service: Rc::clone(&self.service),
            }
        }
    }

    impl<S, T, B> Service<ServiceRequest> for IdentityServiceMiddleware<S, T>
    where
        S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
        S::Future: 'static,
        T: IdentityPolicy,
        B: MessageBody + 'static,
    {
        type Response = ServiceResponse<EitherBody<B>>;
        type Error = Error;
        type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

        actix_service::forward_ready!(service);

        fn call(&self, mut req: ServiceRequest) -> Self::Future {
            let srv = Rc::clone(&self.service);
            let backend = Rc::clone(&self.backend);
            let fut = self.backend.from_request(&mut req);

            async move {
                match fut.await {
                    Ok(id) => {
                        req.extensions_mut()
                            .insert(IdentityItem { id, changed: false });

                        let mut res = srv.call(req).await?;
                        let id = res.request().extensions_mut().remove::<IdentityItem>();

                        if let Some(id) = id {
                            match backend.to_response(id.id, id.changed, &mut res).await {
                                Ok(_) => Ok(res.map_into_left_body()),
                                Err(err) => Ok(res.error_response(err).map_into_right_body()),
                            }
                        } else {
                            Ok(res.map_into_left_body())
                        }
                    }
                    Err(err) => Ok(req.error_response(err).map_into_right_body()),
                }
            }
            .boxed_local()
        }
    }

    #[cfg(test)]
    mod tests {
        use std::{rc::Rc, time::Duration};

        use actix_service::into_service;
        use actix_web::{dev, error, test, Error, Result};

        use super::*;

        #[actix_web::test]
        async fn test_borrowed_mut_error() {
            use actix_utils::future::{ok, Ready};
            use futures_util::future::lazy;

            struct Ident;
            impl IdentityPolicy for Ident {
                type Future = Ready<Result<Option<String>, Error>>;
                type ResponseFuture = Ready<Result<(), Error>>;

                fn from_request(&self, _: &mut dev::ServiceRequest) -> Self::Future {
                    ok(Some("test".to_string()))
                }

                fn to_response<B>(
                    &self,
                    _: Option<String>,
                    _: bool,
                    _: &mut dev::ServiceResponse<B>,
                ) -> Self::ResponseFuture {
                    ok(())
                }
            }

            let srv = crate::middleware::IdentityServiceMiddleware {
                backend: Rc::new(Ident),
                service: Rc::new(into_service(|_: dev::ServiceRequest| async move {
                    actix_web::rt::time::sleep(Duration::from_secs(100)).await;
                    Err::<dev::ServiceResponse, _>(error::ErrorBadRequest("error"))
                })),
            };

            let srv2 = srv.clone();
            let req = test::TestRequest::default().to_srv_request();

            actix_web::rt::spawn(async move {
                let _ = srv2.call(req).await;
            });

            actix_web::rt::time::sleep(Duration::from_millis(50)).await;

            let _ = lazy(|cx| srv.poll_ready(cx)).await;
        }
    }