aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/ui/account/mod.rs
blob: e7031ff680b39814da06e4ac7dec7f528ddab3a9 (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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2023 metamuffin <metamuffin.org>
*/
pub mod admin;
pub mod session;

use super::{error::MyError, layout::LayoutPage};
use crate::{
    database::{Database, User},
    routes::ui::{error::MyResult, home::rocket_uri_macro_r_home, layout::DynLayoutPage},
    CONF,
};
use anyhow::anyhow;
use argon2::{Argon2, PasswordHasher};
use rocket::{
    form::{Contextual, Form},
    get,
    http::{Cookie, CookieJar},
    post,
    response::Redirect,
    uri, FromForm, State,
};

#[derive(FromForm)]
pub struct RegisterForm {
    #[field(validate = len(8..128))]
    pub invitation: String,
    #[field(validate = len(4..32))]
    pub username: String,
    #[field(validate = len(4..64))]
    pub password: String,
}

#[get("/account/register")]
pub async fn r_account_register() -> DynLayoutPage<'static> {
    LayoutPage {
        title: "Register".to_string(),
        content: markup::new! {
            form.account[method="POST", action=""] {
                h1 { "Register for " @CONF.brand  }

                label[for="inp-invitation"] { "Invite Code: " }
                input[type="text", id="inp-invitation", name="invitation"]; br;

                label[for="inp-username"] { "Username: " }
                input[type="text", id="inp-username", name="username"]; br;
                label[for="inp-password"] { "Password: " }
                input[type="password", id="inp-password", name="password"]; br;

                input[type="submit", value="Register now!"];
            }
        },
    }
}

#[derive(FromForm)]
pub struct LoginForm {
    #[field(validate = len(4..32))]
    pub username: String,
    #[field(validate = len(..64))]
    pub password: String,
}

#[get("/account/login")]
pub fn r_account_login() -> DynLayoutPage<'static> {
    LayoutPage {
        title: "Log in".to_string(),
        content: markup::new! {
            form.account[method="POST", action=""] {
                h1 { "Log in to your Account" }

                label[for="inp-username"] { "Username: " }
                input[type="text", id="inp-username", name="username"]; br;
                label[for="inp-password"] { "Password: " }
                input[type="password", id="inp-password", name="password"]; br;

                input[type="submit", value="Login"];

                p { "While logged in, a cookie will be used to identify you." }
            }
        },
    }
}

#[get("/account/logout")]
pub fn r_account_logout() -> DynLayoutPage<'static> {
    LayoutPage {
        title: "Log out".to_string(),
        content: markup::new! {
            form.account[method="POST", action=""] {
                h1 { "Log out" }
                input[type="submit", value="Log out."];
            }
        },
    }
}

#[post("/account/register", data = "<form>")]
pub fn r_account_register_post<'a>(
    database: &'a State<Database>,
    form: Form<Contextual<'a, RegisterForm>>,
) -> MyResult<DynLayoutPage<'a>> {
    let form = match &form.value {
        Some(v) => v,
        None => return Err(format_form_error(form)),
    };

    if database.invites.remove(&form.invitation).unwrap().is_none() {
        return Err(MyError(anyhow!("invitation invalid")));
    }
    match database
        .users
        .compare_and_swap(
            &form.username,
            None,
            Some(&User {
                display_name: form.username.clone(),
                name: form.username.clone(),
                password: hash_password(&form.password),
                admin: false,
            }),
        )
        .unwrap()
    {
        Ok(_) => Ok(LayoutPage {
            title: "Registration successful".to_string(),
            content: markup::new! {
                h1 { "Registration successful, you may log in now." }
            },
        }),
        Err(_) => Err(MyError(anyhow!("username is taken"))),
    }
}

#[post("/account/login", data = "<form>")]
pub fn r_account_login_post(
    database: &State<Database>,
    jar: &CookieJar,
    form: Form<Contextual<LoginForm>>,
) -> MyResult<Redirect> {
    let form = match &form.value {
        Some(v) => v,
        None => return Err(format_form_error(form)),
    };

    // hashing the password regardless if the accounts exists to prevent timing attacks
    let password = hash_password(&form.password);

    let user = database
        .users
        .get(&form.username)?
        .ok_or(anyhow!("invalid password"))?;

    if user.password != password {
        Err(anyhow!("invalid password"))?
    }

    jar.add_private(Cookie::build("user", user.name).permanent().finish());

    Ok(Redirect::found(uri!(r_home())))
}

#[post("/account/logout")]
pub fn r_account_logout_post(jar: &CookieJar) -> MyResult<Redirect> {
    jar.remove_private(Cookie::named("user"));
    Ok(Redirect::found(uri!(r_home())))
}

fn format_form_error<T>(form: Form<Contextual<T>>) -> MyError {
    let mut k = String::from("form validation failed:");
    for e in form.context.errors() {
        k += &format!(
            "\n\t{}: {e}",
            e.name
                .as_ref()
                .map(|e| e.to_string())
                .unwrap_or("<unknown>".to_string())
        )
    }
    MyError(anyhow!(k))
}

pub fn hash_password(s: &str) -> Vec<u8> {
    Argon2::default()
        .hash_password(s.as_bytes(), r"IYMa13osbNeLJKnQ1T8LlA")
        .unwrap()
        .hash
        .unwrap()
        .as_bytes()
        .to_vec()
}