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
260
261
|
/*
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) 2024 metamuffin <metamuffin.org>
*/
pub mod session;
pub mod settings;
use super::{error::MyError, layout::LayoutPage};
use crate::{
database::DataAcid,
routes::ui::{
account::session::Session, error::MyResult, home::rocket_uri_macro_r_home,
layout::DynLayoutPage,
},
uri,
};
use anyhow::anyhow;
use argon2::{password_hash::Salt, Argon2, PasswordHasher};
use chrono::Duration;
use jellybase::{
database::{Ser, TableExt, T_INVITE, T_USER},
CONF,
};
use jellycommon::user::{User, UserPermission};
use rocket::{
form::{Contextual, Form},
get,
http::{Cookie, CookieJar},
post,
response::Redirect,
FromForm, State,
};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
#[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" }
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!"];
p { "Already have an account? " a[href=uri!(r_account_login())] { "Login here" } }
}
},
..Default::default()
}
}
#[derive(FromForm, Serialize, Deserialize)]
pub struct LoginForm {
#[field(validate = len(4..32))]
pub username: String,
#[field(validate = len(..64))]
pub password: String,
#[field(default = 604800)] // one week
pub expire: u64,
}
#[get("/account/login")]
pub fn r_account_login(sess: Option<Session>) -> DynLayoutPage<'static> {
let logged_in = sess.is_some();
let title = if logged_in { "Switch Account" } else { "Login" };
LayoutPage {
title: title.to_string(),
content: markup::new! {
form.account[method="POST", action=""] {
h1 { @title }
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=title];
@if logged_in {
p { "Need another account? " a[href=uri!(r_account_register())] { "Register here" } }
} else {
p { "While logged in, a cookie will be used to identify you." }
p { "Don't have an account yet? " a[href=uri!(r_account_register())] { "Register here" } }
}
}
},
..Default::default()
}
}
#[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."];
}
},
..Default::default()
}
}
#[post("/account/register", data = "<form>")]
pub fn r_account_register_post<'a>(
database: &'a State<DataAcid>,
_sess: Option<Session>,
form: Form<Contextual<'a, RegisterForm>>,
) -> MyResult<DynLayoutPage<'a>> {
let logged_in = _sess.is_some();
let form = match &form.value {
Some(v) => v,
None => return Err(format_form_error(form)),
};
let txn = database.begin_write()?;
let mut invites = txn.open_table(T_INVITE)?;
let mut users = txn.open_table(T_USER)?;
if invites.remove(&*form.invitation)?.is_none() {
Err(anyhow!("invitation invalid"))?;
}
let prev_user = users
.insert(
&*form.username,
Ser(User {
display_name: form.username.clone(),
name: form.username.clone(),
password: hash_password(&form.username, &form.password),
..Default::default()
}),
)?
.map(|x| x.value().0);
if prev_user.is_some() {
Err(anyhow!("username taken"))?;
}
drop(users);
drop(invites);
txn.commit()?;
Ok(LayoutPage {
title: "Registration successful".to_string(),
content: markup::new! {
h1 { @if logged_in {
"Registration successful, you may switch account now."
} else {
"Registration successful, you may log in now."
}}
},
..Default::default()
})
}
#[post("/account/login", data = "<form>")]
pub fn r_account_login_post(
database: &State<DataAcid>,
jar: &CookieJar,
form: Form<Contextual<LoginForm>>,
) -> MyResult<Redirect> {
let form = match &form.value {
Some(v) => v,
None => return Err(format_form_error(form)),
};
jar.add(
Cookie::build((
"session",
login_logic(database, &form.username, &form.password, None, None)?,
))
.permanent()
.build(),
);
Ok(Redirect::found(rocket::uri!(r_home())))
}
#[post("/account/logout")]
pub fn r_account_logout_post(jar: &CookieJar) -> MyResult<Redirect> {
jar.remove_private(Cookie::build("session"));
Ok(Redirect::found(rocket::uri!(r_home())))
}
pub fn login_logic(
database: &DataAcid,
username: &str,
password: &str,
expire: Option<i64>,
drop_permissions: Option<HashSet<UserPermission>>,
) -> MyResult<String> {
// hashing the password regardless if the accounts exists to prevent timing attacks
let password = hash_password(username, password);
let mut user = T_USER
.get(database, username)?
.ok_or(anyhow!("invalid password"))?;
if user.password != password {
Err(anyhow!("invalid password"))?
}
if let Some(ep) = drop_permissions {
// remove all grant perms that are in `ep`
user.permissions
.0
.retain(|p, val| if *val { !ep.contains(p) } else { true })
}
Ok(session::token::create(
user.name,
user.permissions,
Duration::days(CONF.login_expire.min(expire.unwrap_or(i64::MAX))),
))
}
pub 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(username: &str, password: &str) -> Vec<u8> {
Argon2::default()
.hash_password(
format!("{username}\0{password}").as_bytes(),
<&str as TryInto<Salt>>::try_into("IYMa13osbNeLJKnQ1T8LlA").unwrap(),
)
.unwrap()
.hash
.unwrap()
.as_bytes()
.to_vec()
}
|