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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use base64::{prelude::BASE64_STANDARD, Engine};
use regex::Regex;
use serde_json::json;
use std::{collections::HashMap, net::IpAddr, sync::Arc};
use termcolor::Color;

use crate::{logger::Logger, ApiError, Body, HttpResponse};

#[derive(Debug)]
pub enum HttpMethod {
    GET,
    POST,
    PUT,
    DELETE,
    PATCH,
    OPTIONS,
    HEAD,
    TRACE,
    CONNECT,
}

pub struct Credentials {
    username: String,
    password: String,
}

impl HttpMethod {
    fn as_str(&self) -> &str {
        match self {
            HttpMethod::GET => "GET",
            HttpMethod::POST => "POST",
            HttpMethod::PUT => "PUT",
            HttpMethod::DELETE => "DELETE",
            HttpMethod::PATCH => "PATCH",
            HttpMethod::OPTIONS => "OPTIONS",
            HttpMethod::HEAD => "HEAD",
            HttpMethod::TRACE => "TRACE",
            HttpMethod::CONNECT => "CONNECT",
        }
    }
}

fn get_status_code_color(status_code: u16) -> Color {
    match status_code {
        100..=199 => Color::Cyan,
        200..=299 => Color::Green,
        300..=399 => Color::Yellow,
        400..=499 => Color::Red,
        _ => Color::Magenta,
    }
}

type Handler =
    Box<dyn Fn(Option<&str>, HashMap<&str, &str>) -> Result<HttpResponse, ApiError> + Send + Sync>;

pub struct Route {
    pattern: Regex,
    handler: Handler,
    method: HttpMethod,
    authorize: bool,
}
pub struct Router {
    routes: Vec<Route>,
    logger: Option<Arc<Logger>>,
    pub(super) cors: Option<Cors>,
    pub(super) credentials: Option<Credentials>,
}

impl Router {
    pub fn new() -> Self {
        Router {
            routes: Vec::new(),
            logger: None,
            cors: None,
            credentials: None,
        }
    }
    pub fn with_logger(mut self, logger: Option<Arc<Logger>>) -> Self {
        self.logger = logger;
        self
    }

    pub fn with_cors(mut self, cors: Cors) -> Self {
        self.cors = Some(cors);
        self
    }

    pub fn with_credentials(mut self, password: &str, username: &str) -> Self {
        self.credentials = Some(Credentials {
            username: username.to_string(),
            password: password.to_string(),
        });
        self
    }

    pub fn add_route<F>(&mut self, path: &str, method: HttpMethod, handler: F, authorize: bool)
    where
        F: Fn(Option<&str>, HashMap<&str, &str>) -> Result<HttpResponse, ApiError>
            + Send
            + Sync
            + 'static,
    {
        let pattern = if path == "/*" {
            "^.*$".to_string()
        } else {
            format!("^{}$", path.replace('{', "(?P<").replace('}', ">[^/]+)"))
        };
        let regex = Regex::new(&pattern).unwrap();
        self.routes.push(Route {
            pattern: regex,
            handler: Box::new(handler),
            method,
            authorize,
        });
    }

