from django.shortcuts import render
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from django.contrib.auth.hashers import make_password, check_password
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from .models import *
from .serializer import UserSerializer
# 注册视图
class UserRegisterView(ViewSet):
@action(methods=["POST"], detail=False)
def register(self, request):
usernmae = request.data.get('username')
password = request.data.get('password')
re_password = request.data.get('re_password')
is_superuser = request.data.get('is_superuser')
if User.objects.filter(username=usernmae):
return Response({'msg': f'用户{usernmae}已注册!', 'code': 400})
else:
if password == re_password:
user_date = {'username': usernmae, 'password': make_password(password), 'is_superuser': is_superuser}
user_serializer = UserSerializer(data=user_date)
if user_serializer.is_valid():
user_serializer.save()
return Response({'code': 201, 'msg': f'用户{usernmae}注册成功'})
else:
print(user_serializer.errors)
return Response({'code': 401, 'msg': '注册失败', 'errors': user_serializer.errors})
else:
return Response({'msg': '两次密码不一致', 'code': 402})
class UserLoginView(ViewSet):
@action(methods=["POST"], detail=False)
def login(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = User.objects.filter(username=username).first()
# 载荷
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
response_dict = {'code': 100, 'msg': None}
if user and check_password(password, user.password):
# 登录成功签发token
# 载荷
payload = jwt_payload_handler(user)
# token
token = jwt_encode_handler(payload)
response_dict['token'] = token
response_dict['msg'] = f'{user.username} Login successfuly!'
else: # 登录失败
response_dict['code'] = 101
response_dict['msg'] = 'Login Failed, The user name or password is incorrect! '
return Response(response_dict)