from django.shortcuts import render,HttpResponseRedirect from django.views.generic import View from django.http import JsonResponse import re import hashlib from .models import User
class Login(View): """登录""" def get(self, request): return render(request, 'login/login.html') def post(self, request): username = request.POST.get("username") password = request.POST.get("password") if not all([username, password]): return JsonResponse({'code': 0, "msg": "有必填项未填写"}) u = User.objects.filter(username=username).first() if not u: return JsonResponse({'code': 0, "msg": "账号不存在"}) # 校验通过 写入数据库 s = hashlib.sha1() s.update(password.encode("utf-8")) sha1_pwd = s.hexdigest() if u.password != sha1_pwd: return JsonResponse({'code': 0, "msg": "账号或者密码错误"}) request.session['username'] = u.username # session超时过期时间 request.session.set_expiry(60 * 60 * 24) return JsonResponse({'code': 1, "msg": "登录成功","url":'/'}) # 使用哈希 对密码进行加密处理 s = hashlib.sha1() s.update(password.encode("utf-8")) sha1_pwd = s.hexdigest() if u.password != sha1_pwd: return JsonResponse({'code': 0, 'msg': '账号或密码不正确'}) request.session['username'] = u.username request.session.set_expiry(60 * 60 * 24) return JsonResponse({'code': 1, 'msg': '登陆成功', 'url': '/'}) class Reg(View): # 注册 def get(self, request): return render(request, 'login/reg.html') def post(self, request): username = request.POST.get('username') password = request.POST.get('password') cpassword = request.POST.get('cpassword') # 判断注册流程 if not all([username, password, cpassword]): return JsonResponse({'code': 0, 'msg': '有必填项未填写'}) if username.isdigit(): return JsonResponse({'code': 0, 'msg': '账号不能全为数字'}) if not (len(username) < 10): return JsonResponse({'code': 0, 'msg': '账号不能超过10位'}) if not re.match('[0-9a-zA-Z_.!@#$%^&*]{4,10}', password): return JsonResponse({'code': 0, 'msg': '密码为4-10位的数字或字母'}) if password != cpassword: return JsonResponse({'code': 0, 'msg': '两次输入的密码不一致,请检查'}) # 使用哈希 对密码进行加密处理 s = hashlib.sha1() s.update(password.encode("utf-8")) sha1_pwd = s.hexdigest() #校验通过 写入数据库 try: u = User(username=username, password=sha1_pwd, ) u.save() # 注册成功 request.session['username'] = u.username request.session.set_expiry(60 * 60 * 24) return JsonResponse({'code': 1, 'msg': '注册成功','url':'/','username':username,'password':password}) except Exception as e: return JsonResponse({'code': 0, 'msg': f'该用户名已被使用{e}'}) def switchuser(request): # 切换用户 if 'username' in request.session.keys(): del request.session['username'] # 先将之前的账号下线 return HttpResponseRedirect('/')