1
0
mirror of https://github.com/actix/examples synced 2024-12-03 18:22:14 +01:00
examples/middleware/src/redirect.rs

65 lines
2.0 KiB
Rust
Raw Normal View History

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-03-11 03:19:50 +01:00
impl<S, P, B> Transform<S> for CheckLogin
where
S: Service<Request = ServiceRequest<P>, Response = ServiceResponse<B>>,
S::Future: 'static,
{
type Request = ServiceRequest<P>;
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,
}
impl<S, P, B> Service for CheckLoginMiddleware<S>
where
S: Service<Request = ServiceRequest<P>, Response = ServiceResponse<B>>,
S::Future: 'static,
{
type Request = ServiceRequest<P>;
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()
}
fn call(&mut self, req: ServiceRequest<P>) -> Self::Future {
// 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
}
}
}