aboutsummaryrefslogtreecommitdiff
path: root/src/routes.rs
blob: 723e0ea7cb08dcc90a9d536cdbe5e60eb422bcf6 (plain)
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
use hyper::{Body, Method, Request, Response};
use serde::Deserialize;
use serde_urlencoded;
use sqlx::sqlite::SqlitePool;
use std::collections::HashMap;
use std::convert::Infallible;
use tera::Tera;
use url::form_urlencoded;

use crate::controller;
use crate::controller::utils::file;
use crate::controller::utils::with_headers;
use crate::controller::wallet::Wallet;
use crate::db;
use crate::model::config::Config;
use crate::model::user::User;

pub async fn routes(
    config: Config,
    pool: SqlitePool,
    assets: HashMap<String, String>,
    templates: Tera,
    request: Request<Body>,
) -> Result<Response<Body>, Infallible> {
    let method = request.method();
    let uri = request.uri();
    let path = &uri.path().split('/').collect::<Vec<&str>>()[1..];

    let response = match (method, path) {
        (&Method::HEAD, ["status"]) => controller::utils::ok(),
        (&Method::GET, ["status"]) => controller::utils::text("ok".to_string()),
        (&Method::GET, ["login"]) => {
            controller::login::page(&assets, &templates, None).await
        }
        (&Method::POST, ["login"]) => {
            controller::login::login(
                config,
                &assets,
                &templates,
                body_form(request).await,
                pool,
            )
            .await
        }
        (&Method::GET, ["assets", _, filename]) => match *filename {
            "main.js" => file("assets/main.js", "text/javascript").await,
            "chart.js" => file("assets/chart.js", "text/javascript").await,
            "main.css" => file("assets/main.css", "text/css").await,
            "icon.png" => file("assets/icon.png", "image/png").await,
            _ => controller::utils::not_found(),
        },
        _ => match connected_user(&pool, &request).await {
            Some(user) => {
                let wallet = Wallet {
                    pool,
                    assets,
                    templates,
                    user,
                };
                authenticated_routes(config, wallet, request).await
            }
            None => controller::utils::redirect("/login"),
        },
    };

    Ok(with_security_headers(response))
}

