aboutsummaryrefslogtreecommitdiffstats
path: root/app/models/change_email_validator.rb
diff options
context:
space:
mode:
Diffstat (limited to 'app/models/change_email_validator.rb')
-rw-r--r--app/models/change_email_validator.rb45
1 files changed, 33 insertions, 12 deletions
diff --git a/app/models/change_email_validator.rb b/app/models/change_email_validator.rb
index 5cc13d4c2..7ee6654bb 100644
--- a/app/models/change_email_validator.rb
+++ b/app/models/change_email_validator.rb
@@ -7,11 +7,22 @@
class ChangeEmailValidator
include ActiveModel::Validations
- attr_accessor :old_email, :new_email, :password, :user_circumstance, :logged_in_user
+ attr_accessor :old_email,
+ :new_email,
+ :password,
+ :user_circumstance,
+ :logged_in_user
+
+ validates_presence_of :old_email,
+ :message => N_("Please enter your old email address")
+
+ validates_presence_of :new_email,
+ :message => N_("Please enter your new email address")
+
+ validates_presence_of :password,
+ :message => N_("Please enter your password"),
+ :unless => :changing_email
- validates_presence_of :old_email, :message => N_("Please enter your old email address")
- validates_presence_of :new_email, :message => N_("Please enter your new email address")
- validates_presence_of :password, :message => N_("Please enter your password"), :unless => :changing_email
validate :password_and_format_of_email
def initialize(attributes = {})
@@ -20,7 +31,6 @@ class ChangeEmailValidator
end
end
-
def changing_email
self.user_circumstance == 'change_email'
end
@@ -28,22 +38,33 @@ class ChangeEmailValidator
private
def password_and_format_of_email
- if !self.old_email.blank? && !MySociety::Validate.is_valid_email(self.old_email)
- errors.add(:old_email, _("Old email doesn't look like a valid address"))
- end
+ check_email_is_present_and_valid(:old_email)
if errors[:old_email].blank?
- if self.old_email.downcase != self.logged_in_user.email.downcase
+ if !email_belongs_to_user?(old_email)
errors.add(:old_email, _("Old email address isn't the same as the address of the account you are logged in with"))
- elsif (!self.changing_email) && (!self.logged_in_user.has_this_password?(self.password))
+ elsif !changing_email && !correct_password?
if errors[:password].blank?
errors.add(:password, _("Password is not correct"))
end
end
end
- if !self.new_email.blank? && !MySociety::Validate.is_valid_email(self.new_email)
- errors.add(:new_email, _("New email doesn't look like a valid address"))
+ check_email_is_present_and_valid(:new_email)
+ end
+
+ def check_email_is_present_and_valid(email)
+ if !send(email).blank? && !MySociety::Validate.is_valid_email(send(email))
+ errors.add(email, _("#{ email.to_s.humanize } doesn't look like a valid address"))
end
end
+
+ def email_belongs_to_user?(email)
+ email.downcase == logged_in_user.email.downcase
+ end
+
+ def correct_password?
+ logged_in_user.has_this_password?(password)
+ end
+
end