Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

wechat xuhss 602℃ 0评论

校驗登录密码

这里用到了加密算法,后面做管理员列表也需要用到这个算法。

創建一个userservice的公共服务 用于生成密钥:

20210731094015 - Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

import hashlib,base64

class UserService():

    @staticmethod
    def genePwd(pwd,salt):
        m = hashlib.md5()
        str = r"%s-%s"%(base64.encodebytes(pwd.encode("utf-8")), salt)
        m.update(str.encode("utf-8"))
        return m.hexdigest()

然后再User.py的接口中 判断是否密钥正确:

# -*- coding: utf-8 -*-
from flask import Blueprint,render_template,request,jsonify

from common.models.User import User
from common.libs.user.UserService import UserService
route_user = Blueprint( 'user_page',__name__ )

@route_user.route( "/login", methods = ["GET", "POST"] )
def login():
    if request.method == "GET":
        return render_template( "user/login.html" )

    req = request.values
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    resp = {'code':200, 'msg':'登录成功', 'data':{}}
    if login_name is None or len(login_name)<1:
        resp['code']=-1
        resp['msg']="请输入正确的登录用户名~"
        return jsonify(resp)

    if login_pwd is None or len(login_pwd)<1:
        resp['code']=-1
        resp['msg']="请输入正确的登录密码~"
        return jsonify(resp)

    user_info = User.query.filter_by(login_name=login_name).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = "请输入正确的登录用户名和密码1"
        return jsonify(resp)

    if user_info.login_pwd != UserService.genePwd(login_pwd,user_info.login_salt):
        resp['code'] = -1
        resp['msg'] = "请输入正确的登录用户名和密码2"
        return jsonify(resp)

    return jsonify(resp)

这时,输入错误的密码也会得到code=-1的提示。

异步提交ajax請求編程實現

返回json一般用到异步提交:

修改login.html

标签改为div,然后去除action

                <div class="m-t" role="form" >
                    <div class="form-group text-center">
                        <h2 class="font-bold">登录</h2>
                    </div>
                    <div class="form-group">
                        <input type="text" name="login_name" class="form-control" placeholder="请输入登录用户名">
                    </div>
                    <div class="form-group">
                        <input type="password" name="login_pwd" class="form-control" placeholder="请输入登录密码">
                    </div>
                    <button type="submit" class="btn btn-primary block full-width m-b">登录</button>
                </div>

添加ajax请求:

20210731100647 - Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

創建user文件夾login.js 添加ajax请求

20210731101051 - Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

common.js中添加buildurl函数:

方便统一管理:

20210731105136 - Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

    buildUrl:function (path, params) {
        var url = "" + path;
        var _paramUrl = "";
        if (params){
            _paramUrl = Object.keys(params).map(
                function (k) {
                    return [encodeURIComponent(k),encodeURIComponent(params[k])].join("=");
                }
            ).join("&")
            _paramUrl = "?"+_paramUrl;
        }
        return url + _paramUrl;
    }

login.js的内容:

;
var user_login_ops = {
    init:function () {
        this.eventBind();
    },
    eventBind:function () {
        $(".login_wrap .do-login").click(function () {
            var login_name = $(".login_wrap input[name=login_name]").val()
            var login_pwd = $(".login_wrap input[name=login_pwd]").val()

            if (login_name == undefined || login_name.length < 1){
                common_ops.alert("请输入正确的用户名")
                return;
            }
            if (login_pwd == undefined || login_pwd.length < 1){
                common_ops.alert("请输入正确的登录密码")
                return;
            }

            $.ajax({
                url:common_ops.buildUrl("/user/login"),
                type:"POST",
                data:{'login_name':login_name, 'login_pwd':login_pwd},
                dataType:'json',
                success:function (res) {

                }
            });

        });
    }
}

$(document).ready(function () {
    user_login_ops.init();
});

login.html模板中 提交引入login.js文件

20210731110607 - Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

{% block js %}
<script src="{{ buildStaticUrl('/js/user/login.js') }}"></script>
{% endblock %}

点击登录可以看到发送了ajax请求:

20210731111221 - Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

login.js创建一个提交跳转的请求:

            $.ajax({
                url:common_ops.buildUrl("/user/login"),
                type:"POST",
                data:{'login_name':login_name, 'login_pwd':login_pwd},
                dataType:'json',
                success:function (res) {
                    var callback = null;
                    if (res.code == 200){
                        callback = function () {
                            window.location.href = common_ops.buildUrl("/");
                        }
                    }
                    common_ops.alert(res.msg, callback)
                }
            });

