7

I'm building a graphql api with Rust and Warp. I've looked through the docs, but I have still not figured out how to chain the filters, especially for checking the authorization in request header.

let context_extractor = warp::any()
    // this code rejects all request which doesn't contain the authorization in header
    // I'd like to make to check if authorization in header
    .and(warp::header::<String>("authorization"))
    .map(|token: String| -> Context {
        let token_data = match verify_jwt(token) {
            Ok(t) => t,
            Err(_) => return Context { user_id: 0 },
        };

        Context {
            user_id: token_data.claims.user_id,
        }
    });

let handle_request = move |context: Context,
                           request: juniper::http::GraphQLRequest|
      -> Result<Vec<u8>, serde_json::Error> {
    serde_json::to_vec(&request.execute(&schema, &context))
};

warp::post2()
    .and(warp::path(path.into()))
    .and(context_extractor)
    .and(warp::body::json())
    .map(handle_request)
    .map(build_response)
    .boxed()

This is my part of code. It works fine, but there is one problem. I've set up one route context_extractor with .and(warp::header::<String>("authorization"), then it rejects all requests which doesn't contain authorization in header.

How can I make

  1. if request header has a authorization in header, then return Context with the proper user_id

  2. if not, return Context with user_id: 0?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
mununki
  • 350
  • 4
  • 16

1 Answers1

8

I've found the solution in github issues of Warp.

here is a small snippet.

let context_extractor = warp::any().and(
    warp::header::<String>("authorization")
        .map(|token: String| -> Context {
            let token_data = match verify_jwt(token) {
                Ok(t) => t,
                Err(_) => return Context { user_id: 0 },
            };

            Context {
                user_id: token_data.claims.user_id,
            }
        })
        .or(warp::any().map(|| Context { user_id: 0 }))
        .unify(),
);
Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
mununki
  • 350
  • 4
  • 16