123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- import re
- from django.views import View
- from django import http
- from rest_framework import status
- from rest_framework.authentication import SessionAuthentication
- from rest_framework.permissions import IsAuthenticated
- from rest_framework.response import Response
- from rest_framework.viewsets import ModelViewSet
- from rest_framework_jwt.authentication import JSONWebTokenAuthentication
- from .models import User
- from rest_framework_jwt.settings import api_settings
- from .serializers import UserModelSerializer
- jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
- jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
- jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
- from rest_framework_jwt.views import ObtainJSONWebToken
- class UserViewList(ModelViewSet):
- # 1,设置局部认证
- authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication,)
- # authentication_classes = [SessionAuthentication, BasicAuthentication]
- # 2,设置局部权限
- permission_classes = (IsAuthenticated,)
- # 1,提供通用的序列化器
- serializer_class = UserModelSerializer
- # 2,提供通用的数据集
- queryset = User.objects.all()
- class UserView(ModelViewSet):
- # 1,设置局部认证
- authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication,)
- # authentication_classes = [SessionAuthentication, BasicAuthentication]
- # 2,设置局部权限
- permission_classes = (IsAuthenticated,)
- # 1,提供通用的序列化器
- serializer_class = UserModelSerializer
- # 2,提供通用的数据集
- queryset = User.objects.all()
- # 用户登录
- class LoginView(ObtainJSONWebToken):
- def post(self, request, *args, **kwargs):
- usr = request.data.get('username')
- pwd = request.data.get('password')
- if re.match(r'.+@.+', usr):
- user_query = User.objects.filter(email=usr)
- elif re.match(r'1[3-9][0-9]{9}', usr):
- user_query = User.objects.filter(mobile=usr)
- else:
- user_query = User.objects.filter(username=usr)
- user_obj = user_query.first()
- if user_obj and user_obj.check_password(pwd):
- payload = jwt_payload_handler(user_obj)
- token = jwt_encode_handler(payload)
- data = {"code":"200","token":token,"username":user_obj.username,"email":user_obj.email,"mobile":user_obj.mobile,"effective_date":user_obj.effective_date}
- return Response(data,status=status.HTTP_200_OK)
- return Response('账号异常或不存在',status=status.HTTP_202_ACCEPTED)
|