aboutsummaryrefslogtreecommitdiff
path: root/src/routes.rs
blob: ae87d39e1aa113f509bfaa9e4ae385be548a4f99 (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
use http_body_util::{BodyExt, Full};
use hyper::body::{Bytes, Incoming};
use hyper::{Method, Request, Response};
use serde::Deserialize;
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::wallet::Wallet;
use crate::db;
use crate::model::config::Config;
use crate::model::user::User;
use crate::utils::cookie;

pub async fn routes(
    config: Config,
    pool: SqlitePool,
    assets: HashMap<String, String>,
    templates: Tera,
    request: Request<Incoming>,
) -> Result<Response<Full<Bytes>>, 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(&config, &pool, &request).await {
            Some(user) => {
                let wallet = Wallet {
                    pool,
                    assets,
                    templates,
                    user,
                };
                authenticated_routes(&config, wallet, request).await
            }
            None => controller::utils::redirect("/login"),
        },
    };

    Ok(response)
}

async fn connected_user(
    config: &Config,
    pool: &SqlitePool,
    request: &Request<Incoming>,
) -> Option<User> {
    let cookie = request.headers().get("COOKIE")?.to_str().ok()?;
    let login_token = cookie::extract_token(config, cookie).ok()?;
    db::users::get_by_login_token(pool, login_token.to_string()).await
}

async fn authenticated_routes(
    config: &Config,
    wallet: Wallet,
    request: Request<Incoming>,
) -> Response<Full<Bytes>> {
    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 vous 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<Incoming>) -> HashMap<String, String> {
    match request.collect().await {
        // Warning: this is a simplified use case. In principle names can appear multiple times in
        // a form, and the values should be rolled up into a HashMap<String, Vec<String>>. However
        // in this example the simpler approach is sufficient.
        Ok(content) => form_urlencoded::parse(content.to_bytes().as_ref())
            .into_owned()
            .collect::<HashMap<String, String>>(),
        Err(_) => HashMap::new(),
    }
}

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