重复提交处理ajax

var user_login_ops = {
    init:function () {
        this.eventBind();
    },
    eventBind:function () {
        $(".login_wrap .do-login").click(function () {

            var btn_target = $(this);
            if (btn_target.hasClass("disabled")){
                common_ops.alert("正在处理,请不要重复提交Q");
                return;
            }

            var login_name = $(".login_wrap input[name=login_name]").val()
            var login_pwd = $(".login_wrap input[name=login_pwd]").val()

            if (login_name == undefined || login_name.length < 1){
                common_ops.alert("请输入正确的用户名")
                return;
            }
            if (login_pwd == undefined || login_pwd.length < 1){
                common_ops.alert("请输入正确的登录密码")
                return;
            }

            btn_target.addClass("disabled");

            $.ajax({
                url:common_ops.buildUrl("/user/login"),
                type:"POST",
                data:{'login_name':login_name, 'login_pwd':login_pwd},
                dataType:'json',
                success:function (res) {
                    btn_target.removeClass("disabled")
                    var callback = null;
                    if (res.code == 200){
                        callback = function () {
                            window.location.href = common_ops.buildUrl("/");
                        }
                    }
                    common_ops.alert(res.msg, callback)
                }
            });
        });
    }
}

用户登录态的保存:

加密cookie算法实现:

UserService.py实现

import hashlib,base64

class UserService():
    @staticmethod
    def geneAuthCode(user_info):
        m  = hashlib.md5()
        str = r"%s-%s-%s-%s" % (user_info.uid, user_info.login_name, user_info.login_pwd, user_info.login_salt)
        m.update(str.encode("utf-8"))
        return m.hexdigest()

定義通用cookie配置文件的配置:

20210731114757 - Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

AUTH_COOKIE_NAME = "mooc_food"

User.py登录接口添加cookie返回

# -*- coding: utf-8 -*-
from flask import Blueprint,render_template,request,jsonify,make_response
import json
from common.models.User import User
from common.libs.user.UserService import UserService
from application import app

route_user = Blueprint( 'user_page',__name__ )

@route_user.route( "/login", methods = ["GET", "POST"] )
def login():
    if request.method == "GET":
        return render_template( "user/login.html" )

    req = request.values
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    resp = {'code':200, 'msg':'登录成功', 'data':{}}
    if login_name is None or len(login_name)<1:
        resp['code']=-1
        resp['msg']="请输入正确的登录用户名~"
        return jsonify(resp)

    if login_pwd is None or len(login_pwd)<1:
        resp['code']=-1
        resp['msg']="请输入正确的登录密码~"
        return jsonify(resp)

    user_info = User.query.filter_by(login_name=login_name).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = "请输入正确的登录用户名和密码1"
        return jsonify(resp)

    if user_info.login_pwd != UserService.genePwd(login_pwd,user_info.login_salt):
        resp['code'] = -1
        resp['msg'] = "请输入正确的登录用户名和密码2"
        return jsonify(resp)

    responce = make_response(json.dumps(resp))
    responce.set_cookie(app.config["AUTH_COOKIE_NAME"], "%s#%s"%(UserService.geneAuthCode(user_info), user_info.uid))

    return responce

开始运行前,先清楚浏览器cookie:

20210731115522 - Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

运行后 产生了这样的一条cookie:

20210731115658 - Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

攔截器检测登录状态决定是否登录成功

創建一個攔截器:

20210731115941 - Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

from application import app
from flask import request

@app.before_request
def before_request():
    path = request.path
    check_login()

'''
判断用户是否登录

'''
def check_login():
    cookies = request.cookies
    auth_cookie = cookies[app.config['AUTH_COOKIE_NAME']] if app.config['AUTH_COOKIE_NAME'] in cookies else None
    #app.logger.info(auth_cookie)
    if auth_cookie is None:
        return false

www.py引入统一拦截器:

from application import app

'''
統計拦截器
'''
from web.interceptors.authInterceptor import *

'''
蓝图功能
'''
from web.controllers.index import route_index
from web.controllers.user.User import route_user
from web.controllers.static import route_static
from web.controllers.account.Account import route_account

运行就能看到打印出来的cookie

转载请注明:xuhss » Python flask实战订餐系统微信小程序-21登录密码校验及cookie保存

喜欢 (4)

您必须 登录 才能发表评论!