From fcbb6f15983b08f8923de1cd4e9b6df176ca3dab Mon Sep 17 00:00:00 2001 From: Alex Kotov Date: Thu, 15 Oct 2020 04:53:24 +0500 Subject: [PATCH] Add user validation --- src/forms.rs | 11 +++++++++++ src/main.rs | 1 + src/routes.rs | 21 +++++++++++++++++---- 3 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 src/forms.rs diff --git a/src/forms.rs b/src/forms.rs new file mode 100644 index 0000000..cbe218f --- /dev/null +++ b/src/forms.rs @@ -0,0 +1,11 @@ +#[derive(FromForm)] +pub struct UserSignUp { + pub username: String, + pub password: String, +} + +impl UserSignUp { + pub fn is_valid(&self) -> bool { + true + } +} diff --git a/src/main.rs b/src/main.rs index 08c27f9..5d372a8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ mod database; mod routes; mod schema; mod models; +mod forms; #[macro_use] extern crate diesel; #[macro_use] extern crate rocket; diff --git a/src/routes.rs b/src/routes.rs index 208d708..8119981 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -1,9 +1,11 @@ use crate::database; use crate::schema; use crate::models; +use crate::forms; use diesel::prelude::*; use rocket::response::Redirect; +use rocket::request::Form; use rocket_contrib::templates::Template; #[derive(Serialize)] @@ -30,14 +32,25 @@ fn index(db_conn: database::DbConn) -> Template { Template::render("index", &template_context) } -#[post("/users//")] -fn sign_up(db_conn: database::DbConn, username: String, password: String) -> Redirect { +#[post("/users", data = "")] +fn sign_up( + db_conn: database::DbConn, + user_sign_up_form: Form, +) -> Redirect +{ use schema::users; - let encrypted_password = bcrypt::hash(password, bcrypt::DEFAULT_COST).unwrap(); + if !user_sign_up_form.is_valid() { + return Redirect::to(uri!(index)); + } + + let encrypted_password = bcrypt::hash( + user_sign_up_form.password.to_string(), + bcrypt::DEFAULT_COST, + ).unwrap(); let new_user = models::NewUser { - username: username.as_str(), + username: user_sign_up_form.username.as_str(), encrypted_password: encrypted_password.as_str(), };