12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- from django.contrib import auth
- from rest_framework.views import APIView
- from rest_framework.authtoken.models import Token
- from rest_framework.authentication import BasicAuthentication, TokenAuthentication
- from .serializers import UserRegisterSerializer
- from django.middleware.csrf import get_token
- from django.contrib.auth import login
- from api.utils import *
- class UserRegisterAPI(APIView):
- authentication_classes = []
- permission_classes = []
- def get(self, request):
- csrf_token = get_token(request)
- response = Response({'csrftoken': csrf_token})
- # response["Access-Control-Allow-Origin"] = "*"
- return response
- def post(self, request):
- serializer = UserRegisterSerializer(data=request.data)
- if serializer.is_valid():
- newuser = serializer.save()
- token = Token.objects.create(user=newuser)
- # 注册完,同时将用户登录
- auth.login(request, newuser)
- return success(message="用户注册成功", data={
- "username": newuser.username,
- "displayname": newuser.displayname,
- "token": token.key,
- },code=201)
-
- # 处理错误信息
- errors = {}
- for field, field_errors in serializer.errors.items():
- if isinstance(field_errors, list):
- errors[field] = field_errors[0]
- print(field_errors)
- if field_errors[0].code == 'unique':
- errors[field] = str("用户名已存在")
- else:
- errors[field] = str(field_errors)
-
- return failed(message="注册失败", data=errors, code=400)
- class UserLoginAPI(APIView):
- authentication_classes = []
- permission_classes = []
-
- def get(self, request):
- csrf_token = get_token(request)
- response = Response({'csrftoken': csrf_token})
- # response["Access-Control-Allow-Origin"] = "*"
- return response
-
- def post(self, request):
- username = request.data.get('username')
- password = request.data.get('password')
- user = auth.authenticate(request, username=username, password=password)
- if user:
- auth.login(request, user)
- if Token.objects.filter(user=user).exists():
- token = Token.objects.get(user=user).key
- else:
- token = Token.objects.create(user=user).key
- return success(message="登录成功", data={
- 'username': user.username,
- 'displayName': user.displayname,
- 'token': token,
- }, code=201)
- else:
- return failed(message="登录失败", data="用户名不存在,或密码错误", code=401)
- class getDashboard(APIView):
-
- def post(self, request):
- return Response({
- 'data': 'yes'
- })
-
|