|
| 1 | +//! Middleware that blocks requests from a list of given IPs |
| 2 | +
|
| 3 | +use super::prelude::*; |
| 4 | + |
| 5 | +use std::io::Cursor; |
| 6 | +use std::collections::HashMap; |
| 7 | +use std::net::IpAddr; |
| 8 | + |
| 9 | +// Can't derive debug because of Handler. |
| 10 | +#[allow(missing_debug_implementations)] |
| 11 | +#[derive(Default)] |
| 12 | +pub struct BlockIps { |
| 13 | + ips: Vec<IpAddr>, |
| 14 | + handler: Option<Box<Handler>>, |
| 15 | +} |
| 16 | + |
| 17 | +impl BlockIps { |
| 18 | + pub fn new(ips: Vec<IpAddr>) -> Self { |
| 19 | + Self { ips, handler: None } |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +impl AroundMiddleware for BlockIps { |
| 24 | + fn with_handler(&mut self, handler: Box<Handler>) { |
| 25 | + self.handler = Some(handler); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +impl Handler for BlockIps { |
| 30 | + fn call(&self, req: &mut Request) -> Result<Response, Box<Error + Send>> { |
| 31 | + if self.ips.contains(&req.remote_addr().ip()) { |
| 32 | + let body = format!( |
| 33 | + "We are unable to process your request at this time. \ |
| 34 | + Please open an issue at https://github.com/rust-lang/crates.io \ |
| 35 | + and provide the request id {}", |
| 36 | + req.headers().find("X-Request-Id").unwrap()[0] |
| 37 | + ); |
| 38 | + let mut headers = HashMap::new(); |
| 39 | + headers.insert("Content-Length".to_string(), vec![body.len().to_string()]); |
| 40 | + Ok(Response { |
| 41 | + status: (403, "Forbidden"), |
| 42 | + headers, |
| 43 | + body: Box::new(Cursor::new(body.into_bytes())), |
| 44 | + }) |
| 45 | + } else { |
| 46 | + self.handler.as_ref().unwrap().call(req) |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments