what2watch/src/users.rs

308 lines
9.0 KiB
Rust
Raw Normal View History

use std::fmt::Display;
2023-05-18 22:49:33 +00:00
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 axum_login::{secrecy::SecretVec, AuthUser, SqliteStore};
use rand_core::CryptoRngCore;
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-28 19:20:55 +00:00
use crate::{
templates::{CreateUser, LoginGet},
ToBlob,
};
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-25 00:08:40 +00:00
// const PW_QUERY: &str = "select pwhash from witches where id = $1";
2023-05-20 00:17:24 +00:00
2023-05-28 19:20:55 +00:00
#[derive(Debug, Default, Clone, PartialEq, Eq, sqlx::FromRow)]
2023-05-12 22:36:19 +00:00
pub struct User {
2023-05-28 19:20:55 +00:00
pub id: i64,
2023-05-25 00:08:40 +00:00
pub username: String,
pub displayname: Option<String>,
pub email: Option<String>,
pub last_seen: Option<i64>,
pwhash: String,
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-28 19:20:55 +00:00
pub type AuthContext = axum_login::extractors::AuthContext<i64, User, SqliteStore<User>>;
impl AuthUser<i64> for User {
fn get_id(&self) -> i64 {
2023-05-25 00:08:40 +00:00
self.id
}
fn get_password_hash(&self) -> SecretVec<u8> {
SecretVec::new(self.pwhash.as_bytes().to_vec())
}
}
2023-05-28 19:20:55 +00:00
//--------------------------------------------------------------------------
// Result types for user creation
//--------------------------------------------------------------------------
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,
}
//--------------------------------------------------------------------------
// User creation route handlers
//--------------------------------------------------------------------------
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>,
) -> Result<Response, 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:20:55 +00:00
let id = user.id;
let location = format!("/signup_success/{id}");
let resp = axum::response::Redirect::temporary(&location).into_response();
2023-05-20 00:17:24 +00:00
Ok(resp)
}
/// Get 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 {
let user: User = {
2023-05-22 23:57:08 +00:00
let id = id.trim();
let id = Uuid::try_parse(id).unwrap_or_default();
2023-05-25 00:08:40 +00:00
query_as(ID_QUERY)
2023-05-23 00:18:13 +00:00
.bind(id.blob())
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-20 00:17:24 +00:00
resp
}
2023-05-28 19:20:55 +00:00
//--------------------------------------------------------------------------
// Login error and success types
//--------------------------------------------------------------------------
#[Error]
pub struct LoginError(#[from] LoginErrorKind);
#[Error]
#[non_exhaustive]
pub enum LoginErrorKind {
BadPassword,
Unknown,
}
impl IntoResponse for LoginError {
fn into_response(self) -> Response {
match self.0 {
LoginErrorKind::Unknown => (
StatusCode::INTERNAL_SERVER_ERROR,
"An unknown error occurred; you cursed, brah?",
)
.into_response(),
_ => (StatusCode::BAD_REQUEST, format!("{self}")).into_response(),
}
}
}
//--------------------------------------------------------------------------
// Login handlers
//--------------------------------------------------------------------------
/// Handle login queries
#[axum::debug_handler]
pub async fn post_login(
mut auth: AuthContext,
State(pool): State<SqlitePool>,
) -> Result<(), LoginError> {
Err(LoginErrorKind::Unknown.into())
}
pub async fn get_login() -> impl IntoResponse {
LoginGet::default()
}
//-------------------------------------------------------------------------
// private fns
//-------------------------------------------------------------------------
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:20:55 +00:00
let mut rng = OsRng;
let id: i64 = rng.as_rngcore().next_u64() as i64;
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
}