add check for uniqueness violation in account creation

This commit is contained in:
Joe Ardent 2023-05-16 11:55:32 -07:00
parent 95762f341b
commit da5eefa73a
1 changed files with 7 additions and 7 deletions

View File

@ -17,7 +17,7 @@ pub struct User {
}
#[derive(Debug, Clone, sqlx::FromRow, sqlx::Encode)]
struct DbUser {
pub(crate) struct DbUser {
id: Uuid,
username: String,
displayname: Option<String>,
@ -54,7 +54,7 @@ pub async fn create_user(
.to_string();
let id = Uuid::new_v4();
let id_bytes = sqlx::types::Uuid::from_u128(id.as_u128());
let id_bytes = id.as_bytes().as_slice();
let res = sqlx::query(CREATE_QUERY)
.bind(id_bytes)
.bind(username)
@ -76,7 +76,9 @@ pub async fn create_user(
}
Err(sqlx::Error::Database(db)) => {
if let Some(exit) = db.code() {
if exit.parse().unwrap_or(0) == 2067u32 {
let exit = exit.parse().unwrap_or(0u32);
// https://www.sqlite.org/rescode.html codes for unique constraint violations:
if exit == 2067u32 || exit == 1555 {
Err(CreateUserErrorKind::AlreadyExists.into())
} else {
Err(CreateUserErrorKind::Unknown.into())
@ -85,7 +87,7 @@ pub async fn create_user(
Err(CreateUserErrorKind::Unknown.into())
}
}
_ => unreachable!(),
_ => Err(CreateUserErrorKind::Unknown.into()),
}
}
@ -97,9 +99,7 @@ pub struct CreateUserError(#[from] CreateUserErrorKind);
#[non_exhaustive]
pub enum CreateUserErrorKind {
AlreadyExists,
#[error(
desc = "Usernames must be less than 20 characters and contain only ascii letters, numbers, and dashes."
)]
#[error(desc = "Usernames must be less than 20 characters long")]
BadUsername,
PasswordMismatch,
MissingFields,