Tornado學習筆記第七篇-tornado的authenticated裝飾器

我們在學習Flask的時候學習過flask-login庫進行登錄管理,在tornado同樣存在類似的功能authenticated。我們可以使用這個裝飾器進行登錄權限驗證。

Tornado的原生裝飾器

我們看下裝飾器authenticated的源碼,分析下工作原理。

def authenticated(method):
    """Decorate methods with this to require that the user be logged in.

    If the user is not logged in, they will be redirected to the configured
    `login url <RequestHandler.get_login_url>`.

    If you configure a login url with a query parameter, Tornado will
    assume you know what you're doing and use it as-is.  If not, it
    will add a `next` parameter so the login page knows where to send
    you once you're logged in.
    """
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not self.current_user:
            if self.request.method in ("GET", "HEAD"):
                url = self.get_login_url()
                if "?" not in url:
                    if urlparse.urlsplit(url).scheme:
                        # if login url is absolute, make next absolute too
                        next_url = self.request.full_url()
                    else:
                        next_url = self.request.uri
                    url += "?" + urlencode(dict(next=next_url))
                self.redirect(url)
                return
            raise HTTPError(403)
        return method(self, *args, **kwargs)
    return wrapper

源碼中我們看到當self.current_user為空的時候將會執行下面的頁面跳轉。

我們再看下這個self.current_user的源碼。

@property
def current_user(self):
    """The authenticated user for this request.
    This is set in one of two ways:
    * A subclass may override `get_current_user()`, which will be called
      automatically the first time ``self.current_user`` is accessed.
      `get_current_user()` will only be called once per request,
      and is cached for future access::
          def get_current_user(self):
              user_cookie = self.get_secure_cookie("user")
              if user_cookie:
                  return json.loads(user_cookie)
              return None
    * It may be set as a normal variable, typically from an overridden
      `prepare()`::
          @gen.coroutine
          def prepare(self):
              user_id_cookie = self.get_secure_cookie("user_id")
              if user_id_cookie:
                  self.current_user = yield load_user(user_id_cookie)
    Note that `prepare()` may be a coroutine while `get_current_user()`
    may not, so the latter form is necessary if loading the user requires
    asynchronous operations.
    The user object may be any type of the application's choosing.
    """
    if not hasattr(self, "_current_user"):
        self._current_user = self.get_current_user()
    return self._current_user

我們看到文檔注釋知道current_userRequestHandler的動態屬性有兩種方式去賦予初值。

我們再看下get_current_user的源碼:

def get_current_user(self):
    """Override to determine the current user from, e.g., a cookie.
    This method may not be a coroutine.
    """
    return None

這是一個RequestHandler的方法,通過重寫這個方法我們可以設置當前登錄用戶。

注意:這個方法默認返回的是None,并且調用這個方法是同步的,如果重寫的時候涉及到去查詢數據庫就會耗時。如果寫成協程,上層調用是不支持的。

我們接著看authenticated的源碼部分,當用戶為登錄的時候回去調用url = self.get_login_url()。我們看下get_login_url()的源碼:

def get_login_url(self):
    """Override to customize the login URL based on the request.
    By default, we use the ``login_url`` application setting.
    """
    self.require_setting("login_url", "@tornado.web.authenticated")
    return self.application.settings["login_url"]

會從配置中查找一個login_url進行返回。

這樣是符合前后端不分離的單體項目,但是我們要是前后端分離就很不友好了。我們重寫改寫這個裝飾器來完成我們的要求。

我們自己編寫的裝飾器

我們為了在用戶沒有登陸的時候返回json串而不是頁面。我們重新抒寫一個基于jwt的裝飾器。

def authenticated_async(method):
    @functools.wraps(method)
    async def wrapper(self, *args, **kwargs):
        tsessionid = self.request.headers.get("tsessionid", None)
        if tsessionid:

            # 對token過期進行異常捕捉
            try:

                # 從 token 中獲得我們之前存進 payload 的用戶id
                send_data = jwt.decode(tsessionid, self.settings["secret_key"], leeway=self.settings["jwt_expire"],
                                       options={"verify_exp": True})
                user_id = send_data["id"]

                # 從數據庫中獲取到user并設置給_current_user
                try:
                    user = await self.application.objects.get(User, id=user_id)
                    self._current_user = user

                    # 此處需要使用協程方式執行 因為需要裝飾的是一個協程
                    await method(self, *args, **kwargs)

                except User.DoesNotExist as e:
                    self.set_status(401)

            except jwt.ExpiredSignatureError as e:
                self.set_status(401)
        else:
            self.set_status(401)
        self.finish({})

    return wrapper

這樣只要我們在需要權限的地方加上權限裝飾器即可。

class GroupHandler(RedisHandler):

    @authenticated_async
    async def get(self, *args, **kwargs):
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容