我們?cè)趯W(xué)習(xí)Flask的時(shí)候?qū)W習(xí)過(guò)flask-login庫(kù)進(jìn)行登錄管理,在tornado同樣存在類似的功能authenticated。我們可以使用這個(gè)裝飾器進(jìn)行登錄權(quán)限驗(yàn)證。
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
源碼中我們看到當(dāng)self.current_user為空的時(shí)候?qū)?huì)執(zhí)行下面的頁(yè)面跳轉(zhuǎn)。
我們?cè)倏聪逻@個(gè)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_user為RequestHandler的動(dòng)態(tài)屬性有兩種方式去賦予初值。
我們?cè)倏聪?code>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
這是一個(gè)RequestHandler的方法,通過(guò)重寫這個(gè)方法我們可以設(shè)置當(dāng)前登錄用戶。
注意:這個(gè)方法默認(rèn)返回的是None,并且調(diào)用這個(gè)方法是同步的,如果重寫的時(shí)候涉及到去查詢數(shù)據(jù)庫(kù)就會(huì)耗時(shí)。如果寫成協(xié)程,上層調(diào)用是不支持的。
我們接著看authenticated的源碼部分,當(dāng)用戶為登錄的時(shí)候回去調(diào)用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"]
會(huì)從配置中查找一個(gè)login_url進(jìn)行返回。
這樣是符合前后端不分離的單體項(xiàng)目,但是我們要是前后端分離就很不友好了。我們重寫改寫這個(gè)裝飾器來(lái)完成我們的要求。
我們自己編寫的裝飾器
我們?yōu)榱嗽谟脩魶]有登陸的時(shí)候返回json串而不是頁(yè)面。我們重新抒寫一個(gè)基于jwt的裝飾器。
def authenticated_async(method):
@functools.wraps(method)
async def wrapper(self, *args, **kwargs):
tsessionid = self.request.headers.get("tsessionid", None)
if tsessionid:
# 對(duì)token過(guò)期進(jìn)行異常捕捉
try:
# 從 token 中獲得我們之前存進(jìn) 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"]
# 從數(shù)據(jù)庫(kù)中獲取到user并設(shè)置給_current_user
try:
user = await self.application.objects.get(User, id=user_id)
self._current_user = user
# 此處需要使用協(xié)程方式執(zhí)行 因?yàn)樾枰b飾的是一個(gè)協(xié)程
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
這樣只要我們?cè)谛枰獧?quán)限的地方加上權(quán)限裝飾器即可。
class GroupHandler(RedisHandler):
@authenticated_async
async def get(self, *args, **kwargs):