CMS_Django_Backend/apps/auth/views.py
2024-08-21 00:07:34 +08:00

85 lines
2.5 KiB
Python

import binascii
import json, datetime, base64
from django.shortcuts import HttpResponse
from django.middleware.csrf import get_token
from django.views.decorators.http import require_GET, require_POST
from apps.auth import models as auth_models
from django.contrib.auth.hashers import make_password, check_password
# Create your views here.
@require_GET
def gettoken(request):
"""
获取token
:param request:
:return:
"""
token = get_token(request)
return HttpResponse(json.dumps({'token': token}), content_type="application/json,charset=utf-8")
@require_POST
def search_user(request):
"""
查询用户名
:param request:
:return:
"""
username = request.POST.get('username')
user = auth_models.User.objects.filter(username=username)
if user.exists():
return HttpResponse("用户名已存在")
else:
return HttpResponse(True)
@require_POST
def add_user(request):
"""
用户注册
:param request: POST提交注册信息
:return: 注册结果
"""
username = request.POST.get("username")
pwd_base64 = base64.b64encode(request.POST.get("pwd"))
pwd = make_password(pwd_base64)
email = request.POST.get("email")
phone = request.POST.get("phone")
create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
last_login_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(username, pwd, email, phone)
avatar = request.FILES.get("avatar")
auth_models.User.objects.create(
username=username,
pwd=pwd,
email=email,
phone=phone,
create_time=create_time,
last_login_time=last_login_time,
avatar=avatar
)
return HttpResponse("添加用户成功")
@require_POST
def login_user(request):
"""
用户登录,验证用户密码是否正确,正确返回菜单,错误返回用户名或密码不正确
:param request:
:return:
"""
try:
username = request.POST.get("username")
pwd_input = base64.b64decode(request.POST.get("pwd"))
pwd_made = auth_models.User.objects.filter(username=username).first().pwd
pwd = check_password(pwd_input, pwd_made)
if pwd:
return HttpResponse(True)
else:
return HttpResponse("用户名或密码不正确")
except binascii.Error as e:
return HttpResponse("base64解码失败")
except Exception as e:
return HttpResponse("报错了")