// Apply security headers, see https://infosec.mozilla.org/guidelines/web_security
fn with_security_headers(response: Response<Body>) -> Response<Body> {
    with_headers(
        response,
        vec![
            // Allows fine-grained control over where resources can be loaded from. This is the
            // best method to prevent cross-site scripting (XSS) vulnerabilities.
            (
                hyper::header::CONTENT_SECURITY_POLICY,
                "default-src 'self'; frame-ancestors 'none'",
            ),
            // Notifies user agents to only connect to a given site over HTTPS, even if the scheme
            // chosen was HTTP.
            (
                hyper::header::STRICT_TRANSPORT_SECURITY,
                "max-age=63072000; includeSubDomains; preload",
            ),
            // Allows fine-grained control over how and when browsers transmit the HTTP Referer
            // header.
            (hyper::header::REFERRER_POLICY, "same-origin"),
            // Prevent loading scripts and stylesheets unless the server indicates the correct MIME
            // type.
            (hyper::header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
            // [Older browser] Controls how this site can be framed within an iframe.
            (hyper::header::X_FRAME_OPTIONS, "DENY"),
            // [Older browser] Stops pages from loading when they detect reflected cross-site
            // scripting (XSS) attacks (IE and Chrome).
            (hyper::header::X_XSS_PROTECTION, "1; mode=block"),
        ],
    )
}

async fn connected_user(
    pool: &SqlitePool,
    request: &Request<Body>,
) -> Option<User> {
    let cookie = request.headers().get("COOKIE")?.to_str().ok()?;
    let mut xs = cookie.split('=');
    xs.next();
    let login_token = xs.next()?;
    db::users::get_by_login_token(&pool, login_token.to_string()).await
}

async fn authenticated_routes(
    config: Config,
    wallet: Wallet,
    request: Request<Body>,
) -> Response<Body> {
    let method = request.method();
    let uri = request.uri();
    let path = &uri.path().split('/').collect::<Vec<&str>>()[1..];
    let query = uri.query();

    match (method, path) {
        (&Method::GET, [""]) => {
            controller::payments::table(&wallet, parse_query(query)).await
        }
        (&Method::GET, ["payment"]) => {
            controller::payments::create_form(&wallet, parse_query(query)).await
        }
        (&Method::POST, ["payment", "create"]) => {
            controller::payments::create(
                &wallet,
                parse_query(query),
                body_form(request).await,
            )
            .await
        }
        (&Method::GET, ["payment", "category"]) => {
            controller::payments::search_category(&wallet, parse_query(query))
                .await
        }
        (&Method::GET, ["payment", id]) => {
            controller::payments::update_form(
                parse_id(id),
                &wallet,
                parse_query(query),
            )
            .await
        }
        (&Method::POST, ["payment", id, "update"]) => {
            controller::payments::update(
                parse_id(id),
                &wallet,
                parse_query(query),
                body_form(request).await,
            )
            .await
        }
        (&Method::POST, ["payment", id, "delete"]) => {
            controller::payments::delete(
                parse_id(id),
                &wallet,
                parse_query(query),
            )
            .await
        }
        (&Method::GET, ["incomes"]) => {
            controller::incomes::table(&wallet, parse_query(query)).await
        }
        (&Method::GET, ["income"]) => {
            controller::incomes::create_form(&wallet, parse_query(query)).await
        }
        (&Method::POST, ["income", "create"]) => {
            controller::incomes::create(
                &wallet,
                parse_query(query),
                body_form(request).await,
            )
            .await
        }
        (&Method::GET, ["income", id]) => {
            controller::incomes::update_form(
                parse_id(id),
                &wallet,
                parse_query(query),
            )
            .await
        }
        (&Method::POST, ["income", id, "update"]) => {
            controller::incomes::update(
                parse_id(id),
                &wallet,
                parse_query(query),
                body_form(request).await,
            )
            .await
        }
        (&Method::POST, ["income", id, "delete"]) => {
            controller::incomes::delete(
                parse_id(id),
                &wallet,
                parse_query(query),
            )
            .await
        }
        (&Method::GET, ["categories"]) => {
            controller::categories::table(&wallet, parse_query(query)).await
        }
        (&Method::GET, ["category"]) => {
            controller::categories::create_form(&wallet).await
        }
        (&Method::POST, ["category", "create"]) => {
            controller::categories::create(&wallet, body_form(request).await)
                .await
        }
        (&Method::GET, ["category", id]) => {
            controller::categories::update_form(parse_id(id), &wallet).await
        }
        (&Method::POST, ["category", id, "update"]) => {
            controller::categories::update(
                parse_id(id),
                &wallet,
                body_form(request).await,
            )
            .await
        }
        (&Method::POST, ["category", id, "delete"]) => {
            controller::categories::delete(parse_id(id), &wallet).await
        }
        (&Method::GET, ["balance"]) => controller::balance::get(&wallet).await,
        (&Method::GET, ["statistics"]) => {
            controller::statistics::get(&wallet).await
        }
        (&Method::POST, ["logout"]) => {
            controller::login::logout(config, &wallet).await
        }
        _ => controller::error::error(
            &wallet,
            "Page introuvable",
            "La page que recherchez n’existe pas.",
        ),
    }
}

fn parse_query<'a, T: Deserialize<'a>>(query: Option<&'a str>) -> T {
    serde_urlencoded::from_str(query.unwrap_or("")).unwrap()
}

async fn body_form(request: Request<Body>) -> HashMap<String, String> {
    match hyper::body::to_bytes(request).await {
        Ok(bytes) => form_urlencoded::parse(bytes.as_ref())
            .into_owned()
            .collect::<HashMap<String, String>>(),
        Err(_) => HashMap::new(),
    }
}

fn parse_id(str: &str) -> i64 {
    str.parse::<i64>().unwrap()
}