🗝
summary refs log tree commit diff
path: root/src/server/login.rs
blob: 8353317132695b2723f8c18e52bcf8208aa08706 (plain) (blame)
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
use std::time::Duration;

use argon2::{Argon2, PasswordVerifier};
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::{IntoResponse, Redirect, Response},
    routing::get,
    Form, Router,
};
use axum_extra::extract::{
    cookie::{Cookie, SameSite},
    CookieJar,
};
use maud::{html, PreEscaped};
use tap::Tap;

use crate::server::store::Store;

use super::{render_html, ApiState, CookieDomain, MakeError, MakeErrorMessage};

pub fn bind(app: Router<ApiState>) -> Router<ApiState> {
    app.route("/login", get(handle_login_get).post(handle_login_post))
        .route("/logout", get(logout))
        .route(
            "/invite/:invite",
            get(handle_invite_get).post(handle_invite_post),
        )
}

fn make_form(status: StatusCode, error: Option<&str>, submit: &str) -> Response {
    render_html(
        html!(title {"login"}),
        html! {
            @if let Some(error) = error {
                p { "error: " (PreEscaped(error)) }
            }
            form action="" method="post" {
                label for="name" { "name:" }
                input type="text" id="name" name="name" {}
                label for="password" { "password:" }
                input type="password" id="password" name="password" {}
                input type="submit" value=(submit) {}
            }
        },
    )
    .tap_mut(|response| *response.status_mut() = status)
}

#[axum::debug_handler]
async fn handle_login_get() -> Response {
    make_form(StatusCode::OK, None, "login")
}

#[derive(serde::Deserialize)]
struct FormData {
    name: String,
    password: String,
}

#[axum::debug_handler(state = ApiState)]
async fn handle_login_post(
    jar: CookieJar,
    State(store): State<Store>,
    State(CookieDomain(cookie_domain)): State<CookieDomain>,
    Form(form): Form<FormData>,
) -> Result<Response, Response> {
    // read lock scope
    {
        let account = store.get_account(&form.name).await.ok_or_else(|| {
            make_form(StatusCode::FORBIDDEN, Some("invalid credentials"), "login")
        })?;
        Argon2::default()
            .verify_password(form.password.as_bytes(), &account.password.parsed())
            .ok()
            .ok_or_else(|| {
                make_form(StatusCode::FORBIDDEN, Some("invalid credentials"), "login")
            })?;
    }
    let token = store
        .create_token(&form.name)
        .await
        .make_error()?
        .error_message(
            StatusCode::INTERNAL_SERVER_ERROR,
            "account disappeared while generating token",
        )?;

    let mut cookie = Cookie::new("dissociate-token", token);
    cookie.set_http_only(true);
    cookie.set_max_age(Duration::from_secs(60 * 60 * 24 * 29).try_into().ok());
    cookie.set_path("/");
    cookie.set_same_site(SameSite::None);
    cookie.set_secure(true);
    if let Some(cookie_domain) = cookie_domain {
        cookie.set_domain(cookie_domain);
    }

    Ok((jar.add(cookie), Redirect::to("/")).into_response())
}

#[axum::debug_handler]
async fn logout(jar: CookieJar) -> Response {
    (
        jar.remove(Cookie::from("dissociate-token")),
        Redirect::to("/login"),
    )
        .into_response()
}

fn invite_error() -> Response {
    render_html(
        html!(),
        html! {
            h1 { "unknown invite" }
            a href="/" { "return home" }
        },
    )
    .tap_mut(|response| *response.status_mut() = StatusCode::NOT_FOUND)
}

#[axum::debug_handler]
async fn handle_invite_get(Path(invite): Path<String>, State(store): State<Store>) -> Response {
    if !store.check_invite(&invite).await {
        return invite_error();
    }
    make_form(StatusCode::OK, None, "create account")
}

const NAME_ERROR: &str = "invalid name
requirements:
must not be empty
must not exceed 32 characters
must not contain control characters";
#[axum::debug_handler(state = ApiState)]
async fn handle_invite_post(
    jar: CookieJar,
    Path(invite): Path<String>,
    State(store): State<Store>,
    State(CookieDomain(cookie_domain)): State<CookieDomain>,
    Form(form): Form<FormData>,
) -> Result<Response, Response> {
    if form.name.to_ascii_lowercase() == "empty" || form.password.to_ascii_lowercase() == "empty" {
        return Err(make_form(
            StatusCode::BAD_REQUEST,
            Some("are you jokester?"),
            "create account",
        ));
    }
    if form.name.is_empty() || form.name.len() > 32 || form.name.chars().any(|ch| ch.is_control()) {
        return Err(make_form(
            StatusCode::BAD_REQUEST,
            Some(&NAME_ERROR.replace('\n', "<br>")),
            "create account",
        ));
    }
    if form.password.is_empty() {
        return Err(make_form(
            StatusCode::BAD_REQUEST,
            Some("password cannot be empty"),
            "create account",
        ));
    }

    if store.get_account(&form.name).await.is_some() {
        return Err(make_form(
            StatusCode::CONFLICT,
            Some("name taken"),
            "create account",
        ));
    }

    if !store.use_invite(&invite).await.make_error()? {
        return Err(invite_error());
    }

    if !store
        .create_account(&form.name, &form.password)
        .await
        .make_error()?
    {
        return Err(make_form(
            StatusCode::CONFLICT,
            Some("name taken"),
            "create account",
        ));
    }
    let token = store
        .create_token(&form.name)
        .await
        .make_error()?
        .error_message(
            StatusCode::INTERNAL_SERVER_ERROR,
            "account disappeared while generating token",
        )?;

    let mut cookie = Cookie::new("dissociate-token", token);
    cookie.set_http_only(true);
    cookie.set_max_age(Duration::from_secs(60 * 60 * 24 * 29).try_into().ok());
    cookie.set_path("/");
    cookie.set_same_site(SameSite::None);
    cookie.set_secure(true);
    if let Some(cookie_domain) = cookie_domain {
        cookie.set_domain(cookie_domain);
    }

    Ok((jar.add(cookie), Redirect::to("/")).into_response())
}