Showing
1 changed file
with
141 additions
and
188 deletions
1 | -import mimetypes | ||
2 | -import json | ||
3 | -import os | ||
4 | -from datetime import datetime | ||
5 | - | ||
6 | -import boto3 | ||
7 | - | ||
8 | -from django.contrib.auth.models import User | ||
9 | -from django.core import serializers | ||
10 | -from django.views.decorators.csrf import csrf_exempt | ||
11 | -from rest_framework import viewsets | ||
12 | -from rest_framework import permissions | ||
13 | -from rest_framework.response import Response | ||
14 | -from rest_framework.decorators import action | ||
15 | -from rest_framework.permissions import IsAuthenticated, AllowAny | ||
16 | - | ||
17 | -from api.models import Item, SharedItem | ||
18 | -from api.serializers import UserSerializer,GroupSerializer,ItemSerializer | ||
19 | -from rest_framework import status | ||
20 | -from annoying.functions import get_object_or_None | ||
21 | - | ||
22 | -class UserViewSet(viewsets.ModelViewSet): | ||
23 | - """ | ||
24 | - API endpoint that allows users to be viewed or edited. | ||
25 | - """ | ||
26 | - queryset = User.objects.all().order_by('-date_joined') | ||
27 | - serializer_class = UserSerializer | ||
28 | - permission_classes = [permissions.IsAuthenticated] | ||
29 | - | ||
30 | - | ||
31 | -class ItemViewSet(viewsets.ViewSet): | ||
32 | - | ||
33 | - queryset = Item.objects.all() | ||
34 | - serializer_class = ItemSerializer | ||
35 | - permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny, | ||
36 | - #IsOwnerOrReadOnly | ||
37 | - ] | ||
38 | - permission_classes_by_action = {'get': [permissions.AllowAny], | ||
39 | - 'destroy': [permissions.AllowAny]} | ||
40 | - | ||
41 | - # url: items/search | ||
42 | - @action(methods=['GET'], detail=False, permission_classes=[AllowAny], url_path='search', url_name='search') | ||
43 | - def search(self, request): | ||
44 | - if request.method == 'GET': | ||
45 | - keyword = request.GET.get('keyword', '') | ||
46 | - item_list = Item.objects.filter(name__icontains = keyword) | ||
47 | - | ||
48 | - data = serializers.serialize("json", item_list) | ||
49 | - json_data = json.loads(data) | ||
50 | - res = [] | ||
51 | - for i in json_data: | ||
52 | - t = i['fields'] | ||
53 | - t['id'] = i['pk'] | ||
54 | - res.append(t) | ||
55 | - return Response({'data': {'list' : res}}, status=status.HTTP_200_OK) | ||
56 | - | ||
57 | - # url: items/11/ | ||
58 | - # 마지막 slash도 써주어야함 | ||
59 | - def get(self, request, pk): | ||
60 | - item = Item.objects.filter(item_id=pk) | ||
61 | - data = serializers.serialize("json", item) | ||
62 | - json_data = json.loads(data) | ||
63 | - res = json_data[0]['fields'] | ||
64 | - res['id']=json_data[0]['pk'] | ||
65 | - return Response({'data': res}, status=status.HTTP_200_OK) | ||
66 | - | ||
67 | - # url: items/11/ | ||
68 | - # 마지막 slash도 써주어야함 | ||
69 | - def destroy(self, request, pk): | ||
70 | - if request.method == 'DELETE': | ||
71 | - print(pk) | ||
72 | - item = get_object_or_None(Item, item_id=pk) | ||
73 | - if item != None: | ||
74 | - if item.is_folder == True: # 폴더는 삭제 안되도록 처리 | ||
75 | - return Response({'message': 'This item is folder.'}, status=status.HTTP_200_OK) | ||
76 | - item.is_deleted = True | ||
77 | - item.save() | ||
78 | - # item.delete() 이거 하면 완전 삭제되어버림 is deleted True 면 휴지통에서 리스트 조회할 수 있도록! | ||
79 | - return Response({'message': 'delete complete'},status=status.HTTP_200_OK) | ||
80 | - return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) | ||
81 | - | ||
82 | - # url: items/11/move | ||
83 | - # 마지막 slash도 써주어야함 | ||
84 | - @action(methods=['POST'], detail=True, permission_classes=[AllowAny], url_path='move', url_name='move') | ||
85 | - def move(self, request, pk): | ||
86 | - if request.method == 'POST': | ||
87 | - parent_id = request.POST.get('parent', '') | ||
88 | - name = request.POST.get('name','') | ||
89 | - parent = get_object_or_None(Item, item_id=parent_id) | ||
90 | - if parent != None and parent.is_folder == True: | ||
91 | - child = get_object_or_None(Item, item_id=pk) | ||
92 | - if child == None: | ||
93 | - return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) | ||
94 | - child.parent = parent_id | ||
95 | - child.save() | ||
96 | - child = Item.objects.filter(item_id = pk) | ||
97 | - child_data = serializers.serialize("json", child) | ||
98 | - json_child = json.loads(child_data) | ||
99 | - res = json_child[0]['fields'] | ||
100 | - res['id'] = pk | ||
101 | - parent = Item.objects.filter(item_id = parent_id) | ||
102 | - parent_data = serializers.serialize("json", parent) | ||
103 | - json_parent = json.loads(parent_data)[0]['fields'] | ||
104 | - res['parentInfo'] = json_parent | ||
105 | - return Response({'data': res}, status=status.HTTP_200_OK) | ||
106 | - if parent == None: | ||
107 | - return Response({'message': 'parent is not existed.'}, status=status.HTTP_200_OK) | ||
108 | - if parent.is_folder == False: | ||
109 | - return Response({'message': 'parent is not folder.'}, status=status.HTTP_200_OK) | ||
110 | - return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) | ||
111 | - | ||
112 | - @action(methods=['POST'], detail=True, permission_classes=[AllowAny], url_path='copy', url_name='copy') | ||
113 | - def copy(self, request, pk): | ||
114 | - if request.method == 'POST': | ||
115 | - parent_id = request.POST.get('parent', '') | ||
116 | - parent = get_object_or_None(Item, item_id=parent_id) | ||
117 | - if parent != None and parent.is_folder == True: | ||
118 | - child = get_object_or_None(Item, item_id=pk) | ||
119 | - if child == None: | ||
120 | - return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) | ||
121 | - if child.is_folder == True: | ||
122 | - return Response({'message': 'item is folder'}, status=status.HTTP_204_NO_CONTENT) | ||
123 | - copiedName = child.name + "_복사본_" + str(datetime.now().strftime('%Y-%m-%d %H:%M')) | ||
124 | - copiedItem = Item(is_folder = False, name = copiedName, path =child.path, parent = parent_id, user_id= child.user_id, size=child.size, status=child.status) | ||
125 | - copiedItem.save() | ||
126 | - | ||
127 | - copiedItem = Item.objects.filter(name = copiedName) | ||
128 | - copied_data = serializers.serialize("json", copiedItem) | ||
129 | - json_data = json.loads(copied_data) | ||
130 | - res = json_data[0]['fields'] | ||
131 | - res['id'] = json_data[0]['pk'] | ||
132 | - parent = Item.objects.filter(item_id = parent_id) | ||
133 | - parent_data = serializers.serialize("json", parent) | ||
134 | - json_parent = json.loads(parent_data)[0]['fields'] | ||
135 | - res['parentInfo'] = json_parent | ||
136 | - return Response({'data': res}, status=status.HTTP_200_OK) | ||
137 | - if parent == None: | ||
138 | - return Response({'message': 'parent is not existed.'}, status=status.HTTP_200_OK) | ||
139 | - if parent.is_folder == False: | ||
140 | - return Response({'message': 'parent is not folder.'}, status=status.HTTP_200_OK) | ||
141 | - return Response({'message': 'item is not existed.'}, status=status.HTTP_204_NO_CONTENT) | ||
142 | - | ||
143 | - def get_permissions(self): | ||
144 | - try: | ||
145 | - # return permission_classes depending on `action` | ||
146 | - return [permission() for permission in self.permission_classes_by_action[self.action]] | ||
147 | - except KeyError: | ||
148 | - # action is not set return default permission_classes | ||
149 | - return [permission() for permission in self.permission_classes] | ||
150 | - | ||
151 | - | ||
152 | -class SharedItemViewSet(viewsets.ModelViewSet): | ||
153 | - | ||
154 | - queryset = SharedItem.objects.all() | ||
155 | - # serializer_class = SharedItemSerializer | ||
156 | - permission_classes = [permissions.IsAuthenticatedOrReadOnly, permissions.AllowAny, | ||
157 | - # IsOwnerOrReadOnly | ||
158 | - ] | ||
159 | - # url: http://localhost:8000/items/1/share/ | ||
160 | - # 마지막 slash도 써주어야함 | ||
161 | - @csrf_exempt | ||
162 | - @action(methods=['POST'], detail=True, permission_classes=[AllowAny], url_path='share', url_name='share') | ||
163 | - def share(self, request, pk): | ||
164 | - if request.method == 'POST': | ||
165 | - password = request.POST.get('password', '') | ||
166 | - expires = request.POST.get('expires', '') | ||
167 | - | ||
168 | - sharedfile = get_object_or_None(SharedItem, item_id=pk) | ||
169 | - if sharedfile != None: | ||
170 | - # 서버는 정상이나 이미 공유객체로 등록된 파일임 | ||
171 | - return Response({'message': 'This file is already shared'}, status=status.HTTP_200_OK) | ||
172 | - sharedfile = SharedItem(item_id =pk, password=password, expires = expires) | ||
173 | - sharedfile.save() | ||
174 | - sharedfile = SharedItem.objects.get(item_id = pk) | ||
175 | - | ||
176 | - # sf = serializers.serialize("json", sharedfile) | ||
177 | - item = Item.objects.filter(item_id = pk) | ||
178 | - item_json = serializers.serialize("json", item) | ||
179 | - | ||
180 | - json_data = json.loads(item_json) | ||
181 | - print(json_data) | ||
182 | - res = json_data[0]['fields'] | ||
183 | - res['id'] = json_data[0]['pk'] | ||
184 | - return Response({"shared": sharedfile.created_time , 'data': res}, status=status.HTTP_200_OK) | ||
185 | - | ||
186 | -item = ItemViewSet.as_view({ | ||
187 | - 'delete': 'destroy', | ||
188 | -}) | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
1 | +from api.models import User | ||
2 | +from rest_framework import viewsets | ||
3 | +from rest_framework import permissions | ||
4 | +from rest_framework.permissions import IsAuthenticated | ||
5 | +from rest_framework_jwt.authentication import JSONWebTokenAuthentication | ||
6 | +from rest_framework.decorators import action, permission_classes | ||
7 | +from rest_framework import status | ||
8 | +from api.serializers import UserSerializer, SignUpSerializer | ||
9 | +from rest_framework.response import Response | ||
10 | +from django.http import HttpResponse, JsonResponse | ||
11 | +import jwt | ||
12 | +import json | ||
13 | +from datetime import datetime, timedelta | ||
14 | +from .utils import login_decorator | ||
15 | +from django.conf import settings | ||
16 | +from django.views.decorators.csrf import csrf_exempt | ||
17 | + | ||
18 | + | ||
19 | +class UserViewSet(viewsets.ModelViewSet): | ||
20 | + """ | ||
21 | + API endpoint that allows users to be viewed or edited. | ||
22 | + """ | ||
23 | + queryset = User.objects.all().order_by('-id') | ||
24 | + serializer_class = UserSerializer | ||
25 | + permission_classes = [permissions.IsAuthenticated] | ||
26 | + | ||
27 | + @csrf_exempt | ||
28 | + @action(detail=False, methods=['POST'], permission_classes=[permissions.AllowAny], url_path='signUp', url_name='singUp') | ||
29 | + def signUp(self, request): | ||
30 | + serializer = SignUpSerializer(data=request.data) | ||
31 | + if serializer.is_valid(): | ||
32 | + user = serializer.create(data=request.data) | ||
33 | + return Response({ | ||
34 | + 'message': 'user created', | ||
35 | + 'id': user.id, | ||
36 | + 'user_id': user.user_id, | ||
37 | + 'name': user.name, | ||
38 | + 'total_size': user.total_size, | ||
39 | + 'current_size': user.current_size, | ||
40 | + }, | ||
41 | + status=status.HTTP_200_OK, | ||
42 | + ) | ||
43 | + else: | ||
44 | + return Response(serializer.errors, | ||
45 | + status=status.HTTP_400_BAD_REQUEST) | ||
46 | + | ||
47 | + @csrf_exempt | ||
48 | + @action(methods=['post'], detail=False, permission_classes=[permissions.AllowAny], | ||
49 | + url_path='login', url_name='login') | ||
50 | + def login(self, request): | ||
51 | + if not request.data: | ||
52 | + return Response({'Error': "Please provide user_id/password"}, status=status.HTTP_400_BAD_REQUEST) | ||
53 | + | ||
54 | + user_id = request.POST['user_id'] | ||
55 | + password = request.POST['password'] | ||
56 | + try: | ||
57 | + user = User.objects.get(user_id=user_id, password=password) | ||
58 | + except User.DoesNotExist: | ||
59 | + return Response({'Error': "Invalid user_id/password"}, status=status.HTTP_400_BAD_REQUEST) | ||
60 | + if user: | ||
61 | + payload1 = { | ||
62 | + 'id': user.id, | ||
63 | + 'user_id': user.user_id, | ||
64 | + 'exp': datetime.utcnow() + timedelta(seconds=300) | ||
65 | + } | ||
66 | + payload2 = { | ||
67 | + 'id': user.id, | ||
68 | + 'user_id': user.user_id, | ||
69 | + 'exp': datetime.utcnow() + timedelta(days=5) | ||
70 | + } | ||
71 | + access = jwt.encode(payload1, settings.SECRET_KEY, algorithm='HS256').decode('utf-8') | ||
72 | + refresh = jwt.encode(payload2, settings.SECRET_KEY, algorithm='HS256').decode('utf-8') | ||
73 | + exp = jwt.decode(access, settings.SECRET_KEY, algorithm='HS256')['exp'] | ||
74 | + token = {'access': access, | ||
75 | + 'refresh': refresh, | ||
76 | + 'exp': exp} | ||
77 | + return JsonResponse( | ||
78 | + token, | ||
79 | + status=status.HTTP_200_OK, | ||
80 | + ) | ||
81 | + else: | ||
82 | + return JsonResponse( | ||
83 | + {'Error': "Invalid credentials"}, | ||
84 | + status=status.HTTP_400_BAD_REQUEST, | ||
85 | + ) | ||
86 | + return JsonResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED) | ||
87 | + | ||
88 | + @csrf_exempt | ||
89 | + @login_decorator | ||
90 | + @action(methods=['POST'], detail=False, permission_classes=[permissions.IsAuthenticated], | ||
91 | + url_path='renew', url_name='renew') | ||
92 | + def renew(self, request): | ||
93 | + user = request.user | ||
94 | + payload1 = { | ||
95 | + 'id': user.id, | ||
96 | + 'user_id': user.user_id, | ||
97 | + 'exp': datetime.utcnow() + timedelta(seconds=300) | ||
98 | + } | ||
99 | + payload2 = { | ||
100 | + 'id': user.id, | ||
101 | + 'user_id': user.user_id, | ||
102 | + 'exp': datetime.utcnow() + timedelta(days=5) | ||
103 | + } | ||
104 | + access = jwt.encode(payload1, settings.SECRET_KEY, algorithm='HS256').decode('utf-8') | ||
105 | + refresh = jwt.encode(payload2, settings.SECRET_KEY, algorithm='HS256').decode('utf-8') | ||
106 | + exp = jwt.decode(access, settings.SECRET_KEY, algorithm='HS256')['exp'] | ||
107 | + token = {'access': access, | ||
108 | + 'refresh': refresh, | ||
109 | + 'exp': exp} | ||
110 | + return JsonResponse( | ||
111 | + token, | ||
112 | + status=status.HTTP_200_OK, | ||
113 | + ) | ||
114 | + | ||
115 | + @login_decorator | ||
116 | + @action(methods=['GET'], detail=True, permission_classes=[permissions.IsAuthenticated], | ||
117 | + url_path='info', url_name='info') | ||
118 | + def info(self, request, pk): | ||
119 | + if request.method == 'GET': | ||
120 | + user = User.objects.get(id=pk) | ||
121 | + data = { | ||
122 | + 'id': user.id, | ||
123 | + 'user_id': user.user_id, | ||
124 | + 'name': user.name, | ||
125 | + 'total_size': user.total_size, | ||
126 | + 'current_size': user.current_size | ||
127 | + } | ||
128 | + return HttpResponse( | ||
129 | + data, | ||
130 | + status=status.HTTP_200_OK, | ||
131 | + content_type="application/json") | ||
132 | + return HttpResponse( | ||
133 | + {'Error': 'The Method is not allowed.'}, | ||
134 | + status=status.HTTP_405_METHOD_NOT_ALLOWED, | ||
135 | + content_type="application/json") | ||
136 | + | ||
137 | + | ||
138 | + | ||
139 | + | ||
140 | + | ||
141 | + | ... | ... |
-
Please register or login to post a comment