diff options
-rw-r--r-- | src/controllers/users_controller.rs | 46 | ||||
-rw-r--r-- | 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<UsersTemplate> { +fn index(flash: Option<rocket::request::FlashMessage>, conn: utils::DbConn) -> utils::Page<UsersTemplate> { 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<NewUserTemplate> { +fn new(flash: Option<rocket::request::FlashMessage>) -> utils::Page<NewUserTemplate> { 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<String>, + email: Option<String>, + 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="<user>")] -fn create(user: Form<::models::NewUser>, conn: utils::DbConn) -> Flash<Redirect> { - 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<RegisterUserForm>, route: &rocket::Route, conn: utils::DbConn) -> Flash<Redirect> { + 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 @@ <div class="field"> <label>Confirm password:</label> - <input type="text" name="email" value=""> + <input type="text" name="password_confirm" value=""> </div> <div class="actions"> |