-1

async fn get_current_user(
    req: HttpRequest,
    payload: &mut Payload,
    config: &CurrentUserConfig,
) -> Result<CurrentUser, Error> {
    todo!()
}

#[derive(Debug)]
pub struct CurrentUser(User);

impl FromRequest for CurrentUser {
    type Error = Error;
    type Future = impl Future<Output = Result<Self, Self::Error>>;

    #[inline]
    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
        let config = CurrentUserConfig::from_req(req);
        get_current_user(req.clone(), payload, config)
    }
}

The above code does not work properly because 'impl Trait' in type aliases is unstable, what type of Future should I set

........................

mxp-xc
  • 456
  • 2
  • 6

1 Answers1

0

You have some things done wrong. Looking at the FromRequest trait.

pub trait FromRequest: Sized {
    type Error: Into<Error>;
    type Future: Future<Output = Result<Self, Self::Error>>;
    type Config: Default + 'static;
    fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future;

You are returning the wrong type:

type Future: Future<Output = Result<Self, Self::Error>>;

You are returning User instead of CurrentUser

On the issue of which type, you can use Box<dyn Future>.

impl FromRequest for CurrentUser {
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<CurrentUser, Error>>>>;
    type Config = ();
    fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future {
        let fut = get_token(&req);
        Box::pin(async move {
            let res: JwtToken = fut.await?;
            match res {
                JwtToken::User(user) => Ok(user),
                _ => Err(Error::Authentication),
            }
        })
    }
}
Njuguna Mureithi
  • 3,506
  • 1
  • 21
  • 41
  • Thank you. The returned type is wrong. Your solution is very meaningful, but I don't know `BoxedFuture`, I wonder if I can return it as an implementation of future, because I want to call `get_ current_user` without `await` should be a way to implement future, or is it wrong? Because in Python, async fn call without `await` will return a `coroutine` – mxp-xc Dec 20 '21 at 08:18