2018-12-14 09:09:57 +00:00
|
|
|
"""passbook TOTP Forms"""
|
2018-11-16 08:10:35 +00:00
|
|
|
|
|
|
|
from django import forms
|
|
|
|
from django.core.validators import RegexValidator
|
|
|
|
from django.utils.safestring import mark_safe
|
|
|
|
from django.utils.translation import ugettext_lazy as _
|
|
|
|
|
2018-12-14 09:09:57 +00:00
|
|
|
TOTP_CODE_VALIDATOR = RegexValidator(r'^[0-9a-z]{6,8}$',
|
|
|
|
_('Only alpha-numeric characters are allowed.'))
|
2018-11-16 08:10:35 +00:00
|
|
|
|
|
|
|
|
|
|
|
class PictureWidget(forms.widgets.Widget):
|
|
|
|
"""Widget to render value as img-tag"""
|
|
|
|
|
|
|
|
def render(self, name, value, attrs=None, renderer=None):
|
|
|
|
return mark_safe("<img src=\"%s\" />" % value) # nosec
|
|
|
|
|
|
|
|
|
2018-12-14 09:09:57 +00:00
|
|
|
class TOTPVerifyForm(forms.Form):
|
|
|
|
"""Simple Form to verify TOTP Code"""
|
2018-11-16 08:10:35 +00:00
|
|
|
order = ['code']
|
|
|
|
|
2018-12-14 09:09:57 +00:00
|
|
|
code = forms.CharField(label=_('Code'), validators=[TOTP_CODE_VALIDATOR],
|
2018-11-16 08:10:35 +00:00
|
|
|
widget=forms.TextInput(attrs={'autocomplete': 'off'}))
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2018-12-14 09:09:57 +00:00
|
|
|
super().__init__(*args, **kwargs)
|
2018-11-16 08:10:35 +00:00
|
|
|
# This is a little helper so the field is focused by default
|
|
|
|
self.fields['code'].widget.attrs.update({'autofocus': 'autofocus'})
|
|
|
|
|
|
|
|
|
2018-12-14 09:09:57 +00:00
|
|
|
class TOTPSetupInitForm(forms.Form):
|
|
|
|
"""Initial TOTP Setup form"""
|
|
|
|
title = _('Set up TOTP')
|
2018-11-16 08:10:35 +00:00
|
|
|
device = None
|
|
|
|
confirmed = False
|
|
|
|
qr_code = forms.CharField(widget=PictureWidget, disabled=True, required=False,
|
2018-12-14 09:09:57 +00:00
|
|
|
label=_('Scan this Code with your TOTP App.'))
|
|
|
|
code = forms.CharField(label=_('Code'), validators=[TOTP_CODE_VALIDATOR])
|
2018-11-16 08:10:35 +00:00
|
|
|
|
|
|
|
def clean_code(self):
|
|
|
|
"""Check code with new totp device"""
|
|
|
|
if self.device is not None:
|
|
|
|
if not self.device.verify_token(int(self.cleaned_data.get('code'))) \
|
|
|
|
and not self.confirmed:
|
2018-12-14 09:09:57 +00:00
|
|
|
raise forms.ValidationError(_("TOTP Code does not match"))
|
2018-11-16 08:10:35 +00:00
|
|
|
return self.cleaned_data.get('code')
|
|
|
|
|
|
|
|
|
2018-12-14 09:09:57 +00:00
|
|
|
class TOTPSetupStaticForm(forms.Form):
|
2018-11-16 08:10:35 +00:00
|
|
|
"""Static form to show generated static tokens"""
|
|
|
|
tokens = forms.MultipleChoiceField(disabled=True, required=False)
|