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:
parent
c94890b9f0
commit
8b1eef17f7
7 changed files with 51 additions and 53 deletions
7
Cargo.lock
generated
7
Cargo.lock
generated
|
@ -2070,12 +2070,6 @@ dependencies = [
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "urlencoding"
|
|
||||||
version = "2.1.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uuid"
|
name = "uuid"
|
||||||
version = "1.3.3"
|
version = "1.3.3"
|
||||||
|
@ -2390,7 +2384,6 @@ dependencies = [
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"unicode-segmentation",
|
"unicode-segmentation",
|
||||||
"urlencoding",
|
|
||||||
"uuid",
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
|
@ -23,7 +23,6 @@ justerror = "1"
|
||||||
password-hash = { version = "0.5", features = ["std", "getrandom"] }
|
password-hash = { version = "0.5", features = ["std", "getrandom"] }
|
||||||
axum-login = { version = "0.5", features = ["sqlite", "sqlx"] }
|
axum-login = { version = "0.5", features = ["sqlite", "sqlx"] }
|
||||||
unicode-segmentation = "1"
|
unicode-segmentation = "1"
|
||||||
urlencoding = "2"
|
|
||||||
async-session = "3"
|
async-session = "3"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
|
|
@ -60,6 +60,10 @@ pub async fn get_db_pool() -> SqlitePool {
|
||||||
.await
|
.await
|
||||||
.expect("can't connect to database");
|
.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"))
|
let mut m = Migrator::new(std::path::Path::new("./migrations"))
|
||||||
.await
|
.await
|
||||||
|
|
|
@ -10,7 +10,7 @@ use axum::{
|
||||||
};
|
};
|
||||||
use sqlx::SqlitePool;
|
use sqlx::SqlitePool;
|
||||||
|
|
||||||
use crate::{util::form_decode, AuthContext, LoginGet, LoginPost, LogoutGet, LogoutPost, User};
|
use crate::{AuthContext, LoginGet, LoginPost, LogoutGet, LogoutPost, User};
|
||||||
|
|
||||||
//-************************************************************************
|
//-************************************************************************
|
||||||
// Constants
|
// Constants
|
||||||
|
@ -28,7 +28,6 @@ pub struct LoginError(#[from] LoginErrorKind);
|
||||||
pub enum LoginErrorKind {
|
pub enum LoginErrorKind {
|
||||||
Internal,
|
Internal,
|
||||||
BadPassword,
|
BadPassword,
|
||||||
BadUsername,
|
|
||||||
Unknown,
|
Unknown,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -57,10 +56,10 @@ pub async fn post_login(
|
||||||
State(pool): State<SqlitePool>,
|
State(pool): State<SqlitePool>,
|
||||||
Form(login): Form<LoginPost>,
|
Form(login): Form<LoginPost>,
|
||||||
) -> Result<impl IntoResponse, LoginError> {
|
) -> Result<impl IntoResponse, LoginError> {
|
||||||
let username = form_decode(&login.username, LoginErrorKind::BadUsername)?;
|
let username = &login.username;
|
||||||
let username = username.trim();
|
let username = username.trim();
|
||||||
|
|
||||||
let pw = form_decode(&login.password, LoginErrorKind::BadPassword)?;
|
let pw = &login.password;
|
||||||
let pw = pw.trim();
|
let pw = pw.trim();
|
||||||
|
|
||||||
let user = User::try_get(username, &pool)
|
let user = User::try_get(username, &pool)
|
||||||
|
|
|
@ -67,16 +67,11 @@ pub async fn post_create_user(
|
||||||
State(pool): State<SqlitePool>,
|
State(pool): State<SqlitePool>,
|
||||||
Form(signup): Form<CreateUser>,
|
Form(signup): Form<CreateUser>,
|
||||||
) -> Result<impl IntoResponse, CreateUserError> {
|
) -> Result<impl IntoResponse, CreateUserError> {
|
||||||
let username = &signup.username;
|
use crate::util::validate_optional_length;
|
||||||
let displayname = &signup.displayname;
|
let username = signup.username.trim();
|
||||||
let email = &signup.email;
|
let password = signup.password.trim();
|
||||||
let password = &signup.password;
|
let verify = signup.pw_verify.trim();
|
||||||
let verify = &signup.pw_verify;
|
|
||||||
|
|
||||||
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();
|
let name_len = username.graphemes(true).size_hint().1.unwrap();
|
||||||
// we are not ascii exclusivists around here
|
// we are not ascii exclusivists around here
|
||||||
if !(1..=20).contains(&name_len) {
|
if !(1..=20).contains(&name_len) {
|
||||||
|
@ -87,42 +82,22 @@ pub async fn post_create_user(
|
||||||
return Err(CreateUserErrorKind::PasswordMismatch.into());
|
return Err(CreateUserErrorKind::PasswordMismatch.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
let password = urlencoding::decode(password)
|
|
||||||
.map_err(|_| CreateUserErrorKind::BadPassword)?
|
|
||||||
.to_string();
|
|
||||||
let password = password.trim();
|
let password = password.trim();
|
||||||
let password = password.as_bytes();
|
let password = password.as_bytes();
|
||||||
if !(4..=50).contains(&password.len()) {
|
if !(4..=50).contains(&password.len()) {
|
||||||
return Err(CreateUserErrorKind::BadPassword.into());
|
return Err(CreateUserErrorKind::BadPassword.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
let displayname = if let Some(dn) = displayname {
|
// clean up the optionals
|
||||||
let dn = urlencoding::decode(dn)
|
let displayname = validate_optional_length(
|
||||||
.map_err(|_| CreateUserErrorKind::BadDisplayname)?
|
&signup.displayname,
|
||||||
.to_string()
|
0..100,
|
||||||
.trim()
|
CreateUserErrorKind::BadDisplayname,
|
||||||
.to_string();
|
)?;
|
||||||
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 = validate_optional_length(&signup.email, 5..30, CreateUserErrorKind::BadEmail)?;
|
||||||
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 user = create_user(username, displayname, email, password, &pool).await?;
|
let user = create_user(username, &displayname, &email, password, &pool).await?;
|
||||||
tracing::debug!("created {user:?}");
|
tracing::debug!("created {user:?}");
|
||||||
let id = user.id.as_simple().to_string();
|
let id = user.id.as_simple().to_string();
|
||||||
let location = format!("/signup_success/{id}");
|
let location = format!("/signup_success/{id}");
|
||||||
|
|
17
src/users.rs
17
src/users.rs
|
@ -1,5 +1,5 @@
|
||||||
use std::{
|
use std::{
|
||||||
fmt::Display,
|
fmt::{Debug, Display},
|
||||||
time::{SystemTime, UNIX_EPOCH},
|
time::{SystemTime, UNIX_EPOCH},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -14,7 +14,7 @@ use crate::AuthContext;
|
||||||
const USERNAME_QUERY: &str = "select * from witches where username = $1";
|
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";
|
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 struct User {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
pub username: String,
|
pub username: String,
|
||||||
|
@ -24,6 +24,19 @@ pub struct User {
|
||||||
pub(crate) pwhash: String,
|
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 {
|
impl Display for User {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
let uname = &self.username;
|
let uname = &self.username;
|
||||||
|
|
19
src/util.rs
19
src/util.rs
|
@ -1,3 +1,18 @@
|
||||||
pub fn form_decode<E: std::error::Error>(input: &str, err: E) -> Result<String, E> {
|
use std::{error::Error, ops::Range};
|
||||||
Ok(urlencoding::decode(input).map_err(|_| err)?.into_owned())
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue