網站搭建筆記精簡版---廖雪峰WebApp實戰-Day10:使用者登陸(下)筆記
這裡的登陸頁面轉換花了好長時間。
網頁登陸完整日誌分析(重要)
此處講述了具體signin.html的javascrip部分如何進行相應,寫出了相關函式的呼叫順序。花了好長時間理清楚思路。已調通的具體程式碼參考該網頁。或參考之前的博文。
Signin.html GET ‘/signin’ 直接進行middleware初始化處理,之後呼叫@get(‘/signin’)繫結函式 Logger_factory -> response_factoty -> auth_factory -> Auth_factory -> Cookie2user -> find -> select -> RequestHandler Signin() Signin.html POST ‘/api/authenticate’ 先進性middleware初始化處理,之後呼叫@GET(‘/api/authenticate’)繫結函式. Logger_factory -> response_factoty -> auth_factory authenticate -> findAll -> cookie2user –> RequestHandler authenticate() signin.html get ‘/’ 先進性middleware初始化處理,之後呼叫@GET(‘/’)函式. Logger_factory -> response_factoty -> auth_factory authenticate -> findAll -> cookie2user –> RequestHandler index ()
為什麼要使用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-到期時間-C
L = [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
<!DOCTYPE html>
<html class="uk-height-1-1">
<head>
<meta charset="utf-8" />
<title>登入 - Awesome Python Webapp</title>
<link rel="stylesheet" href="/static/css/uikit.min.css">
<link rel="stylesheet" href="/static/css/uikit.gradient.min.css">
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/sha1.min.js"></script>
<script src="/static/js/uikit.min.js"></script>
<script src="/static/js/vue.min.js"></script>
<script src="/static/js/awesome.js"></script>
<script>
$(function() {
var vmAuth = new Vue({
el: '#vm',
data: {
email: '',
passwd: ''
},
methods: {
submit: function(event) {
event.preventDefault();
var
$form = $('#vm'),
email = this.email.trim().toLowerCase(),
data = {
email: email,
passwd: this.passwd==='' ? '' : CryptoJS.SHA1(email + ':' + this.passwd).toString()
};
$form.postJSON('/api/authenticate', data, function(err, result) {
if (! err) {
location.assign('/');
}
});
}
}
});
});
</script>
</head>
<body class="uk-height-1-1">
<div class="uk-vertical-align uk-text-center uk-height-1-1">
<div class="uk-vertical-align-middle" style="width: 320px">
<p><a href="/" class="uk-icon-button"><i class="uk-icon-html5"></i></a> <a href="/">Awesome Python Webapp</a></p>
<form id="vm" v-on="submit: submit" class="uk-panel uk-panel-box uk-form">
<div class="uk-alert uk-alert-danger uk-hidden"></div>
<div class="uk-form-row">
<div class="uk-form-icon uk-width-1-1">
<i class="uk-icon-envelope-o"></i>
<input v-model="email" name="email" type="text" placeholder="電子郵件" maxlength="50" class="uk-width-1-1 uk-form-large">
</div>
</div>
<div class="uk-form-row">
<div class="uk-form-icon uk-width-1-1">
<i class="uk-icon-lock"></i>
<input v-model="passwd" name="passwd" type="password" placeholder="口令" maxlength="50" class="uk-width-1-1 uk-form-large">
</div>
</div>
<div class="uk-form-row">
<button type="submit" class="uk-width-1-1 uk-button uk-button-primary uk-button-large"><i class="uk-icon-sign-in"></i> 登入</button>
</div>
</form>
</div>
</div>
</body>
</html>
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
])