Skip to content

Instantly share code, notes, and snippets.

@apiraino
Last active August 22, 2020 10:30
Show Gist options
  • Select an option

  • Save apiraino/6fc15628d32b114ce60e6aa9a686c3e1 to your computer and use it in GitHub Desktop.

Select an option

Save apiraino/6fc15628d32b114ce60e6aa9a686c3e1 to your computer and use it in GitHub Desktop.
use warp::Filter;
#[derive(Debug)]
pub enum Error {
RejectWith401,
}
impl warp::reject::Reject for Error {}
fn get_token_or_401() -> impl Filter<Extract = (String,), Error = warp::Rejection> + Clone {
warp::header::<String>("Authorization").and_then(move |header_name: String| async move {
let res = header_name.split_ascii_whitespace().collect::<Vec<&str>>();
if res.len() != 2 {
eprintln!("Incorrect header, returning 401");
return Err(warp::reject::custom(Error::RejectWith401));
}
eprintln!("Found token {}", res[1]);
Ok(res[1].to_string())
})
}
fn wrapper<F, T>(filter: F) -> impl Filter<Extract = (&'static str,)> + Clone + Send + Sync
where
F: Filter<Extract = (T,), Error = std::convert::Infallible> + Clone + Send + Sync,
F::Extract: warp::Reply,
T: std::fmt::Debug + std::marker::Send,
{
warp::any()
.map(|| {
eprintln!("before filter");
})
.and(get_token_or_401())
.and(filter) // <-- what is this supposed to to?
// how to plug another filter that validates the token?
.map(|whats_this, token, param1| {
eprintln!("> {:?} {} {:?}", whats_this, token, param1);
"success"
})
}
#[tokio::main]
async fn main() {
let routes = warp::any()
.map(|| "hello world")
// try with warp::path!("/")
.with(warp::wrap_fn(wrapper));
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
async fn check_auth(token: String) -> Result<String, String> {
eprintln!("check token={}", token);
if token.is_empty() || token != "valid-token" {
return Err(format!("Missing or invalid token {}", token));
}
Ok(token)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment