2019-08-21 12:27:21 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
2020-08-05 08:04:05 +00:00
|
|
|
from django.shortcuts import redirect
|
2019-08-21 12:27:21 +00:00
|
|
|
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
|
|
|
# 如果认证没有过,检查账号密码
|
2019-08-21 12:27:21 +00:00
|
|
|
try:
|
2019-11-08 12:17:25 +00:00
|
|
|
user = self.check_user_auth_if_need()
|
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-11-05 10:46:29 +00:00
|
|
|
self.clear_auth_mark()
|
2019-10-30 05:18:11 +00:00
|
|
|
resp = super().create(request, *args, **kwargs)
|
|
|
|
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)
|
2020-08-05 08:04:05 +00:00
|
|
|
except errors.PasswdTooSimple as e:
|
|
|
|
return redirect(e.url)
|