質問

Remote Auth APIからの非同期コールバックを使用して認証関数を記述する必要があります。ログインによる単純な認証はうまく機能していますが、Cookieキーによる承認は機能しません。 Cookieでキー「LP_LOGIN」が表示され、ASYNCのようなAPI URLを取得し、ON_RESPONSE関数を実行するかどうかを確認する必要があります。

コードはほとんど機能しますが、2つの問題があります。まず、on_response関数では、すべてのページで承認されたユーザー用の安全なCookieをセットアップする必要があります。 code user_idは正しいidを返しますが、line:self.set_secure_cookie( "user"、user_id)は機能しません。なぜそれができるのですか?

および2番目の問題。 ASYNC Fetch API URL中に、ユーザーのページは、キー「ユーザー」を備えたON_RESPONSEセットアップ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
役に立ちましたか?

解決

竜巻メーリングリストでこれをクロスポストしたようです ここ

あなたが遭遇している問題の1つは、内部の非同期呼び出しを開始できないことです 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')
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top