Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions app/models/otp_requests_tracker.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
class OtpRequestsTracker < ApplicationRecord
def self.find_or_create_with_phone_and_confirmed(phone, phone_confirmed)
tries = 1
phone_fingerprint = Pii::Fingerprinter.fingerprint(phone.strip)

where(phone_fingerprint: phone_fingerprint, phone_confirmed: phone_confirmed).
first_or_create(otp_send_count: 0, otp_last_sent_at: Time.zone.now)
rescue ActiveRecord::RecordNotUnique
retry unless (tries -= 1).zero?
raise
create_or_find_by(
phone_fingerprint: Pii::Fingerprinter.fingerprint(phone.strip),
phone_confirmed: phone_confirmed,
)
end

def self.atomic_increment(id)
Expand Down
15 changes: 1 addition & 14 deletions spec/models/otp_requests_tracker_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,13 @@
end

context 'match not found' do
it 'creates new record with otp_send_count = 0 and otp_last_sent_at = current time' do
it 'creates new record with otp_send_count = 0' do
expect { OtpRequestsTracker.find_or_create_with_phone_and_confirmed(phone, true) }.
to change(OtpRequestsTracker, :count).by(1)

existing = OtpRequestsTracker.where(phone_fingerprint: phone_fingerprint).first

expect(existing.otp_send_count).to eq 0
expect(existing.otp_last_sent_at).to be_within(2.seconds).of(Time.zone.now)
end
end

context 'race condition' do
it 'retries once, then raises ActiveRecord::RecordNotUnique' do
tracker = OtpRequestsTracker.new
allow(OtpRequestsTracker).to receive(:where).
and_raise(ActiveRecord::RecordNotUnique.new(tracker))

expect(OtpRequestsTracker).to receive(:where).exactly(:once)
expect { OtpRequestsTracker.find_or_create_with_phone_and_confirmed(phone, true) }.
to raise_error ActiveRecord::RecordNotUnique
end
end
end
Expand Down
1 change: 1 addition & 0 deletions spec/services/otp_rate_limiter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
phone,
false,
)
otp_rate_limiter.increment
old_otp_last_sent_at = tracker.reload.otp_last_sent_at
otp_rate_limiter.increment
new_otp_last_sent_at = tracker.reload.otp_last_sent_at
Expand Down