OXYGENHUB
# bf1ab3458db1 oxygenhub / crates / hub / src / web / session.rs
7.6 KiB · Rust · last changed Milestone 0.2: accounts and access 1 month ago source blame history raw
1
//! Sign in, sign out and registration (hub spec §5.1).
2
3
use super::{Error, Page, Shell};
4
use crate::auth::{self, totp, Viewer};
5
use crate::db::{self, accounts};
6
use crate::Shared;
7
use askama::Template;
8
use axum::extract::{Form, Query, State};
9
use axum::http::header;
10
use axum::response::{IntoResponse, Redirect, Response};
11
use serde::Deserialize;
12
13
#[derive(Template)]
14
#[template(path = "login.html")]
15
pub struct LoginPage {
16
    shell: Shell,
17
    error: Option<String>,
18
    next: String,
19
    /// Second step: the password was right, a one-time code is needed.
20
    totp_for: Option<String>,
21
}
22
23
#[derive(Deserialize)]
24
pub struct NextQuery {
25
    next: Option<String>,
26
}
27
28
fn safe_next(next: Option<String>) -> String {
29
    match next {
30
        Some(n) if n.starts_with('/') && !n.starts_with("//") => n,
31
        _ => "/".into(),
32
    }
33
}
34
35
pub async fn login_form(State(app): State<Shared>, viewer: Viewer, Query(q): Query<NextQuery>) -> Response {
36
    if viewer.signed_in() {
37
        return Redirect::to(&safe_next(q.next)).into_response();
38
    }
39
    Page(LoginPage { shell: Shell::new(&app, "/login", &viewer), error: None, next: safe_next(q.next), totp_for: None }).into_response()
40
}
41
42
#[derive(Deserialize)]
43
pub struct LoginForm {
44
    username: String,
45
    password: String,
46
    #[serde(default)]
47
    code: String,
48
    #[serde(default)]
49
    next: String,
50
}
51
52
pub async fn login(State(app): State<Shared>, viewer: Viewer, Form(f): Form<LoginForm>) -> Result<Response, Error> {
53
    let shell = Shell::new(&app, "/login", &viewer);
54
    let next = safe_next(Some(f.next.clone()));
55
    let fail = |msg: &str, totp_for: Option<String>| {
56
        Page(LoginPage { shell: shell.clone(), error: Some(msg.into()), next: next.clone(), totp_for }).into_response()
57
    };
58
    let username = f.username.trim().to_string();
59
    let account = accounts::account_by_name(&app.db, &username).await.map_err(|e| Error::from_db(shell.clone(), e))?;
60
    let Some(account) = account.filter(|a| auth::verify_password(&a.password_hash, &f.password)) else {
61
        accounts::audit(&app.db, None, "login.failed", &username, "").await.ok();
62
        return Ok(fail("Wrong username or password.", None));
63
    };
64
    if account.banned {
65
        return Ok(fail("This account is banned.", None));
66
    }
67
    if let Some(secret) = &account.totp_secret {
68
        if f.code.trim().is_empty() {
69
            return Ok(fail("Enter the code from your authenticator app.", Some(username)));
70
        }
71
        let now = (db::now_ms() / 1000) as u64;
72
        if !totp::verify(secret, &f.code, now) {
73
            match totp::use_recovery_code(&account.recovery_codes, &f.code) {
74
                Some(rest) => {
75
                    accounts::set_totp(&app.db, account.id, Some(secret), &rest).await.map_err(|e| Error::from_db(shell.clone(), e))?
76
                }
77
                None => {
78
                    accounts::audit(&app.db, Some(&account), "login.totp_failed", &username, "").await.ok();
79
                    return Ok(fail("That code is not right.", Some(username)));
80
                }
81
            }
82
        }
83
    }
84
    accounts::audit(&app.db, Some(&account), "login", &username, "").await.ok();
85
    Ok(signed_in(&app, &account, &next))
86
}
87
88
/// A redirect that sets the session cookie.
89
pub fn signed_in(app: &Shared, account: &accounts::Account, to: &str) -> Response {
90
    let value = auth::session_value(&app.cookie_key, &account.username, &account.session_salt);
91
    let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" };
92
    let cookie = format!("{}={value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000{secure}", auth::SESSION_COOKIE);
93
    ([(header::SET_COOKIE, cookie)], Redirect::to(to)).into_response()
94
}
95
96
#[derive(Deserialize)]
97
pub struct CsrfForm {
98
    #[serde(rename = "_csrf")]
99
    pub csrf: String,
100
}
101
102
pub async fn logout(State(app): State<Shared>, viewer: Viewer, Form(f): Form<CsrfForm>) -> Response {
103
    if !viewer.csrf_ok(&f.csrf) {
104
        return Redirect::to("/").into_response();
105
    }
106
    if let Some(a) = viewer.account() {
107
        accounts::audit(&app.db, Some(a), "logout", &a.username, "").await.ok();
108
    }
109
    let cookie = format!("{}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0", auth::SESSION_COOKIE);
110
    ([(header::SET_COOKIE, cookie)], Redirect::to("/")).into_response()
111
}
112
113
#[derive(Template)]
114
#[template(path = "register.html")]
115
pub struct RegisterPage {
116
    shell: Shell,
117
    error: Option<String>,
118
    mode: String,
119
    first: bool,
120
    invite: String,
121
}
122
123
/// The registration mode: the settings table overrides `hub.toml`.
124
pub async fn registration_mode(app: &Shared) -> String {
125
    accounts::setting(&app.db, "registration_mode").await.ok().flatten().unwrap_or_else(|| app.config.registration.mode.clone())
126
}
127
128
#[derive(Deserialize)]
129
pub struct InviteQuery {
130
    invite: Option<String>,
131
}
132
133
pub async fn register_form(State(app): State<Shared>, viewer: Viewer, Query(q): Query<InviteQuery>) -> Result<Response, Error> {
134
    if viewer.signed_in() {
135
        return Ok(Redirect::to("/").into_response());
136
    }
137
    let shell = Shell::new(&app, "/register", &viewer);
138
    let first = accounts::account_count(&app.db).await.map_err(|e| Error::from_db(shell.clone(), e))? == 0;
139
    Ok(Page(RegisterPage { shell, error: None, mode: registration_mode(&app).await, first, invite: q.invite.unwrap_or_default() })
140
        .into_response())
141
}
142
143
#[derive(Deserialize)]
144
pub struct RegisterForm {
145
    username: String,
146
    email: String,
147
    password: String,
148
    #[serde(default)]
149
    invite: String,
150
}
151
152
pub async fn register(State(app): State<Shared>, viewer: Viewer, Form(f): Form<RegisterForm>) -> Result<Response, Error> {
153
    let shell = Shell::new(&app, "/register", &viewer);
154
    let first = accounts::account_count(&app.db).await.map_err(|e| Error::from_db(shell.clone(), e))? == 0;
155
    let mode = registration_mode(&app).await;
156
    let fail = |msg: &str| {
157
        Page(RegisterPage { shell: shell.clone(), error: Some(msg.into()), mode: mode.clone(), first, invite: f.invite.clone() })
158
            .into_response()
159
    };
160
    let username = f.username.trim().to_string();
161
    if !crate::repos::names::valid_owner(&username) {
162
        return Ok(fail("A username is letters, digits, dots, dashes and underscores, and is not a reserved word."));
163
    }
164
    if let Err(e) = auth::password_ok(&f.password) {
165
        return Ok(fail(e));
166
    }
167
    if !first {
168
        match mode.as_str() {
169
            "open" => {}
170
            "invite" => {
171
                let ok = !f.invite.trim().is_empty()
172
                    && accounts::invitation_unused(&app.db, f.invite.trim()).await.map_err(|e| Error::from_db(shell.clone(), e))?;
173
                if !ok {
174
                    return Ok(fail("Registration needs a valid invitation code."));
175
                }
176
            }
177
            _ => return Ok(fail("Registration is closed.")),
178
        }
179
    }
180
    if accounts::account_by_name(&app.db, &username).await.map_err(|e| Error::from_db(shell.clone(), e))?.is_some()
181
        || accounts::org_by_name(&app.db, &username).await.map_err(|e| Error::from_db(shell.clone(), e))?.is_some()
182
    {
183
        return Ok(fail("That name is taken."));
184
    }
185
    let hash = auth::hash_password(&f.password).map_err(|e| Error::bad(shell.clone(), e.to_string()))?;
186
    let account = accounts::create_account(&app.db, &username, f.email.trim(), &hash, &auth::random_hex(16), first)
187
        .await
188
        .map_err(|e| Error::from_db(shell.clone(), e))?;
189
    if !first && mode == "invite" {
190
        accounts::use_invitation(&app.db, f.invite.trim(), account.id).await.ok();
191
    }
192
    accounts::audit(&app.db, Some(&account), "register", &username, if first { "first account: administrator" } else { "" }).await.ok();
193
    Ok(signed_in(&app, &account, "/"))
194
}