fairingrey/actix-realworld-example-app

Consider implementing FromRequest for authentication method

fairingrey opened this issue · 1 comments

This actually doesn't seem too difficult. Consider implementing the FromRequest trait for our auth method so we don't have to call a specific method all the time to get the auth object.

https://actix.rs/actix-web/actix_web/trait.FromRequest.html

Concerning code is here:

https://github.com/fairingrey/actix-realworld-example-app/blob/master/src/utils/auth.rs

Thanks to @colelawrence for letting me know of the idea!

I tried doing this just earlier, but it probably requires a Box of some sort...

Trying to insert the following code into https://github.com/fairingrey/actix-realworld-example-app/blob/master/src/utils/auth.rs gives me this error.

impl FromRequest<AppState> for Auth {
    type Config = ();
    type Result = Box<Future<Item = Auth, Error = Error>>;

    fn from_request(req: &HttpRequest<AppState>, _: &Self::Config) -> Self::Result {
        let db = req.state().db.clone();

        result(preprocess_authz_token(req))
            .and_then(move |token| db.send(GenerateAuth { token }).from_err())
            .flatten()
    }
}

Error:

error[E0277]: the trait bound `actix_web::handler::AsyncResult<utils::auth::Auth>: std::convert::From<std::boxed::Box<(dyn futures::future::Future<Error=error::Error, Item=utils::auth::Auth> + 'static)>>` is not satisfied
  --> src/utils/auth.rs:23:6
   |
23 | impl FromRequest<AppState> for Auth {
   |      ^^^^^^^^^^^^^^^^^^^^^ the trait `std::convert::From<std::boxed::Box<(dyn futures::future::Future<Error=error::Error, Item=utils::auth::Auth> + 'static)>>` is not implemented for `actix_web::handler::AsyncResult<utils::auth::Auth>`
   |

Not sure why, given Box should support converting into an AsyncResult (Future<T, E>). In the first place I'm not exactly a huge fan of using Box anyway, when impl Future usually works faster since the compiler doesn't have to infer much (and is also much more flexible).

Maybe I won't do this after all, I think the current auth method works fine for now. But perhaps someone with more experience could chime in.