1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247

use std::{fs, path::Path, net::{IpAddr,SocketAddr}};
use axum::http::{header::FORWARDED, HeaderMap};
use forwarded_header_value::{ForwardedHeaderValue, Identifier};

use crate::defs::{
    Config as ServerConfig,
    AUTHORIZATION,
    REFERER,
    BEARER,
    USER_AGENT,
    ACCEPT_LANGUAGE,
    X_FORWARDED_FOR,
    X_REAL_IP,
    X_INTERNAL,
    SESSION_ID,
    FILE_SCHEME,
    AppDBs,
    UserId,
};

use crate::defs::UserNotifyData;

pub struct ReqHeaderMap {
    pub header: HeaderMap,
    pub req_path: Vec<String>,    
}

impl ReqHeaderMap {
    pub fn new(header: HeaderMap, request_path: &str) -> Self {
        let req_path = 
            Self::req_end_path(request_path)
            .split(",").map(|s| s.to_string())
            .collect();
        ReqHeaderMap {
            header,
            req_path,
        }
    }
    pub fn req_end_path(req_path: &str) -> String {
        let arr_req_path: Vec<String> = req_path.split("/").map(|s| s.to_string()).collect();
        format!("{}",arr_req_path[arr_req_path.len()-1])
    } 
    pub fn req_user(&self, app_dbs: &AppDBs) -> (String, UserNotifyData) {
        let token = self.auth();
        if !token.is_empty() {
            // dbg!(&token);
            return UserNotifyData::from_token(&token, &app_dbs.config.paseto);
        } else {
            let arr_req_path: Vec<String> = self.req_path.iter()
                .filter(|it| it.contains(SESSION_ID))
                .map(|s| s.to_string())
                .collect();
            if arr_req_path.len() > 0 && arr_req_path[0].contains(SESSION_ID) { 
                let req_sid = format!("{}",&arr_req_path[0].replace(SESSION_ID, ""));
                if let Some(uid) = UserId::from(&req_sid) {
                    let id_path = format!("{}/{}", &app_dbs.config.users_store_uri.replace(FILE_SCHEME, ""), &uid);
                    if ! Path::new(&id_path).exists() {
                        let _ = fs::create_dir(&id_path);
                    }
                    let id = format!("{}",uid);
                    return (   
                        id.to_owned(),
                        UserNotifyData{
                            key: String::from(SESSION_ID),
                            auth: id.to_owned(),
                            id,
                        }
                    );
                }
            }
        }
        (String::from(""), UserNotifyData::default())
    }
    #[allow(dead_code)]
    pub fn req_path_clean(&self) -> Vec<String> {
        let arr_value: Vec<String> = 
            self.req_path.iter()
            .filter(|it| !it.contains(SESSION_ID))
            .map(|s| s.to_string())
            .collect();
        // if path has sid, this will make an empty value and arr_value.len() will be 1
        if arr_value.len() == 1 && arr_value[0].is_empty() {
            Vec::new()
        } else {
            arr_value
        }
    }
    #[allow(dead_code)]
    pub fn req_path_contains(&self,value: &str) -> Vec<String> {
        let arr_value: Vec<String> = 
            self.req_path.iter()
            .filter(|it| it.contains(value))
            .map(|s| s.to_string())
            .collect();
        if arr_value.len() == 0 || arr_value[0].is_empty() {
            Vec::new()
        } else {
            arr_value
        }
    }
    pub fn auth(&self) -> String {
        if let Some(auth) = self.header.get(AUTHORIZATION) {
            format!("{}",auth.to_str().unwrap_or("").replace(&format!("{} ", BEARER),""))
        } else { 
            String::from("")
        }
    }
    #[allow(dead_code)]
    pub fn referer(&self) -> String {
        if let Some(referer) = self.header.get(REFERER) {
            format!("{}",referer.to_str().unwrap_or(""))
        } else { 
            String::from("")
        }
    }
    #[allow(dead_code)]
    pub fn internal(&self) -> String {
        if let Some(internal) = self.header.get(X_INTERNAL) {
            format!("{}",internal.to_str().unwrap_or(""))
        } else { 
            String::from("")
        }
    }
    pub fn is_browser(&self) -> bool {
        if let Some(user_agent) = self.header.get(USER_AGENT) {
            let agent = user_agent.to_str().unwrap_or(""); 
            if agent.contains("Mozilla") { 
                true
            } else if agent.contains("WebKit") {
                true
            } else if agent.contains("Chrome") {
                true
            } else {
                false
            }
        } else { 
            false
        } 
    }
    #[allow(dead_code)]
    pub fn is_curl(&self) -> bool {
        if let Some(user_agent) = self.header.get(USER_AGENT) {
            let agent = user_agent.to_str().unwrap_or(""); 
            if agent.contains("curl") { 
                true
            } else {
                false
            }
        } else { 
            false
        } 
    }
    pub fn is_wget(&self) -> bool {
        if let Some(user_agent) = self.header.get(USER_AGENT) {
            let agent = user_agent.to_str().unwrap_or("").to_lowercase(); 
            if agent.contains("wget") { 
                true
            } else {
                false
            }
        } else { 
            false
        } 
    }
    #[allow(dead_code)]
    pub fn response_user_agent_html(&self) -> bool {
        if let Some(user_agent) = self.header.get(USER_AGENT) {
            let agent = user_agent.to_str().unwrap_or("").to_lowercase(); 
            agent.contains("curl") || agent.contains("wget") 
        } else {
            false
        }
    }
    #[allow(dead_code)]
    pub fn agent(&self) -> String {
        if let Some(user_agent) = self.header.get(USER_AGENT) {
            user_agent.to_str().unwrap_or("").to_owned()
        } else {
            String::from("")
        }
    }
    #[allow(dead_code)]
    pub fn lang(&self, config: &ServerConfig) -> String {
        if let Some(langs) = self.header.get(ACCEPT_LANGUAGE) {
            let langs_data = langs.to_str().unwrap_or("");
            if langs_data.is_empty() {
                format!("{}",config.dflt_lang)
            } else {
                let arr_langs: Vec<String> = langs_data.split(",").map(|s| s.to_string()).collect();
                let arr_lang: Vec<String> = arr_langs[0].split("-").map(|s| s.to_string()).collect();
                format!("{}",arr_lang[0])
            }
        } else {
            format!("{}",config.dflt_lang)
        }
    }
    /// Tries to parse the `x-real-ip` header
    #[allow(dead_code)]
    fn maybe_x_forwarded_for(&self) -> Option<IpAddr> {
        self.header
            .get(X_FORWARDED_FOR)
            .and_then(|hv| hv.to_str().ok())
            .and_then(|s| s.split(',').find_map(|s| s.trim().parse::<IpAddr>().ok()))
    }

