用Python實現(xiàn)web端用戶登錄和注冊功能的教程
用戶管理是絕大部分Web網(wǎng)站都需要解決的問題。用戶管理涉及到用戶注冊和登錄。
用戶注冊相對簡單,我們可以先通過API把用戶注冊這個功能實現(xiàn)了:
_RE_MD5 = re.compile(r'^[0-9a-f]{32}$')
@api
@post('/api/users')
def register_user():
i = ctx.request.input(name='', email='', password='')
name = i.name.strip()
email = i.email.strip().lower()
password = i.password
if not name:
raise APIValueError('name')
if not email or not _RE_EMAIL.match(email):
raise APIValueError('email')
if not password or not _RE_MD5.match(password):
raise APIValueError('password')
user = User.find_first('where email=?', email)
if user:
raise APIError('register:failed', 'email', 'Email is already in use.')
user = User(name=name, email=email, password=password, image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email).hexdigest())
user.insert()
return user
注意用戶口令是客戶端傳遞的經(jīng)過MD5計算后的32位Hash字符串,所以服務(wù)器端并不知道用戶的原始口令。
接下來可以創(chuàng)建一個注冊頁面,讓用戶填寫注冊表單,然后,提交數(shù)據(jù)到注冊用戶的API:
{% extends '__base__.html' %}
{% block title %}注冊{% endblock %}
{% block beforehead %}
<script>
function check_form() {
$('#password').val(CryptoJS.MD5($('#password1').val()).toString());
return true;
}
</script>
{% endblock %}
{% block content %}
<div class="uk-width-2-3">
<h1>歡迎注冊!</h1>
<form id="form-register" class="uk-form uk-form-stacked" onsubmit="return check_form()">
<div class="uk-alert uk-alert-danger uk-hidden"></div>
<div class="uk-form-row">
<label class="uk-form-label">名字:</label>
<div class="uk-form-controls">
<input name="name" type="text" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<label class="uk-form-label">電子郵件:</label>
<div class="uk-form-controls">
<input name="email" type="text" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<label class="uk-form-label">輸入口令:</label>
<div class="uk-form-controls">
<input id="password1" type="password" class="uk-width-1-1">
<input id="password" name="password" type="hidden">
</div>
</div>
<div class="uk-form-row">
<label class="uk-form-label">重復(fù)口令:</label>
<div class="uk-form-controls">
<input name="password2" type="password" maxlength="50" placeholder="重復(fù)口令" class="uk-width-1-1">
</div>
</div>
<div class="uk-form-row">
<button type="submit" class="uk-button uk-button-primary"><i class="uk-icon-user"></i> 注冊</button>
</div>
</form>
</div>
{% endblock %}
Try
這樣我們就把用戶注冊的功能完成了:

