Skip to content

Commit

Permalink
fix: input validation on registration
Browse files Browse the repository at this point in the history
  • Loading branch information
ChecksumDev committed Oct 31, 2023
1 parent f75947a commit 18cb7d6
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/routes/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,24 +61,28 @@ struct RegisterRequest {

#[post("/register")]
async fn register(info: web::Json<RegisterRequest>, data: Data<AppData>) -> impl Responder {
if info.username.len() < 3 || info.password.len() < 8 {
return HttpResponse::BadRequest().body("Invalid username or password");
}

let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
let password_hash = argon2
.hash_password(info.password.as_bytes(), &salt)
.unwrap()
.to_string();

let user = sqlx::query_as::<_, User>("SELECT * FROM users WHERE username = $1")
let user = sqlx::query_as::<_, User>("SELECT id FROM users WHERE username = $1")
.bind(&info.username)
.fetch_one(&data.pool)
.fetch_optional(&data.pool)
.await;

if user.is_ok() {
return HttpResponse::BadRequest().body("Username already exists");
if let Ok(Some(_)) = user {
return HttpResponse::Conflict().body("Username already exists");
}

let user = sqlx::query_as::<_, User>(
"INSERT INTO users (uuid, username, password, key, quota, used, permissions) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *",
"INSERT INTO users (uuid, username, password, key, quota, used, permissions) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id, uuid, username, quota, used, permissions",
)
.bind(Uuid::new_v4().to_string())
.bind(&info.username)
Expand All @@ -88,8 +92,10 @@ async fn register(info: web::Json<RegisterRequest>, data: Data<AppData>) -> impl
.bind(0)
.bind(0)
.fetch_one(&data.pool)
.await
.unwrap();
.await;

HttpResponse::Ok().json(user)
}
match user {
Ok(user) => HttpResponse::Ok().json(user),
Err(_) => HttpResponse::InternalServerError().body("Failed to create user"),
}
}

0 comments on commit 18cb7d6

Please sign in to comment.