    /// Tries to parse the `x-real-ip` header
    #[allow(dead_code)]
    fn maybe_x_real_ip(&self) -> Option<IpAddr> {
        self.header
            .get(X_REAL_IP)
            .and_then(|hv| hv.to_str().ok())
            .and_then(|s| s.parse::<IpAddr>().ok())
    }

    /// Tries to parse `forwarded` headers
    #[allow(dead_code)]
    fn maybe_forwarded(&self) -> Option<IpAddr> {
        self.header
            .get_all(FORWARDED).iter().find_map(|hv| {
                hv.to_str()
                    .ok()
                    .and_then(|s| ForwardedHeaderValue::from_forwarded(s).ok())
                    .and_then(|f| {
                        f.iter()
                            .filter_map(|fs| fs.forwarded_for.as_ref())
                            .find_map(|ff| match ff {
                                Identifier::SocketAddr(a) => Some(a.ip()),
                                Identifier::IpAddr(ip) => Some(*ip),
                                _ => None,
                            })
                    })
        })
    }
    #[allow(dead_code)]
    pub fn ip(&self, addr: &SocketAddr) -> String {
        if let Some(ip) = self.maybe_x_real_ip()
            .or_else(||self.maybe_x_forwarded_for())
            .or_else(|| self.maybe_forwarded())
            .or_else(|| None )
        {
            format!("{}",ip)
        } else {
            format!("{}",addr)
        }
    }
}