Simplify form input handling.

The form input values were coming to the handlers already-urldecoded, so no need to re-decode them.
This commit is contained in:
Joe Ardent 2023-06-10 15:30:36 -07:00
parent c94890b9f0
commit 8b1eef17f7
7 changed files with 51 additions and 53 deletions

7
Cargo.lock generated
View file

@ -2070,12 +2070,6 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "urlencoding"
version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9"
[[package]]
name = "uuid"
version = "1.3.3"
@ -2390,7 +2384,6 @@ dependencies = [
"tracing",
"tracing-subscriber",
"unicode-segmentation",
"urlencoding",
"uuid",
]

View file

@ -23,7 +23,6 @@ justerror = "1"
password-hash = { version = "0.5", features = ["std", "getrandom"] }
axum-login = { version = "0.5", features = ["sqlite", "sqlx"] }
unicode-segmentation = "1"
urlencoding = "2"
async-session = "3"
[dev-dependencies]

View file

@ -60,6 +60,10 @@ pub async fn get_db_pool() -> SqlitePool {
.await
.expect("can't connect to database");
// let the filesystem settle before trying anything
// possibly not effective?
tokio::time::sleep(Duration::from_millis(500)).await;
{
let mut m = Migrator::new(std::path::Path::new("./migrations"))
.await

View file

@ -10,7 +10,7 @@ use axum::{
};
use sqlx::SqlitePool;
use crate::{util::form_decode, AuthContext, LoginGet, LoginPost, LogoutGet, LogoutPost, User};
use crate::{AuthContext, LoginGet, LoginPost, LogoutGet, LogoutPost, User};
//-************************************************************************
// Constants
@ -28,7 +28,6 @@ pub struct LoginError(#[from] LoginErrorKind);
pub enum LoginErrorKind {
Internal,
BadPassword,
BadUsername,
Unknown,
}
@ -57,10 +56,10 @@ pub async fn post_login(
State(pool): State<SqlitePool>,
Form(login): Form<LoginPost>,
) -> Result<impl IntoResponse, LoginError> {
let username = form_decode(&login.username, LoginErrorKind::BadUsername)?;
let username = &login.username;
let username = username.trim();
let pw = form_decode(&login.password, LoginErrorKind::BadPassword)?;
let pw = &login.password;
let pw = pw.trim();
let user = User::try_get(username, &pool)

View file

@ -67,16 +67,11 @@ pub async fn post_create_user(
State(pool): State<SqlitePool>,
Form(signup): Form<CreateUser>,
) -> 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;
use crate::util::validate_optional_length;
let username = signup.username.trim();
let password = signup.password.trim();
let verify = signup.pw_verify.trim();
let username = urlencoding::decode(username)
.map_err(|_| CreateUserErrorKind::BadUsername)?
.to_string();
let username = username.trim();
let name_len = username.graphemes(true).size_hint().1.unwrap();
// we are not ascii exclusivists around here
if !(1..=20).contains(&name_len) {
@ -87,42 +82,22 @@ pub async fn post_create_user(
return Err(CreateUserErrorKind::PasswordMismatch.into());
}
let password = urlencoding::decode(password)
.map_err(|_| CreateUserErrorKind::BadPassword)?
.to_string();
let password = password.trim();
let password = password.as_bytes();
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)?
.to_string()
.trim()
.to_string();
if dn.graphemes(true).size_hint().1.unwrap() > 100 {
return Err(CreateUserErrorKind::BadDisplayname.into());
}
Some(dn)
} else {
None
};
let displayname = &displayname;
// clean up the optionals
let displayname = validate_optional_length(
&signup.displayname,
0..100,
CreateUserErrorKind::BadDisplayname,
)?;
// 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;
let email = validate_optional_length(&signup.email, 5..30, CreateUserErrorKind::BadEmail)?;
let user = create_user(username, displayname, email, password, &pool).await?;
let user = create_user(username, &displayname, &email, password, &pool).await?;
tracing::debug!("created {user:?}");
let id = user.id.as_simple().to_string();
let location = format!("/signup_success/{id}");

View file

@ -1,5 +1,5 @@
use std::{
fmt::Display,
fmt::{Debug, Display},
time::{SystemTime, UNIX_EPOCH},
};
@ -14,7 +14,7 @@ use crate::AuthContext;
const USERNAME_QUERY: &str = "select * from witches where username = $1";
const LAST_SEEN_QUERY: &str = "update witches set last_seen = (select unixepoch()) where id = $1";
#[derive(Debug, Default, Clone, PartialEq, Eq, sqlx::FromRow, Serialize, Deserialize)]
#[derive(Default, Clone, PartialEq, Eq, sqlx::FromRow, Serialize, Deserialize)]
pub struct User {
pub id: Uuid,
pub username: String,
@ -24,6 +24,19 @@ pub struct User {
pub(crate) pwhash: String,
}
impl Debug for User {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("User")
.field("id", &self.id)
.field("username", &self.username)
.field("displayname", &self.displayname)
.field("email", &self.email)
.field("last_seen", &self.last_seen)
.field("pwhash", &"<redacted>")
.finish()
}
}
impl Display for User {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let uname = &self.username;

View file

@ -1,3 +1,18 @@
pub fn form_decode<E: std::error::Error>(input: &str, err: E) -> Result<String, E> {
Ok(urlencoding::decode(input).map_err(|_| err)?.into_owned())
use std::{error::Error, ops::Range};
pub fn validate_optional_length<E: Error>(
opt: &Option<String>,
len_range: Range<usize>,
err: E,
) -> Result<Option<String>, E> {
if let Some(opt) = opt {
let opt = opt.trim();
if !len_range.contains(&opt.len()) {
Err(err)
} else {
Ok(Some(opt.to_string()))
}
} else {
Ok(None)
}
}