jumpserver/apps/authentication/views/mfa.py

63 lines
1.9 KiB
Python
Raw Normal View History

2019-11-05 10:46:29 +00:00
# -*- coding: utf-8 -*-
#
from __future__ import unicode_literals
from django.views.generic.edit import FormView
from django.utils.translation import gettext_lazy as _
from django.conf import settings
2019-11-05 10:46:29 +00:00
from .. import forms, errors, mixins
from .utils import redirect_to_guard_view
2020-04-20 02:44:45 +00:00
from common.utils import get_logger
logger = get_logger(__name__)
2019-11-05 10:46:29 +00:00
__all__ = ['UserLoginOtpView']
class UserLoginOtpView(mixins.AuthMixin, FormView):
template_name = 'authentication/login_otp.html'
form_class = forms.UserCheckOtpCodeForm
redirect_field_name = 'next'
def form_valid(self, form):
otp_code = form.cleaned_data.get('code')
mfa_type = form.cleaned_data.get('mfa_type')
2019-11-05 10:46:29 +00:00
try:
self.check_user_mfa(otp_code, mfa_type)
2019-11-05 10:46:29 +00:00
return redirect_to_guard_view()
2021-04-08 04:47:49 +00:00
except (errors.MFAFailedError, errors.BlockMFAError) as e:
form.add_error('code', e.msg)
2019-11-05 10:46:29 +00:00
return super().form_invalid(form)
2020-04-20 02:44:45 +00:00
except Exception as e:
logger.error(e)
2021-04-08 04:47:49 +00:00
import traceback
2021-09-10 06:39:02 +00:00
traceback.print_exception(e)
return redirect_to_guard_view()
2019-11-05 10:46:29 +00:00
def get_context_data(self, **kwargs):
user = self.get_user_from_session()
context = {
'methods': [
{
'name': 'otp',
'label': _('One-time password'),
'enable': bool(user.otp_secret_key),
'selected': False,
},
{
'name': 'sms',
'label': _('SMS'),
'enable': bool(user.phone) and settings.SMS_ENABLED and settings.XPACK_ENABLED,
'selected': False,
},
]
}
for item in context['methods']:
if item['enable']:
item['selected'] = True
break
context.update(kwargs)
return context