Skip to content

Commit

Permalink
Merge pull request #72 from dimagi/ce/extend-token
Browse files Browse the repository at this point in the history
extend tokens to 30 minutes and limit resending
  • Loading branch information
calellowitz authored Jan 10, 2025
2 parents aaeb172 + a49aed7 commit ad6eb13
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
17 changes: 17 additions & 0 deletions users/migrations/0013_phonedevice_attempts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.1.7 on 2025-01-09 21:43

from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("users", "0012_phonedevice_otp_last_sent"),
]

operations = [
migrations.AddField(
model_name="phonedevice",
name="attempts",
field=models.IntegerField(default=1),
),
]
10 changes: 7 additions & 3 deletions users/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,22 +96,26 @@ class PhoneDevice(SideChannelDevice):
phone_number = PhoneNumberField()
user = models.ForeignKey(ConnectUser, on_delete=models.CASCADE)
otp_last_sent = models.DateTimeField(null=True, blank=True)
attempts = models.IntegerField(default=1)

def generate_challenge(self):
# generate and send new token if the old token is valid for less than 5 minutes
# set he otp_last_sent to None to send the new OTP immediately
if self.valid_until - now() <= timedelta(minutes=5):
self.otp_last_sent = None
self.generate_token(valid_secs=600)
self.generate_token(valid_secs=1800)
self.attempts = 0
message = f"Your verification token from commcare connect is {self.token} \n\n {settings.APP_HASH}"
# send the OTP if last sent message is not within the last 2 minutes
# backoff attempts exponentially
wait_time = 2 ** self.attempts
if self.otp_last_sent is None or (
self.otp_last_sent and now() - self.otp_last_sent >= timedelta(minutes=2)
self.otp_last_sent and now() - self.otp_last_sent >= timedelta(minutes=wait_time)
):
if not self.phone_number.raw_input.startswith(TEST_NUMBER_PREFIX):
sender = get_sms_sender(self.phone_number.country_code)
send_sms(self.phone_number.as_e164, message, sender)
self.otp_last_sent = now()
self.attempts += 1
self.save()

return message
Expand Down

0 comments on commit ad6eb13

Please sign in to comment.