From 77f32f0f4b98df0a5ddb17bf00ad5fb49e88ec57 Mon Sep 17 00:00:00 2001 From: wuyue Date: Sat, 8 Sep 2018 18:41:56 +0800 Subject: [PATCH 1/4] fix cors issue --- rest_backend/settings/base.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rest_backend/settings/base.py b/rest_backend/settings/base.py index ff003f4..39d5abe 100644 --- a/rest_backend/settings/base.py +++ b/rest_backend/settings/base.py @@ -51,11 +51,14 @@ MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', + # 跨域 + 'corsheaders.middleware.CorsMiddleware', # 激活locale 'django.middleware.locale.LocaleMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', From 2bd9f0fd3803b25266fed327fd40de50aef96035 Mon Sep 17 00:00:00 2001 From: wuyue Date: Sat, 8 Sep 2018 18:42:17 +0800 Subject: [PATCH 2/4] update django-filter --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index bf116bd..c0f8ffc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,7 +4,7 @@ django-debug-toolbar==1.9.1 django-rest-swagger==2.2.0 djangorestframework==3.8.2 djangorestframework-jwt==1.11.0 -django-filter==1.1.0 +django-filter==2.0.0 Pillow==5.1.0 uwsgi==2.0.15 # https://github.com/darklow/django-suit/tarball/v2 \ No newline at end of file From 5736dacb78b97848adf09be557a8a0775ea36748 Mon Sep 17 00:00:00 2001 From: wuyue Date: Sun, 9 Sep 2018 22:11:54 +0800 Subject: [PATCH 3/4] change session time, add token auth --- rest_backend/settings/base.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/rest_backend/settings/base.py b/rest_backend/settings/base.py index 39d5abe..0a29dc7 100644 --- a/rest_backend/settings/base.py +++ b/rest_backend/settings/base.py @@ -42,6 +42,7 @@ 'corsheaders', # rest接口框架 'rest_framework', + 'rest_framework.authtoken', # rest文档swagger 'rest_framework_swagger', 'rest_backend.libs.backend', @@ -57,6 +58,8 @@ 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', + # token参数认证 + 'rest_backend.utils.middleware.TokenAuthMiddleware', # 跨域 'corsheaders.middleware.CorsMiddleware', # 激活locale @@ -70,7 +73,7 @@ AUTH_USER_MODEL = 'accounts.User' # session过期时间设置 -SESSION_COOKIE_AGE = 60 * 30 +SESSION_COOKIE_AGE = 3600 * 24 TEMPLATES = [ { @@ -149,13 +152,18 @@ REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', + 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], - 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', + 'DEFAULT_FILTER_BACKENDS': [ + 'django_filters.rest_framework.DjangoFilterBackend', + ], + 'DEFAULT_PAGINATION_CLASS': + 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10 } From b665cc71812fabb29fa7f45b6a650d15bdcc75cd Mon Sep 17 00:00:00 2001 From: wuyue Date: Sun, 9 Sep 2018 22:12:40 +0800 Subject: [PATCH 4/4] add accounts profile support --- rest_backend/libs/accounts/urls.py | 24 ++++++++ rest_backend/libs/accounts/views.py | 96 +++++++++++++++++++++++++++++ rest_backend/libs/backend/urls.py | 2 +- rest_backend/utils/middleware.py | 20 ++++++ rest_backend/utils/suit.py | 1 + 5 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 rest_backend/libs/accounts/urls.py create mode 100644 rest_backend/utils/middleware.py diff --git a/rest_backend/libs/accounts/urls.py b/rest_backend/libs/accounts/urls.py new file mode 100644 index 0000000..40c6aee --- /dev/null +++ b/rest_backend/libs/accounts/urls.py @@ -0,0 +1,24 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- +""" +@author: wuyue +@contact: wuyue92tree@163.com +@software: IntelliJ IDEA +@file: urls.py +@create at: 2018-09-09 21:55 + +这一行开始写关于本文件的说明与解释 +""" + +from django.urls import path, include +from .views import * +from rest_framework import routers +# +# router = routers.DefaultRouter() +# router.register('profile', ProfileApiView.as_view()) + +urlpatterns = [ + path('profile/', ProfileApiView.as_view()), + path('initToken/', InitToken.as_view()), + path('getToken/', GetToken.as_view()) +] diff --git a/rest_backend/libs/accounts/views.py b/rest_backend/libs/accounts/views.py index e784a0b..2ef794c 100644 --- a/rest_backend/libs/accounts/views.py +++ b/rest_backend/libs/accounts/views.py @@ -2,5 +2,101 @@ from __future__ import unicode_literals from django.shortcuts import render +from rest_framework import generics +from rest_framework import serializers +from rest_framework.permissions import DjangoModelPermissions +from rest_framework.response import Response +from rest_framework import status +from .models import User +from rest_framework.authtoken.models import Token + # Create your views here. + + +class ProfileSerializer(serializers.ModelSerializer): + """ + 序列化用户信息 + """ + + class Meta: + model = User + # fields = '__all__' + fields = ( + 'username', 'email', 'phone', 'nickname', 'is_superuser', + 'is_staff', + 'last_login', 'date_joined') + read_only_fields = ( + 'username', 'is_superuser', 'is_staff', 'last_login', + 'date_joined') + + # def update(self, instance, validated_data): + + +class ProfileApiView(generics.GenericAPIView): + """ + 用户信息接口 + parameters: + - name: data + type: json + required: true + location: form + """ + serializer_class = ProfileSerializer + filter_backends = None + pagination_class = None + + def get(self, request): + queryset = User.objects.get(id=request.user.id) + serializer = self.get_serializer(queryset) + return Response(serializer.data) + + def post(self, request): + instance = User.objects.get(id=request.user.id) + serializer = ProfileSerializer(data=request.data) + if serializer.is_valid(): + serializer.update(instance=instance, + validated_data=serializer.validated_data) + return Response(serializer.data, status=status.HTTP_200_OK) + else: + return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + +class GetToken(generics.GenericAPIView): + """ + 获取Token令牌 + """ + queryset = Token.objects.all() + permission_classes = [DjangoModelPermissions] + pagination_class = None + + def get(self, request): + try: + access_token = self.get_queryset().get(user_id=request.user.id).key + return Response({'token': access_token}) + except Token.DoesNotExist: + return Response({}) + except Exception as e: + return Response({'系统异常: {}'.format(str(e))}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + +class InitToken(generics.GenericAPIView): + """ + 初始化Token令牌 + """ + queryset = Token.objects.all() + pagination_class = None + permission_classes = [DjangoModelPermissions] + + def get(self, request): + try: + if len(Token.objects.filter(user_id=request.user.id)) > 0: + item = Token.objects.get(user_id=request.user.id) + item.delete() + new_item = Token.objects.create(user_id=request.user.id) + new_item.save() + return Response({'token': new_item.key}) + except Exception as e: + return Response({'系统异常: {}'.format(str(e))}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR) diff --git a/rest_backend/libs/backend/urls.py b/rest_backend/libs/backend/urls.py index 5e93654..b99579e 100644 --- a/rest_backend/libs/backend/urls.py +++ b/rest_backend/libs/backend/urls.py @@ -26,5 +26,5 @@ path('docs/', schema_view), # add api here - + path('account/', include('rest_backend.libs.accounts.urls')), ] diff --git a/rest_backend/utils/middleware.py b/rest_backend/utils/middleware.py new file mode 100644 index 0000000..3aa0bca --- /dev/null +++ b/rest_backend/utils/middleware.py @@ -0,0 +1,20 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- +""" +@author: wuyue +@contact: wuyue92tree@163.com +@software: PyCharm +@file: middleware.py +@create at: 2018-07-28 23:05 + +这一行开始写关于本文件的说明与解释 +""" + +from django.utils.deprecation import MiddlewareMixin + + +class TokenAuthMiddleware(MiddlewareMixin): + def process_request(self, request): + if request.GET.get('token'): + request.META['HTTP_AUTHORIZATION'] = 'Token %s' % request.GET.get( + 'token') diff --git a/rest_backend/utils/suit.py b/rest_backend/utils/suit.py index e1a7a82..2639b0e 100644 --- a/rest_backend/utils/suit.py +++ b/rest_backend/utils/suit.py @@ -23,6 +23,7 @@ class SuitConfig(DjangoSuitConfig): ParentItem('认证和授权', children=[ ChildItem(model='accounts.user'), ChildItem(model='auth.group'), + ChildItem(model='authtoken.token'), ], icon='fa fa-users'), ParentItem('设置', children=[ # ChildItem('修改密码', url='admin:password_change'),