From d52ebade909350f7bf81d91ea158371b4ef62d46 Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Tue, 31 Jul 2018 18:22:42 +0200 Subject: Validate password confirmation on create user. --- src/controllers/users_controller.rs | 46 ++++++++++++++++++++++++++++++------- templates/new_user.html | 2 +- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/controllers/users_controller.rs b/src/controllers/users_controller.rs index 9bfb5e1..b2ba308 100644 --- a/src/controllers/users_controller.rs +++ b/src/controllers/users_controller.rs @@ -12,10 +12,10 @@ pub struct UsersTemplate { implement_responder_for!(UsersTemplate); #[get("/", format = "text/html")] -fn index(conn: utils::DbConn) -> utils::Page { +fn index(flash: Option, conn: utils::DbConn) -> utils::Page { utils::Page { title: String::from("Users"), - flash: None, + flash: flash.map_or(None, |f| Some(f.msg().to_string())), content: UsersTemplate { users: ::models::User::all(conn).unwrap() } @@ -31,21 +31,51 @@ pub struct NewUserTemplate { implement_responder_for!(NewUserTemplate); #[get("/new", format = "text/html")] -fn new() -> utils::Page { +fn new(flash: Option) -> utils::Page { utils::Page { title: String::from("New user"), - flash: None, + flash: flash.map_or(None, |f| Some(f.msg().to_string())), content: NewUserTemplate { user: Default::default() } } } +#[derive(FromForm)] +struct RegisterUserForm { + username: String, + realname: Option, + email: Option, + password: String, + password_confirm: String +} + +impl RegisterUserForm { + fn new_user(&self) -> Result<::models::NewUser, &'static str> { + if self.password != self.password_confirm { + Err("Passwords don't match") + } + else { + Ok(::models::NewUser { + username: self.username.clone(), + realname: self.realname.clone(), + email: self.email.clone(), + password: self.password.clone() + }) + } + } +} + #[post("/create", data="")] -fn create(user: Form<::models::NewUser>, conn: utils::DbConn) -> Flash { - match ::models::User::create(user.get(), conn) { - Ok(_) => Flash::success(Redirect::to("/"), "User successfully created!"), - Err(_) => Flash::error(Redirect::to("/"), "Could not create user!") +fn create(user: Form, route: &rocket::Route, conn: utils::DbConn) -> Flash { + match user.get().new_user() { + Ok(new_user) => { + match ::models::User::create(&new_user, conn) { + Ok(_) => Flash::success(Redirect::to(route.base.path()), "User successfully created!"), + Err(_) => Flash::error(Redirect::to("/"), "Could not create user!") + } + }, + Err(msg) => Flash::error(Redirect::to(&format!("{}/new", route.base.path())), &msg) } } diff --git a/templates/new_user.html b/templates/new_user.html index c64d9ad..e1ffbe1 100644 --- a/templates/new_user.html +++ b/templates/new_user.html @@ -22,7 +22,7 @@
- +
-- cgit v1.2.3