【发布时间】:2020-05-29 06:05:38
【问题描述】:
我正在创建一个 api,用于在登录时使用两因素身份验证对用户进行身份验证。
登录成功后跳转到以下视图。
class TOTPView(APIView):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.verified = False
self.last_verified_counter = -1
self.totp = self.generate_totp()
def get(self, request, *args, **kwargs):
logger.debug(self.totp)
return Response({'success': True},
status=status.HTTP_201_CREATED)
def post(self, request):
token = int(request.data.get('totp_token'))
# check if the current counter value is higher than the value of
# last verified counter and check if entered token is correct by
# calling totp.verify_token()
if ((self.totp.t() > self.last_verified_counter) and
(self.totp.verify(token))):
# if the condition is true, set the last verified counter value
# to current counter value, and return True
self.last_verified_counter = self.totp.t()
self.verified = True
return Response({'success': True},
status=status.HTTP_404_NOT_FOUND)
else:
# if the token entered was invalid or if the counter value
# was less than last verified counter, then return False
self.verified = False
return Response(status=status.HTTP_404_NOT_FOUND)
def generate_totp(self):
key = random_hex(20)
totp = TOTP(key)
totp.time = time.time()
return totp
在这里,当用户发布 OTP 代码/令牌时,POST 方法调用 self.totp 并通过再次调用 self.generate_totp() 覆盖其值。这永远不会验证 TOTP。
我在这里做错了吗?
【问题讨论】:
标签: python django rest django-rest-framework two-factor-authentication