kumidc/authentication/forms/otp.py

35 lines
1.1 KiB
Python
Raw Normal View History

2022-08-04 11:15:10 +00:00
from django import forms
from django.core.exceptions import ValidationError
from django.contrib import messages
from ..models.session import AuthSession
class TOTPLoginForm(forms.Form):
token = forms.IntegerField(max_value=10**9-1, min_value=0)
def __init__(self, request=None, *args, **kwargs):
self.request = request
self.user_cache = None
super().__init__(*args, **kwargs)
2022-08-04 12:11:55 +00:00
def get_user(self):
return self.user_cache
2022-08-04 11:15:10 +00:00
def clean_token(self):
token = str(self.cleaned_data.get('token')).zfill(6)
if self.request.user.is_authenticated:
user = self.request.user
else:
sessionid = self.request.session["AuthSession"]
2022-08-04 12:11:55 +00:00
session = AuthSession.objects.get(id=sessionid)
2022-08-04 11:15:10 +00:00
user = session.user
if user.totpsecret.verify(token):
self.user_cache = user
else:
messages.error(self.request, "The token you entered is incorrect. Please try again.")
raise ValidationError("The token you entered is incorrect. Please try again.")
return token