# -*-coding:utf-8 -*- import json import time from django.shortcuts import render from django.http import HttpResponse from django.core.serializers.json import DjangoJSONEncoder from django.contrib.auth.hashers import make_password, check_password from django.views.decorators.csrf import csrf_exempt from models import * def JsonResponse(data): response = HttpResponse(json.dumps(data, cls=DjangoJSONEncoder), content_type="application/json") response['Access-Control-Allow-Origin'] = '*' return response def params(func): def _wrapper(*args, **kargs): request = args[0] if request.method == "GET": request.PARAMS = request.GET elif request.method == "POST" or request.method == "DELETE": if request.META.get('CONTENT_TYPE') == "application/json": request.PARAMS = json.loads(request.body) if request.body else {} else: request.PARAMS = request.POST elif request.method == "OPTIONS": return JsonResponse({"code": 0, "msg": "success"}) else: request.PARAMS = {} return func(*args, **kargs) return _wrapper def user_manage(request): user = request.session.get("user", None) @csrf_exempt @params def signup(request): """ 用户注册 :param request: :return: user """ req_params = request.PARAMS if req_params: try: username = req_params.get("username") password = make_password(req_params.get("password"), None, "pbkdf2_sha256") status = req_params.get("status") permission = req_params.get("permission") print(username,password,status,permission) obj, created = Users.objects.get_or_create(username=username) if not created: return JsonResponse({"code": -1, "msg": u"该用户名已被注册"}) else: # 保存其他信息 obj.username = username obj.password = password obj.status = status obj.permission = permission obj.signup_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) obj.save() return JsonResponse({"code": 0, "msg": u"注册成功"}) except: traceback.print_exc() else: return JsonResponse({"code": -1, "msg": u"缺少参数"}) @csrf_exempt @params def login(request): """ 用户登录 :param request: username, password :return: True / False """ data = request.PARAMS username = data.get("username", None) passwd = data.get("password", None) if not data: return JsonResponse({"code": -1, "msg": u"参数不完整"}) # 获取user的password try: user = Users.objects.get(username=username) except ObjectDoesNotExist: return JsonResponse({"code": -1, "msg": u"该用户不存在"}) # 检查密码是否正确 check_res = check_password(passwd, user.password) print("***********") print(passwd) print(user.password) print(check_res) if check_res: user_info = {"uid": user.id, "username": user.username, "status": user.status, "permission": user.permission,} request.session["user"] = user_info res = {"code": 0, "msg": "success", "user": user_info} else: res = {"code": -1, "msg": "password wrong!"} print "set session: --> ", request.session.get("user", None) return JsonResponse(res)