Skip to content

Commit

Permalink
Validate OTP code generation timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
your committed May 13, 2024
1 parent 238917e commit 0b75fd8
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
17 changes: 15 additions & 2 deletions app/forms/email_verification_form.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ class EmailVerificationForm < Form
# Required for shared partial in the view
delegate :email_address, to: :claim

validate :otp_validate
validate :sent_one_time_password_must_be_valid
validate :otp_must_be_valid, if: :sent_one_time_password_at?

before_validation do
self.one_time_password = one_time_password.gsub(/\D/, "")
Expand All @@ -22,12 +23,24 @@ def sent_one_time_password_at
claim.sent_one_time_password_at
end

def otp_validate
def sent_one_time_password_must_be_valid
return if sent_one_time_password_at?

errors.add(:one_time_password, i18n_errors_path(:"one_time_password.invalid"))
end

def otp_must_be_valid
otp = OneTimePassword::Validator.new(
one_time_password,
sent_one_time_password_at
)

errors.add(:one_time_password, otp.warning) unless otp.valid?
end

def sent_one_time_password_at?
sent_one_time_password_at&.to_datetime || false
rescue Date::Error
false
end
end
4 changes: 4 additions & 0 deletions config/locales/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,10 @@ en:
presence: "Enter an email address"
format: "Enter an email address in the correct format, like name@example.com"
length: "Email address must be 256 characters or less"
email_verification:
errors:
one_time_password:
invalid: An error occured while validating the passcode, please try generating a new one
mobile_number:
errors:
invalid: "Enter a mobile number, like 07700 900 982 or +44 7700 900 982"
Expand Down
6 changes: 6 additions & 0 deletions spec/forms/email_verification_form_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@
it { is_expected.not_to be_valid }
end

context "when the code generation timestamp is missing" do
let(:one_time_password) { OneTimePassword::Generator.new.code }
let(:sent_one_time_password_at) { nil }
it { is_expected.not_to be_valid }
end

context "when correct code" do
let(:one_time_password) { OneTimePassword::Generator.new.code }
let(:sent_one_time_password_at) { Time.now }
Expand Down

0 comments on commit 0b75fd8

Please sign in to comment.