use axum::body::Body;
use axum::http::{Method, Request};
use tower_cookies::Cookies;
use crate::client_server::extractors::PubkyHost;
use super::extract_ip::extract_ip;
pub(super) struct RequestInfo {
pub authenticated: bool,
pub method: Method,
pub user_pubkey: Option<pubky_common::crypto::PublicKey>,
pub client_ip: Result<std::net::IpAddr, anyhow::Error>,
}
impl RequestInfo {
pub fn from_request(req: &Request<Body>) -> Self {
Self {
authenticated: is_authenticated(req),
method: req.method().clone(),
user_pubkey: req
.extensions()
.get::<PubkyHost>()
.map(|pk| pk.public_key().clone()),
client_ip: extract_ip(req),
}
}
}
fn is_authenticated(req: &Request<Body>) -> bool {
req.extensions()
.get::<Cookies>()
.and_then(|cookies| {
let pk = req.extensions().get::<PubkyHost>()?;
cookies.get(&pk.public_key().z32())?;
Some(())
})
.is_some()
}
pub(super) fn is_write_method(method: &Method) -> bool {
matches!(
*method,
Method::PUT | Method::POST | Method::PATCH | Method::DELETE
)
}