diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/controllers/users_controller.rs | 46 |
1 files changed, 38 insertions, 8 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) } } |