博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网站搭建笔记精简版---廖雪峰WebApp实战-Day10:用户登陆(下)笔记
阅读量:4165 次
发布时间:2019-05-26

本文共 5398 字,大约阅读时间需要 17 分钟。

这里的登陆页面转换花了好长时间。

网页登陆完整日志分析(重要)

此处讲述了具体signin.html的javascrip部分如何进行相应,写出了相关函数的调用顺序。花了好长时间理清楚思路。已调通的具体代码参考。或参考之前的博文。

Signin.html GET ‘/signin’直接进行middleware初始化处理,之后调用@get(‘/signin’)绑定函数Logger_factory -> response_factoty -> auth_factory -> Auth_factory -> Cookie2user -> find -> select -> RequestHandlerSignin()Signin.html POST ‘/api/authenticate’先进性middleware初始化处理,之后调用@GET(‘/api/authenticate’)绑定函数.Logger_factory -> response_factoty -> auth_factory authenticate -> findAll -> cookie2user –> RequestHandlerauthenticate()signin.html get ‘/’先进性middleware初始化处理,之后调用@GET(‘/’)函数.Logger_factory -> response_factoty -> auth_factory authenticate -> findAll -> cookie2user –> RequestHandlerindex ()

为什么要使用cookie

使用cookie验证后,网页右上角就会显示成当前的用户。Session功能可来封装保存用户状态的cookie,但每次均需要从session中取出用户登陆状态。但是由session作的webapp很难扩展。因此直接使用cookie验证。

教程采用直接读取cookie的方式来验证用户登录,即每次用户访问任意URL,都会对cookie进行验证,这种方式的好处是保证服务器处理任意的URL都是无状态的,可以扩展到多台服务器。
由于登录成功后是由服务器生成一个cookie发送给浏览器,所以,要保证这个cookie不会被客户端伪造出来。因此通过一种单向算法SHA1来实现cookie的防伪造。

密码生成

从上一节中,可以看出密码生成的步骤如下:

1 :在register.html文件中的JavaScript将passward进行第一次包装,生成A,传递到@get(’/api/users’)中。

CryptoJS.SHA1(email + ':' + this.password1).toString()

2:@post(’/api/users’)绑定函数接下来对A进行第二次包装,生成B。

sha1_passwd = '%s:%s' % (uid, passwd)

3:user2cookie函数对B进行第三次包装,生成C。

# id-B-到期时间-秘钥expires = str(int(time.time() + max_age))s = '%s-%s-%s-%s' % (user.id, user.passwd, expires, _COOKIE_KEY)

4: 返回用户id-到期时间-C

# 用户id-到期时间-CL = [user.id, expires, hashlib.sha1(s.encode('utf-8')).hexdigest()]

密码比较

在用户cookie未到期时,对用户认证的时候,通过signin.html里的SHA1(email+password)值对password进行包装生成A。

passwd: this.passwd==='' ? '' : CryptoJS.SHA1(email + ':' + this.passwd).toString()

接下来运行handlers中@post('/api/authenticate')的绑定函数,对密码进行再次包装生成B。

# check passwd:sha1 = hashlib.sha1()sha1.update(user.id.encode('utf-8'))sha1.update(b':')sha1.update(passwd.encode('utf-8'))

然后对比两个密码,判断是否登陆。

if user.passwd != sha1.hexdigest()

如果认证通过,更新cookie。最后通过signin.html中的location.assign('/');来跳转到主页面,并传递用户信息到blogs.html中。完成右上角的信息请求。

遇到问题

右上角登陆两个字一直不变成用户名。

解决办法:在@get(’/’)函数中return内容进行更改,以便使得右上角登陆两个字变成用户名。

return {	'__template__': 'blogs.html',	'blogs': blogs,	'__user__': request.__user__}

handler

# 进入登陆页面@get('/signin')async def signin():    return {        '__template__': 'signin.html'}# 登陆信息判别@post('/api/authenticate')async def authenticate(*, email, passwd):    if not email:        raise APIValueError('email', 'Invalid email.')    if not passwd:        raise APIValueError('passwd', 'Invalid password.')    users = await User.findAll('email=?', [email])    if len(users) == 0:        raise APIValueError('email', 'Email not exist.')    user = users[0]    # check passwd:    sha1 = hashlib.sha1()    sha1.update(user.id.encode('utf-8'))    sha1.update(b':')    sha1.update(passwd.encode('utf-8'))    if user.passwd != sha1.hexdigest():        raise APIValueError('passwd', 'Invalid password.')    # authenticate ok, set cookie:    r = web.Response()    r.set_cookie(COOKIE_NAME, user2cookie(user, 86400), max_age=86400, httponly=True)    user.passwd = '******'    r.content_type = 'application/json'    r.body = json.dumps(user, ensure_ascii=False).encode('utf-8')    return r

HTML

    
登录 - Awesome Python Webapp

app

利用middle在处理URL之前,把cookie解析出来,并将登录用户绑定到request对象上,这样,后续的URL处理函数就可以直接拿到登录用户:

# 解释cookie,此处需要异步,进行阻塞等待。async 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 = await User.find(uid)        if user is None:            return None		# 用数据库生成字符串c并与cookie进行比较        s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY)        if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest():            logging.info('invalid sha1')            return None        user.passwd = '******'        return user    except Exception as e:        logging.exception(e)        return None# 提取并解析cookie并绑定在request对象上async def auth_factory(app, handler):    async def auth(request):        logging.info('check user: %s %s' % (request.method, request.path))        request.__user__ = None #初始化        cookie_str = request.cookies.get(COOKIE_NAME) #读取cookie        if cookie_str:            user = await cookie2user(cookie_str)            if user:                logging.info('set current user: %s' % user.email)                request.__user__ = user        if request.path.startswith('/manage/') and (request.__user__ is None or not request.__user__.admin):            return web.HTTPFound('/signin')        return (await handler(request))    return auth

这里注意将该middleware注册到app信息中。

app = web.Application(loop=loop, middlewares=[    logger_factory, response_factory,auth_factory])

参考博客

转载地址:http://xmlxi.baihongyu.com/

你可能感兴趣的文章
2016-2017年度总结--行走在织梦的路上
查看>>
8月英语月刊--do it
查看>>
PV操作--demo test
查看>>
MongoDB配置--docker进阶
查看>>
0-1背包问题--动态规划C#Demo解析
查看>>
背包问题--贪心算法C#Demo解析
查看>>
EA逆向工程--逆向生成实体属性图
查看>>
J2EE规范-入门学习
查看>>
9月英语月刊--thinking
查看>>
0-1背包问题-回溯&贪心算法-C#Demo
查看>>
c++函数学习
查看>>
17年10月自考--一直在路上~
查看>>
docker部署swagger
查看>>
excel导入导出--Java
查看>>
创建一个项目--[Angular入门]
查看>>
aspx,ascx和ashx使用小结
查看>>
$再学习--JS进阶(一)
查看>>
Linux部署jboss引发的思考
查看>>
jdbc.properties数据库连接配置
查看>>
AJAX之XMLHttpRequest--验证(一)
查看>>