samedi 19 mai 2018

Application state access from an Actix web application middleware

I have a simple middleware intended to access the application global state for the authentication token validation sake. Here is the code:

use actix_web;
use actix_web::HttpMessage;

pub struct Authenticator;

impl<S> actix_web::middleware::Middleware<S> for Authenticator {
    fn start(
        &self,
        request: &mut actix_web::HttpRequest<S>,
    ) -> actix_web::Result<actix_web::middleware::Started>
    {
        //let _state = request.state() as &::application::State;
        match request.headers().get("Authentication") {
            Some(_) => Ok(actix_web::middleware::Started::Done),
            None => Err(::view::error("No authentication header provided", actix_web::http::StatusCode::FORBIDDEN)),
        }
    }
}

The commented string shows how I tried to get the state. I have tried many ways actually.
What is the best way of doing such stuff?
Before I finished this issue I thought about adding a reference to needed data (e.g. Arc'd RwLock) to the Authenticator structure and constructing it with the reference during registering my middlewares.
I am still not good with trait stuff, but there must be a clean way of casting the S type to my application-defined State structure:

pub struct State {
    pub database        : actix::Addr<actix::Syn, ::database::Actor>,
    pub cache           : ::std::sync::Arc<::cache::Cache>,
    pub sessions        : ::std::sync::Arc<::session::Storage>,
}




Aucun commentaire:

Enregistrer un commentaire