    pub fn route(
        &self,
        path: &str,
        method: &str,
        data: Option<&str>,
        peer_addr: IpAddr,
        headers: &HashMap<&str, &str>,
    ) -> Result<HttpResponse, ApiError> {
        let stripped_path: Vec<&str> = path.splitn(2, '?').collect();
        if method == HttpMethod::OPTIONS.as_str() {
            let mut response = HttpResponse::new(None, None, 204);
            if let Some(cors) = &self.cors {
                for (key, value) in &cors.headers {
                    response = response.add_response_header(key, value);
                }
            }
            Ok(response)
        } else {
            for route in &self.routes {
                let pattern_match = route.pattern.captures(stripped_path[0]);

                match pattern_match {
                    Some(pattern_match) => {
                        if route.method.as_str() != method {
                            return Err(ApiError::new_with_json(405, "Method Not Allowed"));
                        }
                        if route.authorize {
                            if let Some(credentials) = &self.credentials {
                                if let Some(auth_header) = headers.get("Authorization") {
                                    challenge_basic_auth(
                                        auth_header,
                                        &credentials.password,
                                        &credentials.username,
                                    )?;
                                } else {
                                    return Ok(HttpResponse::new(
                                        Some(Body::Json(json!({"message": "Unauthorized"}))),
                                        None,
                                        401,
                                    )
                                    .add_response_header("WWW-Authenticate", "Basic"));
                                }
                            } else {
                                return Err(ApiError::new_with_json(
                                    500,
                                    "Missing credentials configuration",
                                ));
                            }
                        }
                        let mut param_dict: HashMap<&str, &str> = route
                            .pattern
                            .capture_names()
                            .flatten()
                            .filter_map(|n| Some((n, pattern_match.name(n)?.as_str())))
                            .collect();

                        if stripped_path.len() == 2 {
                            for param in stripped_path[1].split('&') {
                                let pair: Vec<&str> = param.split('=').collect();
                                if pair.len() == 2 {
                                    param_dict.insert(pair[0], pair[1]);
                                }
                            }
                        }
                        let mut response =
                            (route.handler)(data, param_dict).map_err(|mut err| {
                                err.method = Some(method.to_string());
                                err.path = Some(stripped_path[0].to_string());
                                err
                            })?;

                        if let Some(cors) = &self.cors {
                            for (key, value) in &cors.headers {
                                response = response.add_response_header(key, value);
                            }
                        }

                        self.log_response(
                            response.status_code,
                            stripped_path[0],
                            method,
                            peer_addr,
                        )?;

                        return Ok(response);
                    }
                    None => continue,
                }
            }
            let error_response = HttpResponse::new(
                Some(Body::Json(
                    json!({"message": format!("No route found for path {}", path)}),
                )),
                None,
                404,
            );

            self.log_response(
                error_response.status_code,
                stripped_path[0],
                method,
                peer_addr,
            )?;

            Ok(error_response)
        }
    }
    pub fn log_response(
        &self,
        status_code: u16,
        path: &str,
        method: &str,
        peer_addr: IpAddr,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(logger) = &self.logger {
            let time_string = chrono::offset::Local::now()
                .format("%Y-%m-%d %H:%M:%S")
                .to_string();
            let status_code_color = get_status_code_color(status_code);

            let args = vec![
                (time_string, Some(Color::White)),
                (peer_addr.to_string(), Some(Color::Rgb(255, 167, 7))),
                (status_code.to_string(), Some(status_code_color)),
                (method.to_string(), Some(Color::White)),
                (path.to_string(), Some(Color::White)),
            ];

            logger.log_stdout("{} - {} - {} - {} {}", args)?;
        }
        Ok(())
    }
}

impl Default for Router {
    fn default() -> Self {
        Self::new()
    }
}

pub struct Cors {
    headers: Vec<(String, String)>,
}

impl Cors {
    pub fn new() -> Self {
        Cors {
            headers: Vec::new(),
        }
    }

    pub fn with_origins(mut self, value: &str) -> Self {
        self.headers
            .push(("Access-Control-Allow-Origin".to_string(), value.to_string()));
        self
    }

    pub fn with_methods(mut self, value: &str) -> Self {
        self.headers.push((
            "Access-Control-Allow-Methods".to_string(),
            value.to_string(),
        ));
        self
    }

    pub fn with_headers(mut self, value: &str) -> Self {
        self.headers.push((
            "Access-Control-Allow-Headers".to_string(),
            value.to_string(),
        ));
        self
    }

    pub fn with_credentials(mut self, value: &str) -> Self {
        self.headers.push((
            "Access-Control-Allow-Credentials".to_string(),
            value.to_string(),
        ));
        self
    }
}

impl Default for Cors {
    fn default() -> Self {
        Self::new()
    }
}

fn challenge_basic_auth(
    auth_header: &str,
    expectedd_passwd: &str,
    expected_username: &str,
) -> Result<(), ApiError> {
    let auth_parts: Vec<&str> = auth_header.split_whitespace().collect();
    let challenge_response = HttpResponse::new(
        Some(Body::Json(json!({"message": "Unauthorized"}))),
        None,
        401,
    )
    .add_response_header("WWW-Authenticate", "Basic");
    if auth_parts.len() != 2 {
        let err = ApiError::new_with_custom(challenge_response);
        return Err(err);
    }
    let auth_type = auth_parts[0];
    let auth_value = auth_parts[1];
    if auth_type != "Basic" {
        return Err(ApiError::new_with_json(
            401,
            "Unauthorized - unsupported auth challenge",
        ));
    }
    let decoded = BASE64_STANDARD.decode(auth_value).unwrap();
    let decoded_str = String::from_utf8(decoded).unwrap();
    let auth_parts: Vec<&str> = decoded_str.split(':').collect();
    if auth_parts.len() != 2 {
        return Err(ApiError::new_with_custom(challenge_response));
    }
    let username = auth_parts[0];
    let password = auth_parts[1];

    if (username != expected_username) || (password != expectedd_passwd) {
        return Err(ApiError::new_with_custom(challenge_response));
    }
    Ok(())
}