1
use argon2::{Argon2, PasswordHasher};
2
use askama::Template;
3
use axum::{Json, http::StatusCode, response::Html};
4
use rust_i18n::t;
5
use server::command::CmdError;
6
use server::command::user::{Account, NewUser};
7
use server::config::ConfigError;
8
use server::provision::Provisioned;
9

            
10
use crate::{model::RegisterUserSchema, response::WebError};
11

            
12
#[derive(Template)]
13
#[template(
14
    source = r#"<div class="success-alert">User {{ email }} created</div>"#,
15
    ext = "html"
16
)]
17
struct Created<'a> {
18
    email: &'a str,
19
}
20

            
21
3
fn email_conflict() -> WebError {
22
3
    WebError::new(
23
3
        StatusCode::CONFLICT,
24
3
        t!("User with that email already exists").to_string(),
25
3
    )
26
3
}
27

            
28
9
fn insert_failure(error: CmdError) -> WebError {
29
9
    match error {
30
2
        CmdError::Config(ConfigError::EmailTaken) => email_conflict(),
31
        CmdError::Config(ConfigError::EmailBlank) => {
32
3
            WebError::bad_request(t!("Email must not be empty").to_string())
33
        }
34
4
        other => WebError::from(other),
35
    }
36
9
}
37

            
38
61
fn hash_password(password: &str) -> Result<String, WebError> {
39
61
    Argon2::default()
40
61
        .hash_password(password.as_bytes())
41
61
        .map(|hash| hash.to_string())
42
        .map_err(|e| WebError::internal("Password hashing failed", e))
43
61
}
44

            
45
/// Drops a database this request provisioned; one it merely found belongs to someone's ledger.
46
async fn drop_orphan(provisioned: &Provisioned, user_id: uuid::Uuid) {
47
    if !provisioned.created {
48
        return;
49
    }
50
    if let Err(e) = server::provision::drop_user_database(user_id).await {
51
        tracing::error!("{} {e}", t!("Failed to clean up provisioned database:"));
52
    }
53
}
54

            
55
/// Creates the user row.
56
///
57
/// `verified` is set by `create_user`, not left to the column default:
58
/// registration is admin-gated, so the admin has already vouched for the
59
/// account, and nothing ever sets the flag afterwards.
60
59
async fn create_user(
61
59
    body: &RegisterUserSchema,
62
59
    user_id: uuid::Uuid,
63
59
    provisioned: &Provisioned,
64
59
    public_key: &str,
65
59
    password_hash: &str,
66
59
) -> Result<Account, WebError> {
67
59
    let insert = server::command::user::create_user(NewUser {
68
59
        id: user_id,
69
59
        name: &body.name,
70
59
        email: &body.email,
71
59
        password_hash,
72
59
        database_name: &provisioned.database_name,
73
59
        jwt_public_key: public_key,
74
59
    })
75
59
    .await;
76
59
    match insert {
77
59
        Ok(account) => Ok(account),
78
        Err(e) => {
79
            // A concurrent registration may have won the UNIQUE(email) race.
80
            drop_orphan(provisioned, user_id).await;
81
            Err(insert_failure(e))
82
        }
83
    }
84
59
}
85

            
86
61
pub async fn register_user_handler(
87
61
    Json(body): Json<RegisterUserSchema>,
88
61
) -> Result<Html<String>, WebError> {
89
61
    server::command::user::validate_email(&body.email).map_err(|e| insert_failure(e.into()))?;
90
60
    let taken = server::command::user::email_taken(&body.email)
91
60
        .await
92
60
        .map_err(WebError::from)?;
93
60
    if taken {
94
1
        return Err(email_conflict());
95
59
    }
96

            
97
59
    let password_hash = hash_password(&body.password)?;
98
59
    let user_id = uuid::Uuid::new_v4();
99
    // The private half goes into the user's own database, the public half
100
    // into the global users row.
101
59
    let keypair = server::auth_keys::generate()
102
59
        .await
103
        .map_err(|e| WebError::internal("Key generation failed", e))?;
104
59
    let provisioned = server::provision::provision_user_database(user_id)
105
59
        .await
106
        .map_err(|e| WebError::internal("Provisioning failed", e))?;
107

            
108
59
    if let Err(e) = server::provision::store_user_private_key(
109
59
        &provisioned.database_name,
110
59
        &keypair.private_pem_b64,
111
59
    )
112
59
    .await
113
    {
114
        drop_orphan(&provisioned, user_id).await;
115
        return Err(WebError::internal("Storing the signing key failed", e));
116
59
    }
117

            
118
59
    let account = create_user(
119
59
        &body,
120
59
        user_id,
121
59
        &provisioned,
122
59
        &keypair.public_pem_b64,
123
59
        &password_hash,
124
59
    )
125
59
    .await?;
126
59
    created(&account.email)
127
61
}
128

            
129
63
fn created(email: &str) -> Result<Html<String>, WebError> {
130
63
    Created { email }
131
63
        .render()
132
63
        .map(Html)
133
        .map_err(|e| WebError::internal("Rendering the registration result failed", e))
134
63
}
135

            
136
#[cfg(test)]
137
#[path = "register_tests.rs"]
138
mod tests;