2023-05-20 00:17:24 +00:00
|
|
|
use std::{array, fmt::Display, ops::Deref};
|
2023-05-18 22:49:33 +00:00
|
|
|
|
2023-05-12 21:24:57 +00:00
|
|
|
use argon2::{
|
|
|
|
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
|
|
|
|
Argon2,
|
|
|
|
};
|
2023-05-18 22:49:33 +00:00
|
|
|
use askama::Template;
|
2023-05-18 17:05:29 +00:00
|
|
|
use axum::{
|
2023-05-18 19:15:37 +00:00
|
|
|
extract::{Form, State},
|
2023-05-18 17:05:29 +00:00
|
|
|
http::StatusCode,
|
2023-05-19 22:13:49 +00:00
|
|
|
response::{IntoResponse, Response},
|
2023-05-18 17:05:29 +00:00
|
|
|
};
|
2023-05-20 00:17:24 +00:00
|
|
|
use sqlx::{sqlite::SqliteRow, Row, 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-18 17:05:29 +00:00
|
|
|
use crate::templates::CreateUser;
|
|
|
|
|
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-12 22:36:19 +00:00
|
|
|
|
2023-05-20 00:17:24 +00:00
|
|
|
const ID_QUERY: &str = "select * from witches where id = $1";
|
|
|
|
|
|
|
|
const WITCH_SUCCESS_HEADER: &str = "X-Witch-Success";
|
|
|
|
|
|
|
|
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
2023-05-12 22:36:19 +00:00
|
|
|
pub struct User {
|
|
|
|
id: Uuid,
|
|
|
|
username: String,
|
|
|
|
displayname: Option<String>,
|
|
|
|
email: Option<String>,
|
2023-05-20 00:17:24 +00:00
|
|
|
last_seen: Option<i64>,
|
2023-05-12 22:36:19 +00:00
|
|
|
}
|
|
|
|
|
2023-05-18 22:49:33 +00:00
|
|
|
impl Display for User {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
let uname = &self.username;
|
|
|
|
let dname = if let Some(ref n) = self.displayname {
|
|
|
|
n
|
|
|
|
} else {
|
|
|
|
""
|
|
|
|
};
|
|
|
|
let email = if let Some(ref e) = self.email { e } else { "" };
|
|
|
|
write!(f, "Username: {uname}\nDisplayname: {dname}\nEmail: {email}")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-20 00:17:24 +00:00
|
|
|
#[derive(Debug, Default, Clone, sqlx::Encode)]
|
2023-05-16 18:55:32 +00:00
|
|
|
pub(crate) struct DbUser {
|
2023-05-12 22:36:19 +00:00
|
|
|
id: Uuid,
|
|
|
|
username: String,
|
|
|
|
displayname: Option<String>,
|
|
|
|
email: Option<String>,
|
2023-05-20 00:17:24 +00:00
|
|
|
last_seen: Option<i64>,
|
2023-05-12 22:36:19 +00:00
|
|
|
pwhash: String,
|
|
|
|
}
|
|
|
|
|
2023-05-18 22:49:33 +00:00
|
|
|
#[derive(Debug, Clone, Template)]
|
|
|
|
#[template(path = "signup_success.html")]
|
|
|
|
pub struct CreateUserSuccess(User);
|
|
|
|
|
2023-05-20 00:17:24 +00:00
|
|
|
impl sqlx::FromRow<'_, SqliteRow> for User {
|
|
|
|
fn from_row(row: &SqliteRow) -> Result<Self, sqlx::Error> {
|
|
|
|
let bytes: Vec<u8> = row.get("id");
|
|
|
|
let bytes = bytes.as_slice();
|
|
|
|
let bytes: [u8; 16] = bytes.try_into().unwrap();
|
|
|
|
let id = Uuid::from_bytes_le(bytes);
|
|
|
|
let username: String = row.get("username");
|
|
|
|
let displayname: Option<String> = row.get("displayname");
|
|
|
|
let last_seen: Option<i64> = row.get("last_seen");
|
|
|
|
let email: Option<String> = row.get("email");
|
|
|
|
|
|
|
|
Ok(Self {
|
|
|
|
id,
|
|
|
|
username,
|
|
|
|
displayname,
|
|
|
|
email,
|
|
|
|
last_seen,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-12 22:36:19 +00:00
|
|
|
impl From<DbUser> for User {
|
|
|
|
fn from(dbu: DbUser) -> Self {
|
|
|
|
User {
|
|
|
|
id: dbu.id,
|
|
|
|
username: dbu.username,
|
|
|
|
displayname: dbu.displayname,
|
|
|
|
email: dbu.email,
|
2023-05-20 00:17:24 +00:00
|
|
|
last_seen: dbu.last_seen,
|
2023-05-12 22:36:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-18 19:24:43 +00:00
|
|
|
/// Get Handler: displays the form to create a user
|
2023-05-18 17:05:29 +00:00
|
|
|
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
|
2023-05-18 17:05:29 +00:00
|
|
|
#[axum::debug_handler]
|
|
|
|
pub async fn post_create_user(
|
2023-05-18 19:24:43 +00:00
|
|
|
State(pool): State<SqlitePool>,
|
2023-05-18 17:05:29 +00:00
|
|
|
Form(signup): Form<CreateUser>,
|
2023-05-19 22:13:49 +00:00
|
|
|
) -> Result<Response, CreateUserError> {
|
2023-05-18 17:05:29 +00:00
|
|
|
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-18 17:05:29 +00:00
|
|
|
|
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());
|
|
|
|
}
|
|
|
|
|
2023-05-18 17:05:29 +00:00
|
|
|
if password != verify {
|
|
|
|
return Err(CreateUserErrorKind::PasswordMismatch.into());
|
|
|
|
}
|
|
|
|
|
|
|
|
let password = urlencoding::decode(password)
|
|
|
|
.map_err(|_| CreateUserErrorKind::BadPassword)?
|
|
|
|
.to_string();
|
|
|
|
let password = password.as_bytes();
|
|
|
|
|
|
|
|
let displayname = if let Some(dn) = displayname {
|
|
|
|
let dn = urlencoding::decode(dn)
|
|
|
|
.map_err(|_| CreateUserErrorKind::BadDisplayname)?
|
|
|
|
.to_string();
|
|
|
|
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-19 22:13:49 +00:00
|
|
|
let mut resp = axum::response::Redirect::temporary("/signup_success").into_response();
|
|
|
|
resp.headers_mut().append(
|
2023-05-20 00:17:24 +00:00
|
|
|
WITCH_SUCCESS_HEADER,
|
2023-05-19 22:13:49 +00:00
|
|
|
user.id.simple().to_string().parse().unwrap(),
|
|
|
|
);
|
2023-05-20 00:17:24 +00:00
|
|
|
|
2023-05-19 22:13:49 +00:00
|
|
|
Ok(resp)
|
|
|
|
}
|
|
|
|
|
2023-05-20 00:17:24 +00:00
|
|
|
/// Get handler for successful signup; only meaningful
|
2023-05-19 22:13:49 +00:00
|
|
|
pub async fn get_signup_success(
|
|
|
|
headers: axum::http::HeaderMap,
|
|
|
|
State(pool): State<SqlitePool>,
|
2023-05-20 00:17:24 +00:00
|
|
|
) -> Response {
|
|
|
|
let user = if let Some(id) = headers.get(WITCH_SUCCESS_HEADER) {
|
|
|
|
let id = id.to_str().unwrap();
|
|
|
|
let id = Uuid::try_parse(id).unwrap_or_default();
|
|
|
|
let id_bytes = id.as_bytes();
|
|
|
|
sqlx::query_as(ID_QUERY)
|
|
|
|
.bind(id_bytes.as_slice())
|
|
|
|
.fetch_one(&pool)
|
|
|
|
.await
|
|
|
|
.unwrap_or_default()
|
|
|
|
} else {
|
|
|
|
User::default()
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut resp = CreateUserSuccess(user.clone()).into_response();
|
|
|
|
|
|
|
|
if user.username.is_empty() {
|
|
|
|
// redirect to front page if we got here without a valid witch header
|
|
|
|
*resp.status_mut() = StatusCode::TEMPORARY_REDIRECT;
|
|
|
|
resp.headers_mut().insert("Location", "/".parse().unwrap());
|
2023-05-19 22:13:49 +00:00
|
|
|
}
|
2023-05-20 00:17:24 +00:00
|
|
|
resp
|
2023-05-18 17:05:29 +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-15 03:33:36 +00:00
|
|
|
let id = Uuid::new_v4();
|
2023-05-16 19:24:53 +00:00
|
|
|
let id_bytes = id.to_bytes_le();
|
|
|
|
let id_bytes = id_bytes.as_slice();
|
2023-05-15 03:33:36 +00:00
|
|
|
let res = sqlx::query(CREATE_QUERY)
|
|
|
|
.bind(id_bytes)
|
|
|
|
.bind(username)
|
|
|
|
.bind(displayname)
|
|
|
|
.bind(email)
|
|
|
|
.bind(pwhash)
|
|
|
|
.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-15 03:33:36 +00:00
|
|
|
};
|
|
|
|
Ok(user)
|
|
|
|
}
|
|
|
|
Err(sqlx::Error::Database(db)) => {
|
|
|
|
if let Some(exit) = db.code() {
|
2023-05-16 18:55:32 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
#[Error(desc = "Could not create user.")]
|
|
|
|
#[non_exhaustive]
|
|
|
|
pub struct CreateUserError(#[from] CreateUserErrorKind);
|
|
|
|
|
2023-05-18 17:05:29 +00:00
|
|
|
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-12 21:24:57 +00:00
|
|
|
#[Error]
|
|
|
|
#[non_exhaustive]
|
|
|
|
pub enum CreateUserErrorKind {
|
|
|
|
AlreadyExists,
|
2023-05-16 19:24:53 +00:00
|
|
|
#[error(desc = "Usernames must be between 1 and 20 non-whitespace characters long")]
|
2023-05-15 03:33:36 +00:00
|
|
|
BadUsername,
|
2023-05-12 21:24:57 +00:00
|
|
|
PasswordMismatch,
|
2023-05-18 17:05:29 +00:00
|
|
|
BadPassword,
|
|
|
|
BadDisplayname,
|
|
|
|
BadEmail,
|
2023-05-12 21:24:57 +00:00
|
|
|
MissingFields,
|
2023-05-16 23:24:24 +00:00
|
|
|
UnknownDBError,
|
2023-05-12 21:24:57 +00:00
|
|
|
}
|