1
use askama::Template;
2
use axum::response::{Html, IntoResponse, Response};
3
use axum_extra::extract::CookieJar;
4

            
5
use crate::response::WebError;
6

            
7
pub mod account;
8
pub mod commodity;
9
pub mod config;
10
pub mod forms;
11
pub mod report;
12
pub mod script;
13
pub mod tag;
14
pub mod template;
15
pub mod transaction;
16

            
17
/// Whether the cookie `name` holds a token of `kind` that verifies. A directory
18
/// outage counts as not verified: this only decides which navigation the index
19
/// shows.
20
8
async fn holds_valid_token(
21
8
    cookie_jar: &CookieJar,
22
8
    name: &str,
23
8
    kind: crate::token::TokenType,
24
8
) -> bool {
25
8
    match cookie_jar.get(name) {
26
1
        Some(cookie) => crate::auth_keys::verify(cookie.value(), kind)
27
1
            .await
28
1
            .is_ok_and(|details| details.is_some()),
29
7
        None => false,
30
    }
31
8
}
32

            
33
/// The access cookie lives minutes, the refresh cookie days, and a request
34
/// that carries only the latter is refreshed by the middleware.
35
4
pub async fn index(cookie_jar: CookieJar) -> impl IntoResponse {
36
    let is_logged_in =
37
4
        holds_valid_token(&cookie_jar, "access_token", crate::token::TokenType::Access).await
38
4
            || holds_valid_token(
39
4
                &cookie_jar,
40
4
                "refresh_token",
41
4
                crate::token::TokenType::Refresh,
42
4
            )
43
4
            .await;
44

            
45
4
    let template = IndexTemplate {
46
4
        is_logged_in,
47
4
        scripting_enabled: true,
48
4
    };
49

            
50
4
    HtmlTemplate(template)
51
4
}
52

            
53
#[derive(Template)]
54
#[template(path = "pages/index.html")]
55
struct IndexTemplate {
56
    is_logged_in: bool,
57
    scripting_enabled: bool,
58
}
59

            
60
2
pub async fn register() -> impl IntoResponse {
61
2
    let template = RegisterTemplate {};
62
2
    HtmlTemplate(template)
63
2
}
64

            
65
#[derive(Template)]
66
#[template(path = "pages/register.html")]
67
struct RegisterTemplate;
68

            
69
1
pub async fn login() -> impl IntoResponse {
70
1
    HtmlTemplate(crate::login::LoginTemplate::default())
71
1
}
72

            
73
/// A wrapper type that we'll use to encapsulate HTML parsed by askama into valid HTML for axum to serve.
74
struct HtmlTemplate<T>(T);
75

            
76
/// Allows us to convert Askama HTML templates into valid HTML for axum to serve in the response.
77
impl<T> IntoResponse for HtmlTemplate<T>
78
where
79
    T: Template,
80
{
81
161
    fn into_response(self) -> Response {
82
161
        match self.0.render() {
83
159
            Ok(html) => Html(html).into_response(),
84
2
            Err(err) => WebError::internal("Failed to render template", err).into_response(),
85
        }
86
161
    }
87
}
88

            
89
#[cfg(test)]
90
#[path = "pages_tests.rs"]
91
mod tests;