2019-03-11 03:19:50 +01:00
|
|
|
use actix_service::{Service, Transform};
|
|
|
|
use actix_web::dev::{ServiceRequest, ServiceResponse};
|
|
|
|
use actix_web::{http, HttpResponse};
|
|
|
|
use futures::future::{ok, Either, FutureResult};
|
|
|
|
use futures::Poll;
|
2018-07-09 21:36:03 +02:00
|
|
|
|
|
|
|
pub struct CheckLogin;
|
|
|
|
|
2019-04-14 19:34:41 +02:00
|
|
|
impl<S, B> Transform<S> for CheckLogin
|
2019-03-11 03:19:50 +01:00
|
|
|
where
|
2019-04-14 19:34:41 +02:00
|
|
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
2019-03-11 03:19:50 +01:00
|
|
|
S::Future: 'static,
|
|
|
|
{
|
2019-04-14 19:34:41 +02:00
|
|
|
type Request = ServiceRequest;
|
2019-03-11 03:19:50 +01:00
|
|
|
type Response = ServiceResponse<B>;
|
|
|
|
type Error = S::Error;
|
|
|
|
type InitError = ();
|
|
|
|
type Transform = CheckLoginMiddleware<S>;
|
|
|
|
type Future = FutureResult<Self::Transform, Self::InitError>;
|
|
|
|
|
|
|
|
fn new_transform(&self, service: S) -> Self::Future {
|
|
|
|
ok(CheckLoginMiddleware { service })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
pub struct CheckLoginMiddleware<S> {
|
|
|
|
service: S,
|
|
|
|
}
|
|
|
|
|
2019-04-14 19:34:41 +02:00
|
|
|
impl<S, B> Service for CheckLoginMiddleware<S>
|
2019-03-11 03:19:50 +01:00
|
|
|
where
|
2019-04-14 19:34:41 +02:00
|
|
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>>,
|
2019-03-11 03:19:50 +01:00
|
|
|
S::Future: 'static,
|
|
|
|
{
|
2019-04-14 19:34:41 +02:00
|
|
|
type Request = ServiceRequest;
|
2019-03-11 03:19:50 +01:00
|
|
|
type Response = ServiceResponse<B>;
|
|
|
|
type Error = S::Error;
|
|
|
|
type Future = Either<S::Future, FutureResult<Self::Response, Self::Error>>;
|
|
|
|
|
|
|
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
|
|
|
self.service.poll_ready()
|
|
|
|
}
|
|
|
|
|
2019-04-14 19:34:41 +02:00
|
|
|
fn call(&mut self, req: ServiceRequest) -> Self::Future {
|
2019-03-11 03:19:50 +01:00
|
|
|
// We only need to hook into the `start` for this middleware.
|
|
|
|
|
2018-07-09 21:36:03 +02:00
|
|
|
let is_logged_in = false; // Change this to see the change in outcome in the browser
|
|
|
|
|
|
|
|
if is_logged_in {
|
2019-03-11 03:19:50 +01:00
|
|
|
Either::A(self.service.call(req))
|
|
|
|
} else {
|
|
|
|
// Don't forward to /login if we are already on /login
|
|
|
|
if req.path() == "/login" {
|
|
|
|
Either::A(self.service.call(req))
|
|
|
|
} else {
|
|
|
|
Either::B(ok(req.into_response(
|
|
|
|
HttpResponse::Found()
|
|
|
|
.header(http::header::LOCATION, "/login")
|
|
|
|
.finish()
|
|
|
|
.into_body(),
|
|
|
|
)))
|
|
|
|
}
|
2018-07-09 21:36:03 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|