用Python實(shí)現(xiàn)web端用戶登錄和注冊(cè)功能的教程
用戶管理是絕大部分Web網(wǎng)站都需要解決的問題。用戶管理涉及到用戶注冊(cè)和登錄。
用戶注冊(cè)相對(duì)簡(jiǎn)單,我們可以先通過API把用戶注冊(cè)這個(gè)功能實(shí)現(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計(jì)算后的32位Hash字符串,所以服務(wù)器端并不知道用戶的原始口令。
接下來可以創(chuàng)建一個(gè)注冊(cè)頁面,讓用戶填寫注冊(cè)表單,然后,提交數(shù)據(jù)到注冊(cè)用戶的API:
{% extends '__base__.html' %} {% block title %}注冊(cè){% 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>歡迎注冊(cè)!</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> 注冊(cè)</button> </div> </form> </div> {% endblock %} Try
這樣我們就把用戶注冊(cè)的功能完成了:
用戶登錄比用戶注冊(cè)復(fù)雜。由于HTTP協(xié)議是一種無狀態(tài)協(xié)議,而服務(wù)器要跟蹤用戶狀態(tài),就只能通過cookie實(shí)現(xiàn)。大多數(shù)Web框架提供了Session功能來封裝保存用戶狀態(tài)的cookie。
Session的優(yōu)點(diǎn)是簡(jiǎn)單易用,可以直接從Session中取出用戶登錄信息。
Session的缺點(diǎn)是服務(wù)器需要在內(nèi)存中維護(hù)一個(gè)映射表來存儲(chǔ)用戶登錄信息,如果有兩臺(tái)以上服務(wù)器,就需要對(duì)Session做集群,因此,使用Session的Web App很難擴(kuò)展。
我們采用直接讀取cookie的方式來驗(yàn)證用戶登錄,每次用戶訪問任意URL,都會(huì)對(duì)cookie進(jìn)行驗(yàn)證,這種方式的好處是保證服務(wù)器處理任意的URL都是無狀態(tài)的,可以擴(kuò)展到多臺(tái)服務(wù)器。
由于登錄成功后是由服務(wù)器生成一個(gè)cookie發(fā)送給瀏覽器,所以,要保證這個(gè)cookie不會(huì)被客戶端偽造出來。
實(shí)現(xiàn)防偽造cookie的關(guān)鍵是通過一個(gè)單向算法(例如MD5),舉例如下:
當(dāng)用戶輸入了正確的口令登錄成功后,服務(wù)器可以從數(shù)據(jù)庫取到用戶的id,并按照如下方式計(jì)算出一個(gè)字符串:
"用戶id" + "過期時(shí)間" + MD5("用戶id" + "用戶口令" + "過期時(shí)間" + "SecretKey")
當(dāng)瀏覽器發(fā)送cookie到服務(wù)器端后,服務(wù)器可以拿到的信息包括:
- 用戶id
- 過期時(shí)間
- MD5值
如果未到過期時(shí)間,服務(wù)器就根據(jù)用戶id查找用戶口令,并計(jì)算:
MD5("用戶id" + "用戶口令" + "過期時(shí)間" + "SecretKey")
并與瀏覽器cookie中的MD5進(jìn)行比較,如果相等,則說明用戶已登錄,否則,cookie就是偽造的。
這個(gè)算法的關(guān)鍵在于MD5是一種單向算法,即可以通過原始字符串計(jì)算出MD5,但無法通過MD5反推出原始字符串。
所以登錄API可以實(shí)現(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 # 計(jì)算加密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) 對(duì)于每個(gè)URL處理函數(shù),如果我們都去寫解析cookie的代碼,那會(huì)導(dǎo)致代碼重復(fù)很多次。 利用攔截器在處理URL之前,把cookie解析出來,并將登錄用戶綁定到ctx.request對(duì)象上,這樣,后續(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
這樣,我們就完成了用戶注冊(cè)和登錄的功能。
- Python實(shí)現(xiàn)注冊(cè)登錄系統(tǒng)
- Python登錄注冊(cè)驗(yàn)證功能實(shí)現(xiàn)
- Python實(shí)現(xiàn)注冊(cè)、登錄小程序功能
- Python制作簡(jiǎn)易注冊(cè)登錄系統(tǒng)
- Python +Selenium解決圖片驗(yàn)證碼登錄或注冊(cè)問題(推薦)
- python實(shí)現(xiàn)登錄與注冊(cè)系統(tǒng)
- Python3 Tkinkter + SQLite實(shí)現(xiàn)登錄和注冊(cè)界面
- python應(yīng)用文件讀取與登錄注冊(cè)功能
- Python?+?Tkinter連接本地MySQL數(shù)據(jù)庫簡(jiǎn)單實(shí)現(xiàn)注冊(cè)登錄
- Python實(shí)現(xiàn)用戶登錄注冊(cè)
相關(guān)文章
淺談python函數(shù)調(diào)用返回兩個(gè)或多個(gè)變量的方法
今天小編就為大家分享一篇淺談python函數(shù)調(diào)用返回兩個(gè)或多個(gè)變量的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01Linux下用Python腳本監(jiān)控目錄變化代碼分享
這篇文章主要介紹了Linux下用Python腳本監(jiān)控目錄變化代碼分享,本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-05-05mac安裝python3后使用pip和pip3的區(qū)別說明
這篇文章主要介紹了mac安裝python3后使用pip和pip3的區(qū)別說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-09-09Python random模塊用法解析及簡(jiǎn)單示例
這篇文章主要介紹了Python random模塊用法解析及簡(jiǎn)單示例,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12使用python獲取CPU和內(nèi)存信息的思路與實(shí)現(xiàn)(linux系統(tǒng))
這篇文章主要介紹了python獲取CPU和內(nèi)存信息的思路與實(shí)現(xiàn),有需要的朋友可以參考一下2014-01-01Python實(shí)現(xiàn)求一個(gè)集合所有子集的示例
今天小編就為大家分享一篇Python 實(shí)現(xiàn)求一個(gè)集合所有子集的示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-05-05python用opencv完成圖像分割并進(jìn)行目標(biāo)物的提取
這篇文章主要介紹了python用opencv完成圖像分割并進(jìn)行目標(biāo)物的提取,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05