41 lines
No EOL
1.2 KiB
Python
41 lines
No EOL
1.2 KiB
Python
from django.db import models
|
|
from django.utils import timezone
|
|
|
|
from datetime import timedelta
|
|
|
|
from localauth.models import TwoFactor
|
|
from localauth.helpers import generate_token
|
|
|
|
from dbsettings.functions import getValue
|
|
|
|
from .functions import sendMessage
|
|
|
|
class SMSTwoFactor(TwoFactor):
|
|
@classmethod
|
|
def initiate(cls, user):
|
|
if user.phone:
|
|
cls.objects.get_or_create(user=user)
|
|
|
|
def send_token(self, description="%s"):
|
|
token = SMSTwoFactorToken.objects.create(user=self)
|
|
sendMessageToUsers([user], description % token)
|
|
|
|
def validate_token(self, token):
|
|
tokens = SMSTwoFactorToken.objects.filter(
|
|
user=self,
|
|
token=token,
|
|
used=False,
|
|
created__gte=timezone.now() - timedelta(seconds=getValue("sms.token.maxage", 300))
|
|
).all()
|
|
|
|
if tokens:
|
|
tokens.update(used=True)
|
|
return True
|
|
|
|
return False
|
|
|
|
class SMSTwoFactorToken(models.Model):
|
|
user = models.ForeignKey(SMSTwoFactor, models.CASCADE)
|
|
token = models.CharField(max_length=256, default=generate_token)
|
|
created = models.DateTimeField(auto_now_add=True)
|
|
used = models.BooleanField(default=False) |