what2watch/src/signup.rs

221 lines
6.7 KiB
Rust
Raw Normal View History

2023-05-12 21:24:57 +00:00
use argon2::{
2023-05-25 00:08:40 +00:00
password_hash::{rand_core::OsRng, PasswordHasher, SaltString},
2023-05-12 21:24:57 +00:00
Argon2,
};
2023-05-18 22:49:33 +00:00
use askama::Template;
use axum::{
extract::{Form, Path, State},
http::StatusCode,
response::{IntoResponse, Response},
};
2023-05-28 19:20:55 +00:00
use sqlx::{query_as, SqlitePool};
2023-05-16 19:24:53 +00:00
use unicode_segmentation::UnicodeSegmentation;
2023-05-12 21:24:57 +00:00
use uuid::Uuid;
2023-05-29 00:55:16 +00:00
use crate::{templates::CreateUser, User};
2023-05-15 03:33:36 +00:00
const CREATE_QUERY: &str =
"insert into witches (id, username, displayname, email, pwhash) values ($1, $2, $3, $4, $5)";
2023-05-20 00:17:24 +00:00
const ID_QUERY: &str = "select * from witches where id = $1";
2023-05-28 20:31:45 +00:00
//-************************************************************************
2023-05-28 19:20:55 +00:00
// Result types for user creation
2023-05-28 20:31:45 +00:00
//-************************************************************************
2023-05-28 19:20:55 +00:00
2023-05-18 22:49:33 +00:00
#[derive(Debug, Clone, Template)]
#[template(path = "signup_success.html")]
pub struct CreateUserSuccess(User);
2023-05-28 19:20:55 +00:00
#[Error(desc = "Could not create user.")]
#[non_exhaustive]
pub struct CreateUserError(#[from] CreateUserErrorKind);
impl IntoResponse for CreateUserError {
fn into_response(self) -> askama_axum::Response {
match self.0 {
CreateUserErrorKind::UnknownDBError => {
(StatusCode::INTERNAL_SERVER_ERROR, format!("{self}")).into_response()
}
_ => (StatusCode::BAD_REQUEST, format!("{self}")).into_response(),
}
2023-05-20 00:17:24 +00:00
}
}
2023-05-28 19:20:55 +00:00
#[Error]
#[non_exhaustive]
pub enum CreateUserErrorKind {
AlreadyExists,
#[error(desc = "Usernames must be between 1 and 20 non-whitespace characters long")]
BadUsername,
PasswordMismatch,
#[error(desc = "Password must have at least 4 and at most 50 characters")]
BadPassword,
#[error(desc = "Display name must be less than 100 characters long")]
BadDisplayname,
BadEmail,
MissingFields,
UnknownDBError,
}
2023-05-28 20:31:45 +00:00
//-************************************************************************
2023-05-28 19:20:55 +00:00
// User creation route handlers
2023-05-28 20:31:45 +00:00
//-************************************************************************
2023-05-28 19:20:55 +00:00
2023-05-18 19:24:43 +00:00
/// Get Handler: displays the form to create a user
pub async fn get_create_user() -> CreateUser {
CreateUser::default()
}
2023-05-18 19:24:43 +00:00
/// Post Handler: validates form values and calls the actual, private user
/// creation function
#[axum::debug_handler]
pub async fn post_create_user(
2023-05-18 19:24:43 +00:00
State(pool): State<SqlitePool>,
Form(signup): Form<CreateUser>,
2023-05-29 00:55:16 +00:00
) -> Result<impl IntoResponse, CreateUserError> {
let username = &signup.username;
let displayname = &signup.displayname;
let email = &signup.email;
let password = &signup.password;
let verify = &signup.pw_verify;
2023-05-16 19:24:53 +00:00
let username = username.trim();
2023-05-16 19:24:53 +00:00
let name_len = username.graphemes(true).size_hint().1.unwrap();
// we are not ascii exclusivists around here
if !(1..=20).contains(&name_len) {
return Err(CreateUserErrorKind::BadUsername.into());
}
if password != verify {
return Err(CreateUserErrorKind::PasswordMismatch.into());
}
let password = urlencoding::decode(password)
.map_err(|_| CreateUserErrorKind::BadPassword)?
.to_string();
2023-05-28 19:20:55 +00:00
let password = password.trim();
let password = password.as_bytes();
2023-05-28 19:20:55 +00:00
if !(4..=50).contains(&password.len()) {
return Err(CreateUserErrorKind::BadPassword.into());
}
let displayname = if let Some(dn) = displayname {
let dn = urlencoding::decode(dn)
.map_err(|_| CreateUserErrorKind::BadDisplayname)?
2023-05-28 19:20:55 +00:00
.to_string()
.trim()
.to_string();
2023-05-28 19:20:55 +00:00
if dn.graphemes(true).size_hint().1.unwrap() > 100 {
return Err(CreateUserErrorKind::BadDisplayname.into());
}
Some(dn)
} else {
None
};
let displayname = &displayname;
// TODO(2023-05-17): validate email
let email = if let Some(email) = email {
let email = urlencoding::decode(email)
.map_err(|_| CreateUserErrorKind::BadEmail)?
.to_string();
Some(email)
} else {
None
};
let email = &email;
2023-05-18 19:24:43 +00:00
let user = create_user(username, displayname, email, password, &pool).await?;
tracing::debug!("created {user:?}");
2023-05-28 19:58:26 +00:00
let id = user.id.as_simple().to_string();
let location = format!("/signup_success/{id}");
2023-05-29 00:55:16 +00:00
let resp = axum::response::Redirect::temporary(&location);
2023-05-20 00:17:24 +00:00
Ok(resp)
}
2023-05-28 20:31:45 +00:00
/// Generic handler for successful signup
pub async fn handle_signup_success(
Path(id): Path<String>,
State(pool): State<SqlitePool>,
2023-05-20 00:17:24 +00:00
) -> Response {
2023-05-28 20:31:45 +00:00
let id = id.trim();
let user: User = {
2023-05-22 23:57:08 +00:00
let id = Uuid::try_parse(id).unwrap_or_default();
2023-05-25 00:08:40 +00:00
query_as(ID_QUERY)
2023-05-28 19:58:26 +00:00
.bind(id)
2023-05-20 00:17:24 +00:00
.fetch_one(&pool)
.await
.unwrap_or_default()
};
let mut resp = CreateUserSuccess(user.clone()).into_response();
2023-05-22 23:57:08 +00:00
if user.username.is_empty() || id.is_empty() {
// redirect to front page if we got here without a valid witch ID
2023-05-20 00:17:24 +00:00
*resp.status_mut() = StatusCode::TEMPORARY_REDIRECT;
resp.headers_mut().insert("Location", "/".parse().unwrap());
}
2023-05-28 20:31:45 +00:00
2023-05-20 00:17:24 +00:00
resp
}
2023-05-28 20:31:45 +00:00
//-************************************************************************
2023-05-28 19:20:55 +00:00
// private fns
2023-05-28 20:31:45 +00:00
//-************************************************************************
2023-05-28 19:20:55 +00:00
async fn create_user(
username: &str,
displayname: &Option<String>,
email: &Option<String>,
password: &[u8],
pool: &SqlitePool,
) -> Result<User, CreateUserError> {
2023-05-12 21:24:57 +00:00
// Argon2 with default params (Argon2id v19)
let argon2 = Argon2::default();
let salt = SaltString::generate(&mut OsRng);
2023-05-15 03:33:36 +00:00
let pwhash = argon2
2023-05-12 21:24:57 +00:00
.hash_password(password, &salt)
.unwrap() // safe to unwrap, we know the salt is valid
.to_string();
2023-05-28 19:58:26 +00:00
let id = Uuid::new_v4();
2023-05-15 03:33:36 +00:00
let res = sqlx::query(CREATE_QUERY)
2023-05-28 19:20:55 +00:00
.bind(id)
2023-05-15 03:33:36 +00:00
.bind(username)
.bind(displayname)
.bind(email)
2023-05-25 00:08:40 +00:00
.bind(&pwhash)
2023-05-15 03:33:36 +00:00
.execute(pool)
.await;
match res {
Ok(_) => {
let user = User {
id,
username: username.to_string(),
displayname: displayname.to_owned(),
email: email.to_owned(),
2023-05-20 00:17:24 +00:00
last_seen: None,
2023-05-25 00:08:40 +00:00
pwhash,
2023-05-15 03:33:36 +00:00
};
Ok(user)
}
Err(sqlx::Error::Database(db)) => {
if let Some(exit) = db.code() {
let exit = exit.parse().unwrap_or(0u32);
// https://www.sqlite.org/rescode.html codes for unique constraint violations:
if exit == 2067u32 || exit == 1555 {
2023-05-15 03:33:36 +00:00
Err(CreateUserErrorKind::AlreadyExists.into())
} else {
2023-05-16 23:24:24 +00:00
Err(CreateUserErrorKind::UnknownDBError.into())
2023-05-15 03:33:36 +00:00
}
} else {
2023-05-16 23:24:24 +00:00
Err(CreateUserErrorKind::UnknownDBError.into())
2023-05-15 03:33:36 +00:00
}
}
2023-05-16 23:24:24 +00:00
_ => Err(CreateUserErrorKind::UnknownDBError.into()),
2023-05-15 03:33:36 +00:00
}
2023-05-12 21:24:57 +00:00
}