Esempio n. 1
0
    def post(self, request):
        """
        用户登录json api接口
        ---
        request_serializer: UserLoginSerializer
        """
        serializer = UserLoginSerializer(data=request.data)
        if serializer.is_valid():
            data = serializer.data
            user = auth.authenticate(username=data["username"],
                                     password=data["password"])
            # 用户名或密码错误的话 返回None
            if user:
                if not user.two_factor_auth:
                    auth.login(request, user)
                    return success_response(u"登录成功")

                # 没有输入两步验证的验证码
                if user.two_factor_auth and "tfa_code" not in data:
                    return success_response("tfa_required")

                if OtpAuth(user.tfa_token).valid_totp(data["tfa_code"]):
                    auth.login(request, user)
                    return success_response(u"登录成功")
                else:
                    return error_response(u"验证码错误")
            else:
                return error_response(u"用户名或密码错误")
        else:
            return serializer_invalid_response(serializer)
Esempio n. 2
0
 def put(self, request):
     serializer = TwoFactorAuthCodeSerializer(data=request.data)
     if serializer.is_valid():
         user = request.user
         code = serializer.data["code"]
         if OtpAuth(user.tfa_token).valid_totp(code):
             user.two_factor_auth = False
             user.save()
         else:
             return error_response(u"验证码错误")
     else:
         return serializer_invalid_response(serializer)
Esempio n. 3
0
 def post(self, request):
     """
     开启两步验证
     """
     serializer = TwoFactorAuthCodeSerializer(data=request.data)
     if serializer.is_valid():
         code = serializer.data["code"]
         user = request.user
         if OtpAuth(user.tfa_token).valid_totp(code):
             user.two_factor_auth = True
             user.save()
             return success_response(u"开启两步验证成功")
         else:
             return error_response(u"验证码错误")
     else:
         return serializer_invalid_response(serializer)
Esempio n. 4
0
    def get(self, request):
        """
        获取绑定二维码
        """
        user = request.user
        if user.two_factor_auth:
            return error_response(u"已经开启两步验证了")
        token = rand_str()
        user.tfa_token = token
        user.save()

        image = qrcode.make(OtpAuth(token).to_uri("totp", settings.WEBSITE_INFO["url"], "OnlineJudgeAdmin"))
        buf = StringIO.StringIO()
        image.save(buf, 'gif')

        return HttpResponse(buf.getvalue(), 'image/gif')