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):
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容