diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 06f148f84..2f6c452d4 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -63,29 +63,21 @@ class UsersController < ApplicationController end def new + debugger @organisation_id = params["organisation_id"] - @resource = User.new + @user = User.new end def create - @resource = User.new - if user_params["email"].empty? - @resource.errors.add :email, I18n.t("validations.email.blank") - elsif !email_valid?(user_params["email"]) - @resource.errors.add :email, I18n.t("validations.email.invalid") - elsif user_params[:role] && !current_user.assignable_roles.key?(user_params[:role].to_sym) - @resource.errors.add :role, I18n.t("validations.role.invalid") - end - if @resource.errors.present? - render :new, status: :unprocessable_entity + @user = User.new(user_params.merge(org_params).merge(password_params)) + if @user.save + redirect_to created_user_redirect_path else - user = User.create(user_params.merge(org_params).merge(password_params)) - if user.persisted? - redirect_to created_user_redirect_path - else - @resource.errors.add :email, I18n.t("validations.email.taken") - render :new, status: :unprocessable_entity + unless @user.errors[:organisation].empty? + @user.errors.add(:organisation_id, message: @user.errors[:organisation]) + @user.errors.delete(:organisation) end + render :new, status: :unprocessable_entity end end diff --git a/app/models/user.rb b/app/models/user.rb index 8b9d3f52f..ef371461c 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,6 +1,7 @@ class User < ApplicationRecord # Include default devise modules. Others available are: # :omniauthable + include Helpers::Email devise :database_authenticatable, :recoverable, :rememberable, :validatable, :trackable, :lockable, :two_factor_authenticatable, :confirmable, :timeoutable @@ -8,6 +9,9 @@ class User < ApplicationRecord has_many :owned_case_logs, through: :organisation has_many :managed_case_logs, through: :organisation + validate :validate_email + validates :name, :role, :email, presence: true + has_paper_trail ignore: %w[last_sign_in_at current_sign_in_at current_sign_in_ip @@ -149,4 +153,16 @@ class User < ApplicationRecord def valid_for_authentication? super && active? end + +private + + def validate_email + unless email_valid?(email) + if User.exists?(["email LIKE ?", "%#{email}%"]) + errors.add :email, I18n.t("validations.email.taken") + else + errors.add :email, I18n.t("validations.email.invalid") + end + end + end end diff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erb index 2b3db667e..4b875c40d 100644 --- a/app/views/users/new.html.erb +++ b/app/views/users/new.html.erb @@ -4,7 +4,7 @@ <%= govuk_back_link(href: :back) %> <% end %> -<%= form_for(@resource, as: :user, html: { method: :post }) do |f| %> +<%= form_for(@user, as: :user, html: { method: :post }) do |f| %>