2019-08-21 12:27:21 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
from rest_framework.permissions import AllowAny
|
|
|
|
from rest_framework.response import Response
|
|
|
|
from rest_framework.generics import CreateAPIView
|
|
|
|
|
2019-11-05 10:46:29 +00:00
|
|
|
from common.utils import get_logger
|
|
|
|
|
2019-11-01 12:34:56 +00:00
|
|
|
from .. import serializers, errors
|
2019-11-05 10:46:29 +00:00
|
|
|
from ..mixins import AuthMixin
|
2019-08-21 12:27:21 +00:00
|
|
|
|
|
|
|
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
|
|
__all__ = ['TokenCreateApi']
|
|
|
|
|
|
|
|
|
2019-11-05 10:46:29 +00:00
|
|
|
class TokenCreateApi(AuthMixin, CreateAPIView):
|
2019-08-21 12:27:21 +00:00
|
|
|
permission_classes = (AllowAny,)
|
|
|
|
serializer_class = serializers.BearerTokenSerializer
|
|
|
|
|
2019-11-05 10:46:29 +00:00
|
|
|
def create_session_if_need(self):
|
|
|
|
if self.request.session.is_empty():
|
|
|
|
self.request.session.create()
|
2020-02-07 09:24:52 +00:00
|
|
|
self.request.session.set_expiry(600)
|
2019-11-01 12:34:56 +00:00
|
|
|
|
2019-08-21 12:27:21 +00:00
|
|
|
def create(self, request, *args, **kwargs):
|
2019-11-05 10:46:29 +00:00
|
|
|
self.create_session_if_need()
|
2019-11-01 12:34:56 +00:00
|
|
|
# 如果认证没有过,检查账号密码
|
2022-05-07 08:20:12 +00:00
|
|
|
serializer = self.get_serializer(data=request.data)
|
|
|
|
serializer.is_valid(raise_exception=True)
|
2019-08-21 12:27:21 +00:00
|
|
|
try:
|
2022-05-07 08:20:12 +00:00
|
|
|
user = self.get_user_or_auth(serializer.validated_data)
|
2019-11-01 12:34:56 +00:00
|
|
|
self.check_user_mfa_if_need(user)
|
|
|
|
self.check_user_login_confirm_if_need(user)
|
2019-08-21 12:27:21 +00:00
|
|
|
self.send_auth_signal(success=True, user=user)
|
2019-10-30 05:18:11 +00:00
|
|
|
resp = super().create(request, *args, **kwargs)
|
2021-11-11 11:07:13 +00:00
|
|
|
self.clear_auth_mark()
|
2019-10-30 05:18:11 +00:00
|
|
|
return resp
|
2019-11-01 12:34:56 +00:00
|
|
|
except errors.AuthFailedError as e:
|
2019-11-06 08:59:54 +00:00
|
|
|
return Response(e.as_data(), status=400)
|
2019-11-08 08:32:00 +00:00
|
|
|
except errors.NeedMoreInfoError as e:
|
|
|
|
return Response(e.as_data(), status=200)
|
2021-12-09 06:48:49 +00:00
|
|
|
except errors.MFAUnsetError:
|
|
|
|
return Response({'error': 'MFA unset, please set first'}, status=400)
|
|
|
|
except Exception as e:
|
|
|
|
return Response({"error": str(e)}, status=400)
|