use std::collections::HashMap;
use std::net::SocketAddr;
use bytes::Bytes;
use http::{HeaderMap, Method, Uri, request::Parts, uri::Scheme};
#[derive(Debug, Clone, Copy)]
pub struct ClientAddr(pub SocketAddr);
#[derive(Debug, Clone, Copy)]
pub struct ConnectionSecure(pub bool);
pub struct RequestContext<'a> {
parts: &'a Parts,
query: HashMap<String, Vec<String>>,
form: HashMap<String, Vec<String>>,
body: Bytes,
}
impl<'a> RequestContext<'a> {
pub fn new(parts: &'a Parts) -> Self {
Self {
query: parse_query(parts.uri.query().unwrap_or_default()),
parts,
form: HashMap::new(),
body: Bytes::new(),
}
}
pub fn with_body(parts: &'a Parts, body: Bytes) -> Self {
let mut ctx = Self::new(parts);
if ctx.is_form_content_type() && !body.is_empty() {
if let Ok(text) = std::str::from_utf8(&body) {
ctx.form = parse_query(text);
}
}
ctx.body = body;
ctx
}
fn is_form_content_type(&self) -> bool {
self.header("content-type")
.split(';')
.next()
.unwrap_or_default()
.trim()
.eq_ignore_ascii_case("application/x-www-form-urlencoded")
}
pub fn parts(&self) -> &Parts {
self.parts
}
pub fn body(&self) -> &Bytes {
&self.body
}
pub fn method(&self) -> &Method {
&self.parts.method
}
pub fn uri(&self) -> &Uri {
&self.parts.uri
}
pub fn path(&self) -> &str {
self.parts.uri.path()
}
pub fn request_uri(&self) -> String {
match self.parts.uri.query() {
Some(query) => format!("{}?{}", self.path(), query),
None => self.path().to_string(),
}
}
pub fn headers(&self) -> &HeaderMap {
&self.parts.headers
}
pub fn header(&self, name: &str) -> &str {
self.parts
.headers
.get(name)
.and_then(|value| value.to_str().ok())
.unwrap_or_default()
}
pub fn host(&self) -> &str {
let host = self.header("host");
if !host.is_empty() {
return host;
}
self.parts
.uri
.authority()
.map(|a| a.as_str())
.unwrap_or_default()
}
pub fn user_agent(&self) -> &str {
self.header("user-agent")
}
pub fn query_get(&self, key: &str) -> &str {
self.query
.get(key)
.and_then(|values| values.first())
.map(String::as_str)
.unwrap_or_default()
}
pub fn form_value(&self, key: &str) -> &str {
self.form
.get(key)
.and_then(|values| values.first())
.map(String::as_str)
.unwrap_or_else(|| self.query_get(key))
}
pub fn query(&self) -> &HashMap<String, Vec<String>> {
&self.query
}
pub fn post_form(&self) -> &HashMap<String, Vec<String>> {
&self.form
}
pub fn extensions(&self) -> &http::Extensions {
&self.parts.extensions
}
pub fn remote_addr(&self) -> Option<SocketAddr> {
self.parts.extensions.get::<ClientAddr>().map(|addr| addr.0)
}
}
fn parse_query(raw: &str) -> HashMap<String, Vec<String>> {
let mut out: HashMap<String, Vec<String>> = HashMap::new();
for (key, value) in form_urlencoded::parse(raw.as_bytes()) {
out.entry(key.into_owned())
.or_default()
.push(value.into_owned());
}
out
}
pub fn provider_id_from_request(r: &RequestContext<'_>) -> String {
let path = r.path().trim_matches('/');
let parts: Vec<&str> = path.split('/').collect();
for (i, part) in parts.iter().enumerate() {
if *part == "provider" && i + 1 < parts.len() {
return parts[i + 1].to_string();
}
}
String::new()
}
pub fn is_secure_request(r: &RequestContext<'_>) -> bool {
if let Some(ConnectionSecure(secure)) = r.extensions().get::<ConnectionSecure>() {
if *secure {
return true;
}
}
if r.uri().scheme() == Some(&Scheme::HTTPS) {
return true;
}
r.header("x-forwarded-proto").eq_ignore_ascii_case("https")
}
pub fn client_ip(r: &RequestContext<'_>) -> String {
let forwarded = r.header("x-forwarded-for");
if !forwarded.is_empty() {
return forwarded
.split(',')
.next()
.unwrap_or(forwarded)
.trim()
.to_string();
}
let real_ip = r.header("x-real-ip");
if !real_ip.is_empty() {
return real_ip.to_string();
}
match r.remote_addr() {
Some(addr) => addr.ip().to_string(),
None => String::new(),
}
}