import json

from django import http

def middleware(response):
    def inner(request):
        user_ok = '123'
        password_ok = '123'
        if request.method=='POST':
            user = request.POST.get("user")
            password = request.POST.get("password")
            if user is None:
                try:
                    user = json.loads(request.body.decode()).get("user")
                except Exception:
                    return http.HttpResponseForbidden("请输入用户名")
                if user is None:
                    return http.HttpResponseForbidden('请输入用户名')
            if password is None:
                try:
                    password = json.loads(request.body.decode()).get("password")
                except Exception:
                    return http.HttpResponseForbidden("请输入密码")
                if password is None:
                    return http.HttpResponseForbidden('请输入密码')
            if user!=user_ok or password!=password_ok:
                return http.HttpResponseForbidden('账号密码不正确')
            res = response(request)
        else:
            if len(request.body.decode())==0:
                return http.HttpResponseForbidden('请传入用户名和密码')
            req_data = json.loads(request.body.decode())
            user = req_data.get("user")  # 用户名
            password = req_data.get("password")  # 密码
            if user is None:
                return http.HttpResponseForbidden('请输入用户名')
            if password is None:
                return http.HttpResponseForbidden('请输入密码')
            if user!=user_ok or password!=password_ok:
                return http.HttpResponseForbidden('账号密码不正确')
            # print(request.method)
            res = response(request)
        return res
    return inner