2019-08-21 12:27:21 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2019-11-05 10:46:29 +00:00
|
|
|
import time
|
2020-06-15 12:31:50 +00:00
|
|
|
from django.utils.translation import ugettext as _
|
2019-08-21 12:27:21 +00:00
|
|
|
from rest_framework.permissions import AllowAny
|
|
|
|
from rest_framework.generics import CreateAPIView
|
2019-11-05 10:46:29 +00:00
|
|
|
from rest_framework.serializers import ValidationError
|
|
|
|
from rest_framework.response import Response
|
2019-08-21 12:27:21 +00:00
|
|
|
|
2019-11-05 10:46:29 +00:00
|
|
|
from common.permissions import IsValidUser
|
|
|
|
from ..serializers import OtpVerifySerializer
|
2019-08-21 12:27:21 +00:00
|
|
|
from .. import serializers
|
2019-11-05 10:46:29 +00:00
|
|
|
from .. import errors
|
|
|
|
from ..mixins import AuthMixin
|
2019-08-21 12:27:21 +00:00
|
|
|
|
|
|
|
|
2019-11-05 10:46:29 +00:00
|
|
|
__all__ = ['MFAChallengeApi', 'UserOtpVerifyApi']
|
|
|
|
|
|
|
|
|
|
|
|
class MFAChallengeApi(AuthMixin, CreateAPIView):
|
2019-08-21 12:27:21 +00:00
|
|
|
permission_classes = (AllowAny,)
|
|
|
|
serializer_class = serializers.MFAChallengeSerializer
|
2019-11-05 10:46:29 +00:00
|
|
|
|
|
|
|
def perform_create(self, serializer):
|
|
|
|
try:
|
|
|
|
user = self.get_user_from_session()
|
|
|
|
code = serializer.validated_data.get('code')
|
2019-11-18 10:12:03 +00:00
|
|
|
valid = user.check_mfa(code)
|
2019-11-05 10:46:29 +00:00
|
|
|
if not valid:
|
|
|
|
self.request.session['auth_mfa'] = ''
|
|
|
|
raise errors.MFAFailedError(
|
|
|
|
username=user.username, request=self.request
|
|
|
|
)
|
2019-11-06 04:06:30 +00:00
|
|
|
else:
|
|
|
|
self.request.session['auth_mfa'] = '1'
|
2019-11-05 10:46:29 +00:00
|
|
|
except errors.AuthFailedError as e:
|
2019-11-06 04:06:30 +00:00
|
|
|
data = {"error": e.error, "msg": e.msg}
|
2019-11-05 10:46:29 +00:00
|
|
|
raise ValidationError(data)
|
2019-11-08 08:32:00 +00:00
|
|
|
except errors.NeedMoreInfoError as e:
|
|
|
|
return Response(e.as_data(), status=200)
|
2019-11-05 10:46:29 +00:00
|
|
|
|
|
|
|
def create(self, request, *args, **kwargs):
|
|
|
|
super().create(request, *args, **kwargs)
|
|
|
|
return Response({'msg': 'ok'})
|
|
|
|
|
|
|
|
|
|
|
|
class UserOtpVerifyApi(CreateAPIView):
|
|
|
|
permission_classes = (IsValidUser,)
|
|
|
|
serializer_class = OtpVerifySerializer
|
|
|
|
|
|
|
|
def create(self, request, *args, **kwargs):
|
|
|
|
serializer = self.get_serializer(data=request.data)
|
|
|
|
serializer.is_valid(raise_exception=True)
|
|
|
|
code = serializer.validated_data["code"]
|
|
|
|
|
2019-11-18 10:12:03 +00:00
|
|
|
if request.user.check_mfa(code):
|
2019-11-05 10:46:29 +00:00
|
|
|
request.session["MFA_VERIFY_TIME"] = int(time.time())
|
|
|
|
return Response({"ok": "1"})
|
|
|
|
else:
|
2020-06-15 12:31:50 +00:00
|
|
|
return Response({"error": _("Code is invalid")}, status=400)
|