views.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import re
  2. from django.views import View
  3. from django import http
  4. from rest_framework import status
  5. from rest_framework.authentication import SessionAuthentication
  6. from rest_framework.permissions import IsAuthenticated
  7. from rest_framework.response import Response
  8. from rest_framework.viewsets import ModelViewSet
  9. from rest_framework_jwt.authentication import JSONWebTokenAuthentication
  10. from .models import User
  11. from rest_framework_jwt.settings import api_settings
  12. from .serializers import UserModelSerializer
  13. jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
  14. jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
  15. jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
  16. from rest_framework_jwt.views import ObtainJSONWebToken
  17. class UserViewList(ModelViewSet):
  18. # 1,设置局部认证
  19. authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication,)
  20. # authentication_classes = [SessionAuthentication, BasicAuthentication]
  21. # 2,设置局部权限
  22. permission_classes = (IsAuthenticated,)
  23. # 1,提供通用的序列化器
  24. serializer_class = UserModelSerializer
  25. # 2,提供通用的数据集
  26. queryset = User.objects.all()
  27. class UserView(ModelViewSet):
  28. # 1,设置局部认证
  29. authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication,)
  30. # authentication_classes = [SessionAuthentication, BasicAuthentication]
  31. # 2,设置局部权限
  32. permission_classes = (IsAuthenticated,)
  33. # 1,提供通用的序列化器
  34. serializer_class = UserModelSerializer
  35. # 2,提供通用的数据集
  36. queryset = User.objects.all()
  37. # 用户登录
  38. class LoginView(ObtainJSONWebToken):
  39. def post(self, request, *args, **kwargs):
  40. usr = request.data.get('username')
  41. pwd = request.data.get('password')
  42. if re.match(r'.+@.+', usr):
  43. user_query = User.objects.filter(email=usr)
  44. elif re.match(r'1[3-9][0-9]{9}', usr):
  45. user_query = User.objects.filter(mobile=usr)
  46. else:
  47. user_query = User.objects.filter(username=usr)
  48. user_obj = user_query.first()
  49. if user_obj and user_obj.check_password(pwd):
  50. payload = jwt_payload_handler(user_obj)
  51. token = jwt_encode_handler(payload)
  52. data = {"code":"200","token":token,"username":user_obj.username,"email":user_obj.email,"mobile":user_obj.mobile,"effective_date":user_obj.effective_date}
  53. return Response(data,status=status.HTTP_200_OK)
  54. return Response('账号异常或不存在',status=status.HTTP_202_ACCEPTED)