1 Star 0 Fork 7

小王/WebBlog

forked from thanatosx/WebBlog 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
FrontUtils.py 1.26 KB
一键复制 编辑 原始数据 按行查看 历史
thanatosx 提交于 2015-07-01 19:41 +08:00 . Thanatos Victoria
import hashlib
import logging
import asyncio
import time
from config.config_util import config
from domain import User
__author__ = 'thanatos'
__COOKIE_KEY = config.session.secret
def user2cookie(user, max_age):
"""
Generate cookie str by user.
"""
# build cookie string by: id-expires-sha1
expires = str(int(time.time() + max_age))
s = '%s-%s-%s-%s' % (user.id, user.password, expires, __COOKIE_KEY)
user_auth_cookie = [str(user.id), expires, hashlib.md5(s.encode('utf-8')).hexdigest()]
return '-'.join(user_auth_cookie)
@asyncio.coroutine
def cookie2user(cookie_str):
"""
Parse cookie and load user if cookie is valid.
"""
if not cookie_str:
return None
try:
L = cookie_str.split('-')
if len(L) != 3:
return None
uid, expires, sha1 = L
if int(expires) < time.time():
return None
user = yield from User.find(uid)
if user is None:
return None
s = '%s-%s-%s-%s' % (uid, user.password, expires, __COOKIE_KEY)
if sha1 != hashlib.md5(s.encode('utf-8')).hexdigest():
logging.info('invalid sha1')
return None
return user
except Exception as e:
logging.exception(e)
return None
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/xioaw/WebBlog.git
git@gitee.com:xioaw/WebBlog.git
xioaw
WebBlog
WebBlog
master

搜索帮助