Newer
Older
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
Error,
};
use futures::prelude::future::LocalBoxFuture;
use std::future::{ready, Ready};
pub struct AuthService {
pub token: String,
impl<S, B> Transform<S, ServiceRequest> for AuthService
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
B: MessageBody + 'static,
type Error = Error;
type InitError = ();
type Transform = AuthenticatedMiddleware<S>;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(AuthenticatedMiddleware {
service: std::rc::Rc::new(service),
}
}
pub struct AuthenticatedMiddleware<S> {
async fn authenticate(req: &mut ServiceRequest, token: String) -> bool {
Some(cookie) => return cookie.value().to_string().eq(&token),
None => false,
impl<S, B> Service<ServiceRequest> for AuthenticatedMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
B: MessageBody + 'static,
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
let token = self.auth.token.to_owned();
if let false = authenticate(&mut req, token).await {
return Ok(req.into_response(
actix_web::HttpResponse::Unauthorized()
.finish()
.map_into_right_body(),
));