Python版——博客網站<三> 引入python-markdown2與用戶註冊和登陸

 

開源地址:https://github.com/leebingbin/Python3.WebAPP.Blogphp

 

1、 python-markdown2

    用戶管理是絕大部分Web網站都須要解決的問題。用戶管理涉及到最核心的無非是用戶註冊和登陸。不過,在此以前,咱們須要先引入python-markdown模塊 (github主頁:https://github.com/trentm/python-markdown2):python-markdown模塊使用有兩個模式,一種是作爲獨立的命令行,另一種是作爲python的模塊使用。markdown工具,能夠將txt轉化成html格式。這一類工具的做用是將按必定格式寫成的可讀性強的文本文件轉化爲結構化的標準xhtml或html。markdown最初用perl寫成,後來移植到python,java,php。這裏主要介紹下python-markdown的用法。markdown工具在不少程序中用到,好比說wordpress, pybb等,特別適合wiki, blog,forum等。html

markdown2.py

    示例:java

python markdown2.py foo.md > foo.html

    目前作的博客網站,是作爲python的模塊使用。 用戶註冊相對簡單,咱們能夠先經過API (可參考:http://www.javashuo.com/article/p-ktnjrglh-by.html)把用戶註冊這個功能實現了:python

@post('/api/users')
def api_register_user(*, email, name, passwd):
    if not name or not name.strip():
        raise APIValueError('name')
    if not email or not _RE_EMAIL.match(email):
        raise APIValueError('email')
    if not passwd or not _RE_SHA1.match(passwd):
        raise APIValueError('passwd')
    users = yield from User.findAll('email=?', [email])
    if len(users) > 0:
        raise APIError('register:failed', 'email', 'Email is already in use.')
    uid = next_id()
    sha1_passwd = '%s:%s' % (uid, passwd)
    user = User(id=uid, name=name.strip(), email=email, passwd=hashlib.sha1(sha1_passwd.encode('utf-8')).hexdigest(), image='http://www.gravatar.com/avatar/%s?d=mm&s=120' % hashlib.md5(email.encode('utf-8')).hexdigest())
    yield from user.save()
    # make session 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

2、 註冊

    注意用戶口令是客戶端傳遞的通過SHA1計算後的40位Hash字符串,因此服務器端並不知道用戶的原始口令。接下來能夠建立一個註冊頁面,讓用戶填寫註冊表單,而後,提交數據到註冊用戶的API:git

{% extends '__base__.html' %}

{% block title %}註冊{% endblock %}

{% block beforehead %}

<script>

function validateEmail(email) {
    var re = /^[a-z0-9\.\-\_]+\@[a-z0-9\-\_]+(\.[a-z0-9\-\_]+){1,4}$/;
    return re.test(email.toLowerCase());
}

$(function () {
    var vm = new Vue({
        el: '#vm',
        data: {
            name: '',
            email: '',
            password1: '',
            password2: ''
        },
        methods: {
            submit: function (event) {
                event.preventDefault();
                var $form = $('#vm');
                if (! this.name.trim()) {
                    return $form.showFormError('請輸入名字');
                }
                if (! validateEmail(this.email.trim().toLowerCase())) {
                    return $form.showFormError('請輸入正確的Email地址');
                }
                if (this.password1.length < 6) {
                    return $form.showFormError('口令長度至少爲6個字符');
                }
                if (this.password1 !== this.password2) {
                    return $form.showFormError('兩次輸入的口令不一致');
                }
                var email = this.email.trim().toLowerCase();
                $form.postJSON('/api/users', {
                    name: this.name.trim(),
                    email: email,
                    passwd: CryptoJS.SHA1(email + ':' + this.password1).toString()
                }, function (err, r) {
                    if (err) {
                        return $form.showFormError(err);
                    }
                    return location.assign('/');
                });
            }
        }
    });
    $('#vm').show();
});

</script>

{% endblock %}

{% block content %}

    <div class="uk-width-2-3">
        <h1>歡迎註冊!</h1>
        <form id="vm" v-on="submit: submit" class="uk-form uk-form-stacked">
            <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 v-model="name" type="text" maxlength="50" placeholder="名字" class="uk-width-1-1">
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">電子郵件:</label>
                <div class="uk-form-controls">
                    <input v-model="email" type="text" maxlength="50" placeholder="your-name@example.com" class="uk-width-1-1">
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">輸入口令:</label>
                <div class="uk-form-controls">
                    <input v-model="password1" type="password" maxlength="50" placeholder="輸入口令" class="uk-width-1-1">
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">重複口令:</label>
                <div class="uk-form-controls">
                    <input v-model="password2" type="password" maxlength="50" placeholder="重複口令" 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 %}

這樣咱們就把用戶註冊的功能完成了:github

 

3、 登陸

    用戶登陸比用戶註冊複雜。因爲HTTP協議是一種無狀態協議,而服務器要跟蹤用戶狀態,就只能經過cookie實現。大多數Web框架提供了Session功能來封裝保存用戶狀態的cookie。Session的優勢是簡單易用,能夠直接從Session中取出用戶登陸信息。Session的缺點是服務器須要在內存中維護一個映射表來存儲用戶登陸信息,若是有兩臺以上服務器,就須要對Session作集羣,所以,使用Session的Web App很難擴展。web

    咱們採用直接讀取cookie的方式來驗證用戶登陸,每次用戶訪問任意URL,都會對cookie進行驗證,這種方式的好處是保證服務器處理任意的URL都是無狀態的,能夠擴展到多臺服務器。因爲登陸成功後是由服務器生成一個cookie發送給瀏覽器,因此,要保證這個cookie不會被客戶端僞造出來。實現防僞造cookie的關鍵是經過一個單向算法(例如SHA1),舉例以下:算法

    當用戶輸入了正確的口令登陸成功後,服務器能夠從數據庫取到用戶的id,並按照以下方式計算出一個字符串:數據庫

"用戶id" + "過時時間" + SHA1("用戶id" + "用戶口令" + "過時時間" + "SecretKey")

    當瀏覽器發送cookie到服務器端後,服務器能夠拿到的信息包括:json

  • 用戶id

  • 過時時間

  • SHA1值

    若是未到過時時間,服務器就根據用戶id查找用戶口令,並計算:

SHA1("用戶id" + "用戶口令" + "過時時間" + "SecretKey")

    並與瀏覽器cookie中的MD5進行比較,若是相等,則說明用戶已登陸,不然,cookie就是僞造的。這個算法的關鍵在於SHA1是一種單向算法,便可以經過原始字符串計算出SHA1結果,但沒法經過SHA1結果反推出原始字符串。

    因此登陸API能夠實現以下:

@post('/api/authenticate')
def authenticate(*, email, passwd):
    if not email:
        raise APIValueError('email', 'Invalid email.')
    if not passwd:
        raise APIValueError('passwd', 'Invalid password.')
    users = yield from 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
# 計算加密cookie
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.passwd, expires, _COOKIE_KEY)
    L = [user.id, expires, hashlib.sha1(s.encode('utf-8')).hexdigest()]
    return '-'.join(L)

    對於每一個URL處理函數,若是咱們都去寫解析cookie的代碼,那會致使代碼重複不少次。

    利用middle在處理URL以前,把cookie解析出來,並將登陸用戶綁定到 request 對象上,這樣,後續

的URL處理函數就能夠直接拿到登陸用戶:

@asyncio.coroutine
def auth_factory(app, handler):
    @asyncio.coroutine
    def auth(request):
        logging.info('check user: %s %s' % (request.method, request.path))
        request.__user__ = None
        cookie_str = request.cookies.get(COOKIE_NAME)
        if cookie_str:
            user = yield from 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 (yield from handler(request))
    return 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.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

    至此,完成了用戶註冊和登陸的功能。

 

本文爲博主原創文章,轉載請註明出處!

https://my.oschina.net/u/3375733/blog/

相關文章
相關標籤/搜索