用戶登錄比用戶注冊復(fù)雜。由于HTTP協(xié)議是一種無狀態(tài)協(xié)議,而服務(wù)器要跟蹤用戶狀態(tài),就只能通過cookie實現(xiàn)。大多數(shù)Web框架提供了Session功能來封裝保存用戶狀態(tài)的cookie。
Session的優(yōu)點是簡單易用,可以直接從Session中取出用戶登錄信息。
Session的缺點是服務(wù)器需要在內(nèi)存中維護一個映射表來存儲用戶登錄信息,如果有兩臺以上服務(wù)器,就需要對Session做集群,因此,使用Session的Web App很難擴展。
我們采用直接讀取cookie的方式來驗證用戶登錄,每次用戶訪問任意URL,都會對cookie進行驗證,這種方式的好處是保證服務(wù)器處理任意的URL都是無狀態(tài)的,可以擴展到多臺服務(wù)器。
由于登錄成功后是由服務(wù)器生成一個cookie發(fā)送給瀏覽器,所以,要保證這個cookie不會被客戶端偽造出來。
實現(xiàn)防偽造cookie的關(guān)鍵是通過一個單向算法(例如MD5),舉例如下:
當(dāng)用戶輸入了正確的口令登錄成功后,服務(wù)器可以從數(shù)據(jù)庫取到用戶的id,并按照如下方式計算出一個字符串:
"用戶id" + "過期時間" + MD5("用戶id" + "用戶口令" + "過期時間" + "SecretKey")
當(dāng)瀏覽器發(fā)送cookie到服務(wù)器端后,服務(wù)器可以拿到的信息包括:
- 用戶id
- 過期時間
- MD5值
如果未到過期時間,服務(wù)器就根據(jù)用戶id查找用戶口令,并計算:
MD5("用戶id" + "用戶口令" + "過期時間" + "SecretKey")
并與瀏覽器cookie中的MD5進行比較,如果相等,則說明用戶已登錄,否則,cookie就是偽造的。
這個算法的關(guān)鍵在于MD5是一種單向算法,即可以通過原始字符串計算出MD5,但無法通過MD5反推出原始字符串。
所以登錄API可以實現(xiàn)如下:
@api
@post('/api/authenticate')
def authenticate():
i = ctx.request.input()
email = i.email.strip().lower()
password = i.password
user = User.find_first('where email=?', email)
if user is None:
raise APIError('auth:failed', 'email', 'Invalid email.')
elif user.password != password:
raise APIError('auth:failed', 'password', 'Invalid password.')
max_age = 604800
cookie = make_signed_cookie(user.id, user.password, max_age)
ctx.response.set_cookie(_COOKIE_NAME, cookie, max_age=max_age)
user.password = '******'
return user
# 計算加密cookie:
def make_signed_cookie(id, password, max_age):
expires = str(int(time.time() + max_age))
L = [id, expires, hashlib.md5('%s-%s-%s-%s' % (id, password, expires, _COOKIE_KEY)).hexdigest()]
return '-'.join(L)
對于每個URL處理函數(shù),如果我們都去寫解析cookie的代碼,那會導(dǎo)致代碼重復(fù)很多次。
利用攔截器在處理URL之前,把cookie解析出來,并將登錄用戶綁定到ctx.request對象上,這樣,后續(xù)的URL處理函數(shù)就可以直接拿到登錄用戶:
@interceptor('/')
def user_interceptor(next):
user = None
cookie = ctx.request.cookies.get(_COOKIE_NAME)
if cookie:
user = parse_signed_cookie(cookie)
ctx.request.user = user
return next()
# 解密cookie:
def parse_signed_cookie(cookie_str):
try:
L = cookie_str.split('-')
if len(L) != 3:
return None
id, expires, md5 = L
if int(expires) < time.time():
return None
user = User.get(id)
if user is None:
return None
if md5 != hashlib.md5('%s-%s-%s-%s' % (id, user.password, expires, _COOKIE_KEY)).hexdigest():
return None
return user
except:
return None
Try
這樣,我們就完成了用戶注冊和登錄的功能。
相關(guān)文章
淺談python函數(shù)調(diào)用返回兩個或多個變量的方法
今天小編就為大家分享一篇淺談python函數(shù)調(diào)用返回兩個或多個變量的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
Linux下用Python腳本監(jiān)控目錄變化代碼分享
這篇文章主要介紹了Linux下用Python腳本監(jiān)控目錄變化代碼分享,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-05-05
mac安裝python3后使用pip和pip3的區(qū)別說明
這篇文章主要介紹了mac安裝python3后使用pip和pip3的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
使用python獲取CPU和內(nèi)存信息的思路與實現(xiàn)(linux系統(tǒng))
這篇文章主要介紹了python獲取CPU和內(nèi)存信息的思路與實現(xiàn),有需要的朋友可以參考一下2014-01-01
python用opencv完成圖像分割并進行目標(biāo)物的提取
這篇文章主要介紹了python用opencv完成圖像分割并進行目標(biāo)物的提取,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05

