1
0
mirror of https://github.com/actix/examples synced 2025-01-23 14:24:35 +01:00

70 lines
2.1 KiB
Rust
Raw Normal View History

use std::future::{ready, Ready};
2019-12-07 23:59:24 +06:00
2022-08-28 18:39:28 +01:00
use actix_web::{
body::EitherBody,
dev::{self, Service, ServiceRequest, ServiceResponse, Transform},
http, Error, HttpResponse,
};
2022-02-22 12:12:17 +00:00
use futures_util::future::LocalBoxFuture;
2018-07-09 21:36:03 +02:00
pub struct CheckLogin;
impl<S, B> Transform<S, ServiceRequest> for CheckLogin
2019-03-10 19:19:50 -07:00
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
2019-03-10 19:19:50 -07:00
S::Future: 'static,
2022-02-22 12:01:01 +00:00
B: 'static,
2019-03-10 19:19:50 -07:00
{
type Response = ServiceResponse<EitherBody<B>>;
2019-04-25 11:19:21 -07:00
type Error = Error;
2019-03-10 19:19:50 -07:00
type InitError = ();
type Transform = CheckLoginMiddleware<S>;
2019-12-07 23:59:24 +06:00
type Future = Ready<Result<Self::Transform, Self::InitError>>;
2019-03-10 19:19:50 -07:00
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(CheckLoginMiddleware { service }))
2019-03-10 19:19:50 -07:00
}
}
pub struct CheckLoginMiddleware<S> {
service: S,
}
impl<S, B> Service<ServiceRequest> for CheckLoginMiddleware<S>
2019-03-10 19:19:50 -07:00
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
2019-03-10 19:19:50 -07:00
S::Future: 'static,
2022-02-22 12:01:01 +00:00
B: 'static,
2019-03-10 19:19:50 -07:00
{
type Response = ServiceResponse<EitherBody<B>>;
2019-04-25 11:19:21 -07:00
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
2019-03-10 19:19:50 -07:00
dev::forward_ready!(service);
2019-03-10 19:19:50 -07:00
2022-02-22 12:01:01 +00:00
fn call(&self, request: ServiceRequest) -> Self::Future {
2022-02-22 12:12:17 +00:00
// Change this to see the change in outcome in the browser.
// Usually this boolean would be acquired from a password check or other auth verification.
let is_logged_in = false;
2022-02-22 12:01:01 +00:00
2022-02-22 12:12:17 +00:00
// Don't forward to `/login` if we are already on `/login`.
if !is_logged_in && request.path() != "/login" {
2022-02-22 12:01:01 +00:00
let (request, _pl) = request.into_parts();
let response = HttpResponse::Found()
.insert_header((http::header::LOCATION, "/login"))
.finish()
// constructed responses map to "right" body
.map_into_right_body();
return Box::pin(async { Ok(ServiceResponse::new(request, response)) });
}
let res = self.service.call(request);
2018-07-09 21:36:03 +02:00
Box::pin(async move {
2022-02-22 12:01:01 +00:00
// forwarded responses map to "left" body
res.await.map(ServiceResponse::map_into_left_body)
})
2018-07-09 21:36:03 +02:00
}
}