Skip to main content

revolt_database/util/
ip.rs

1#[cfg(feature = "rocket-impl")]
2pub mod rocket {
3    use revolt_config::config;
4    use rocket::Request;
5
6    pub fn to_ip(request: &'_ Request<'_>) -> String {
7        request
8            .client_ip()
9            .map(|x| x.to_string())
10            .unwrap_or_default()
11    }
12
13    /// Find the actual IP of the client
14    pub async fn to_real_ip(request: &'_ Request<'_>) -> String {
15        if config().await.api.security.trust_cloudflare {
16            request
17                .headers()
18                .get_one("CF-Connecting-IP")
19                .map(|x| x.to_string())
20                .unwrap_or_else(|| to_ip(request))
21        } else {
22            to_ip(request)
23        }
24    }
25}
26
27#[cfg(feature = "axum-impl")]
28pub mod axum {
29    use axum::{
30        extract::ConnectInfo,
31        http::request::Parts,
32    };
33    use revolt_config::config;
34    use std::net::SocketAddr;
35
36    pub fn to_ip(parts: &Parts) -> String {
37        parts
38            .extensions
39            .get::<ConnectInfo<SocketAddr>>()
40            .map(|info| info.ip().to_string())
41            .unwrap_or_default()
42    }
43
44    /// Find the actual IP of the client
45    pub async fn to_real_ip(parts: &Parts) -> String {
46        if config().await.api.security.trust_cloudflare {
47            parts
48                .headers
49                .get("CF-Connecting-IP")
50                .map(|x| x.to_str().unwrap().to_string())
51                .unwrap_or_else(|| to_ip(parts))
52        } else {
53            to_ip(parts)
54        }
55    }
56}