Аутентификация с использованием ключа cookie с асинхронным обратным вызовом
-
27-09-2019 - |
Вопрос
Мне нужно написать функцию аутентификации с асинхронным обратным вызовом от Remote API Auth. Простая аутентификация со входом работает хорошо, но авторизация с ключом cookie не работает. Он должен проверить, если в файлах cookie присутствуют ключ «LP_Login», Fetch API URL URL, как Async и выполнить функцию on_response.
Код почти работает, но вижу две проблемы. Во-первых, в функции on_response мне нужно настроить безопасное cookie для авторизованного пользователя на каждой странице. В коде user_id возвращает правильный идентификатор, но строка: self.set_secure_cookie ("user", user_id) не работает. Почему это может быть?
И вторая проблема. Во время Async Fetch API URL API, страница пользователя загружена до того, как on_Response Setup Cookie с ключом «Пользователь», и страница будет иметь несанкционированную секцию со ссылкой на логин или вход. Это будет запутано для пользователей. Чтобы решить его, я могу остановить страницу загрузки для пользователя, которые пытаются загрузить первую страницу сайта. Можно ли сделать и как? Может быть, проблема имеет более правильный способ решить это?
class BaseHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get_current_user(self):
user_id = self.get_secure_cookie("user")
user_cookie = self.get_cookie("lp_login")
if user_id:
self.set_secure_cookie("user", user_id)
return Author.objects.get(id=int(user_id))
elif user_cookie:
url = urlparse("http://%s" % self.request.host)
domain = url.netloc.split(":")[0]
try:
username, hashed_password = urllib.unquote(user_cookie).rsplit(',',1)
except ValueError:
# check against malicious clients
return None
else:
url = "http://%s%s%s/%s/" % (domain, "/api/user/username/", username, hashed_password)
http = tornado.httpclient.AsyncHTTPClient()
http.fetch(url, callback=self.async_callback(self.on_response))
else:
return None
def on_response(self, response):
answer = tornado.escape.json_decode(response.body)
username = answer['username']
if answer["has_valid_credentials"]:
author = Author.objects.get(email=answer["email"])
user_id = str(author.id)
print user_id # It returns needed id
self.set_secure_cookie("user", user_id) # but session can's setup
Решение
Кажется, вы пересекаете это в списке рассылки Tornado здесь
Одна из проблем, в которых вы работаете, это то, что вы не можете начать асинхронный звонок внутри get_current_user
, вы можете начать только асинхронный звонок от чего-то, что происходит внутри get
или post
.
Я не проверил это, но я думаю, что это должно быть близко к тому, что вы ищете.
#!/bin/python
import tornado.web
import tornado.http
import tornado.escape
import functools
import logging
import urllib
import Author
def upgrade_lp_login_cookie(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.current_user and self.get_cookie('lp_login'):
self.upgrade_lp_login(self.async_callback(method, self, *args, **kwargs))
else:
return method(self, *args, **kwargs)
return wrapper
class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
user_id = self.get_secure_cookie("user")
if user_id:
return Author.objects.get(id=int(user_id))
def upgrade_lp_login(self, callback):
lp_login = self.get_cookie("lp_login")
try:
username, hashed_password = urllib.unquote(lp_login).rsplit(',',1)
except ValueError:
# check against malicious clients
logging.info('invalid lp_login cookie %s' % lp_login)
return callback()
url = "http://%(host)s/api/user/username/%s/%s" % (self.request.host,
urllib.quote(username),
urllib.quote(hashed_password))
http = tornado.httpclient.AsyncHTTPClient()
http.fetch(url, self.async_callback(self.finish_upgrade_lp_login, callback))
def finish_upgrade_lp_login(self, callback, response):
answer = tornado.escape.json_decode(response.body)
# username = answer['username']
if answer['has_valid_credentials']:
# set for self.current_user, overriding previous output of self.get_current_user()
self._current_user = Author.objects.get(email=answer["email"])
# set the cookie for next request
self.set_secure_cookie("user", str(self.current_user.id))
# now chain to the real get/post method
callback()
@upgrade_lp_login_cookie
def get(self):
self.render('template.tmpl')