From 3b7bc3f2bb7fcd3a295127f6fc3dd59116f88d6b Mon Sep 17 00:00:00 2001 From: baarkerlounger <5101747+baarkerlounger@users.noreply.github.com> Date: Thu, 9 Dec 2021 15:32:07 +0000 Subject: [PATCH] Validate that password match when updating and show errors if they don't (#158) * Validate that password match and show error if not * User spec * Test user update failure * Format error messages for Form builder gem * Test error message --- app/controllers/users_controller.rb | 20 +++++++++- app/views/users/edit.html.erb | 2 + app/views/users/edit_password.html.erb | 14 ++++--- app/views/users/reset_password.html.erb | 2 + spec/features/user_spec.rb | 2 +- spec/requests/user_controller_spec.rb | 49 +++++++++++++++++++++++++ 6 files changed, 81 insertions(+), 8 deletions(-) diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index a65b1f137..33f23e41a 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -10,6 +10,12 @@ class UsersController < ApplicationController bypass_sign_in @user flash[:notice] = I18n.t("devise.passwords.updated") if user_params.key?("password") redirect_to user_path(@user) + elsif user_params.key?("password") + format_error_messages + render :edit_password, status: :unprocessable_entity + else + format_error_messages + render :edit, status: :unprocessable_entity end end @@ -39,6 +45,18 @@ class UsersController < ApplicationController private + def format_error_messages + errors = @user.errors.to_hash + @user.errors.clear + errors.each do |attribute, message| + @user.errors.add attribute.to_sym, format_error_message(attribute, message) + end + end + + def format_error_message(attribute, message) + [attribute.to_s.humanize.capitalize, message].join(" ") + end + def password_params { password: SecureRandom.hex(8) } end @@ -48,7 +66,7 @@ private end def user_params - params.require(:user).permit(:email, :name, :password, :role) + params.require(:user).permit(:email, :name, :password, :password_confirmation, :role) end def find_resource diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb index 3d4d5e7b8..f355ba993 100644 --- a/app/views/users/edit.html.erb +++ b/app/views/users/edit.html.erb @@ -10,6 +10,8 @@ <%= form_for(current_user, as: :user, html: { method: :patch }) do |f| %>