dahee kim

feat: :sparkles: add token authentication in all api

1 +# Generated by Django 3.1.2 on 2020-11-22 14:39
2 +
3 +from django.db import migrations, models
4 +import django.utils.timezone
5 +
6 +
7 +class Migration(migrations.Migration):
8 +
9 + initial = True
10 +
11 + dependencies = [
12 + ]
13 +
14 + operations = [
15 + migrations.CreateModel(
16 + name='AddDevice',
17 + fields=[
18 + ('id', models.IntegerField(primary_key=True, serialize=False)),
19 + ('state', models.BooleanField(default=False)),
20 + ],
21 + ),
22 + migrations.CreateModel(
23 + name='Device',
24 + fields=[
25 + ('device_id', models.AutoField(primary_key=True, serialize=False)),
26 + ('rfid_id', models.CharField(max_length=255)),
27 + ('created', models.DateTimeField(default=django.utils.timezone.now)),
28 + ],
29 + ),
30 + migrations.CreateModel(
31 + name='Door',
32 + fields=[
33 + ('door_id', models.CharField(max_length=255, primary_key=True, serialize=False)),
34 + ],
35 + ),
36 + migrations.CreateModel(
37 + name='Lock',
38 + fields=[
39 + ('id', models.IntegerField(primary_key=True, serialize=False)),
40 + ('state', models.BooleanField(default=True)),
41 + ],
42 + ),
43 + migrations.CreateModel(
44 + name='Record',
45 + fields=[
46 + ('id', models.IntegerField(primary_key=True, serialize=False)),
47 + ('recording', models.BooleanField(default=True)),
48 + ],
49 + ),
50 + migrations.CreateModel(
51 + name='RemoteHistory',
52 + fields=[
53 + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
54 + ('device_name', models.CharField(max_length=255)),
55 + ('created', models.DateTimeField(default=django.utils.timezone.now)),
56 + ],
57 + ),
58 + migrations.CreateModel(
59 + name='Video',
60 + fields=[
61 + ('vid_name', models.CharField(max_length=255, primary_key=True, serialize=False)),
62 + ('created', models.DateTimeField(default=django.utils.timezone.now)),
63 + ('vid_time', models.CharField(max_length=255)),
64 + ('thumb', models.CharField(max_length=255)),
65 + ],
66 + ),
67 + ]
...@@ -3,7 +3,7 @@ import botocore ...@@ -3,7 +3,7 @@ import botocore
3 import threading 3 import threading
4 from django.http import HttpResponse 4 from django.http import HttpResponse
5 from django.core import serializers 5 from django.core import serializers
6 -from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist 6 +from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist, PermissionDenied
7 from django.shortcuts import render 7 from django.shortcuts import render
8 from django.contrib.auth.models import User 8 from django.contrib.auth.models import User
9 9
...@@ -15,6 +15,7 @@ from rest_framework.views import APIView ...@@ -15,6 +15,7 @@ from rest_framework.views import APIView
15 from rest_framework.request import Request 15 from rest_framework.request import Request
16 from rest_framework.response import Response 16 from rest_framework.response import Response
17 from rest_framework.authtoken.models import Token 17 from rest_framework.authtoken.models import Token
18 +from rest_framework.authentication import TokenAuthentication
18 19
19 from boto3.session import Session 20 from boto3.session import Session
20 from src.settings import AWS_REGION 21 from src.settings import AWS_REGION
...@@ -61,29 +62,44 @@ class Login(APIView) : ...@@ -61,29 +62,44 @@ class Login(APIView) :
61 62
62 63
63 64
64 -''' 65 +
65 def post(self, request, format = None) : 66 def post(self, request, format = None) :
66 queryset = Door.objects.create(door_id = 12345) 67 queryset = Door.objects.create(door_id = 12345)
67 return Response({ 68 return Response({
68 'msg' : 'doorid값 삽입 완료', 69 'msg' : 'doorid값 삽입 완료',
69 }) 70 })
70 -''' 71 +
71 72
72 73
73 #기기 관련 api 74 #기기 관련 api
74 class Devices(APIView) : 75 class Devices(APIView) :
75 # 기기 목록 조회 76 # 기기 목록 조회
76 - def get(self, request, format = None) : 77 + def get(self, request, format = None) :
77 - queryset = Device.objects.all() 78 + try :
78 - serializer = DeviceSerializer(queryset, many = True) 79 + if request.auth == None :
79 - res = { 80 + raise PermissionDenied
80 - 'deviceList': serializer.data 81 + queryset = Device.objects.all()
81 - } 82 + serializer = DeviceSerializer(queryset, many = True)
82 - return Response(res, status = status.HTTP_200_OK) 83 + res = {
84 + 'deviceList': serializer.data
85 + }
86 + return Response(res, status = status.HTTP_200_OK)
87 + except FieldDoesNotExist as error :
88 + return Response({
89 + 'error' : "FieldDoesNotExist ",
90 + 'date' : datetime.now()
91 + }, status = status.HTTP_400_BAD_REQUEST)
92 + except PermissionDenied as error :
93 + return Response({
94 + 'error' : "PermissionDenied",
95 + 'date' : datetime.now()
96 + }, status = status.HTTP_400_BAD_REQUEST)
83 97
84 # 기기 추가 요청 98 # 기기 추가 요청
85 def put(self, request, format = None) : 99 def put(self, request, format = None) :
86 try : 100 try :
101 + if request.auth == None :
102 + raise PermissionDenied
87 print(request.body) 103 print(request.body)
88 data = json.loads(request.body) 104 data = json.loads(request.body)
89 target = AddDevice.objects.get(id=1) 105 target = AddDevice.objects.get(id=1)
...@@ -105,10 +121,17 @@ class Devices(APIView) : ...@@ -105,10 +121,17 @@ class Devices(APIView) :
105 'error' : "FieldDoesNotExist ", 121 'error' : "FieldDoesNotExist ",
106 'date' : datetime.now() 122 'date' : datetime.now()
107 }, status = status.HTTP_400_BAD_REQUEST) 123 }, status = status.HTTP_400_BAD_REQUEST)
124 + except PermissionDenied as error :
125 + return Response({
126 + 'error' : "PermissionDenied",
127 + 'date' : datetime.now()
128 + }, status = status.HTTP_400_BAD_REQUEST)
108 129
109 # 기기 추가 130 # 기기 추가
110 def post(self, request, format = None) : # request body에 rfid_id 포함되어있음  131 def post(self, request, format = None) : # request body에 rfid_id 포함되어있음 
111 try : 132 try :
133 + if request.auth == None :
134 + raise PermissionDenied
112 print(request.data) 135 print(request.data)
113 data = {x: request.POST.get(x) for x in request.POST.keys()} 136 data = {x: request.POST.get(x) for x in request.POST.keys()}
114 request_id = data.get('rfid_id', None) 137 request_id = data.get('rfid_id', None)
...@@ -125,12 +148,19 @@ class Devices(APIView) : ...@@ -125,12 +148,19 @@ class Devices(APIView) :
125 'error' : "FieldDoesNotExist ", 148 'error' : "FieldDoesNotExist ",
126 'date' : datetime.now() 149 'date' : datetime.now()
127 }, status = status.HTTP_400_BAD_REQUEST) 150 }, status = status.HTTP_400_BAD_REQUEST)
151 + except PermissionDenied as error :
152 + return Response({
153 + 'error' : "PermissionDenied",
154 + 'date' : datetime.now()
155 + }, status = status.HTTP_400_BAD_REQUEST)
128 156
129 157
130 158
131 # 기기 삭제 159 # 기기 삭제
132 def delete(self, request, device_id, format = None): # request URI에 device_id(자동생성되는 기기 고유 번호 != rfid_id) 포함 160 def delete(self, request, device_id, format = None): # request URI에 device_id(자동생성되는 기기 고유 번호 != rfid_id) 포함
133 - try : 161 + try :
162 + if request.auth == None :
163 + raise PermissionDenied
134 request_id = device_id 164 request_id = device_id
135 if request_id == None: 165 if request_id == None:
136 raise FieldDoesNotExist 166 raise FieldDoesNotExist
...@@ -145,22 +175,37 @@ class Devices(APIView) : ...@@ -145,22 +175,37 @@ class Devices(APIView) :
145 'error' : "FieldDoesNotExist ", 175 'error' : "FieldDoesNotExist ",
146 'date' : datetime.now() 176 'date' : datetime.now()
147 }, status = status.HTTP_400_BAD_REQUEST) 177 }, status = status.HTTP_400_BAD_REQUEST)
178 + except PermissionDenied as error :
179 + return Response({
180 + 'error' : "PermissionDenied",
181 + 'date' : datetime.now()
182 + }, status = status.HTTP_400_BAD_REQUEST)
148 183
149 # 원격 잠금 해제 184 # 원격 잠금 해제
150 class Remote(APIView): 185 class Remote(APIView):
151 # 원격 잠금 해제 기록 조회 186 # 원격 잠금 해제 기록 조회
152 def get(self, request, format = None) : 187 def get(self, request, format = None) :
153 #models.py의 class History 사용. 188 #models.py의 class History 사용.
154 - queryset = RemoteHistory.objects.all() 189 + try:
155 - serializer = RemoteHistorySerializer(queryset, many = True) 190 + if request.auth == None :
156 - res = { 191 + raise PermissionDenied
157 - "remoteHistoryList": serializer.data 192 + queryset = RemoteHistory.objects.all()
158 - } 193 + serializer = RemoteHistorySerializer(queryset, many = True)
159 - return Response(res, status = status.HTTP_200_OK) 194 + res = {
195 + "remoteHistoryList": serializer.data
196 + }
197 + return Response(res, status = status.HTTP_200_OK)
198 + except PermissionDenied as error :
199 + return Response({
200 + 'error' : "FieldDoesNotExist ",
201 + 'date' : datetime.now()
202 + }, status = status.HTTP_400_BAD_REQUEST)
160 203
161 # 원격 잠금 해제 204 # 원격 잠금 해제
162 def put(self, request, format = None) : 205 def put(self, request, format = None) :
163 try: 206 try:
207 + if request.auth == None :
208 + raise PermissionDenied
164 print(request.body) 209 print(request.body)
165 data = json.loads(request.body) 210 data = json.loads(request.body)
166 device_name = data.get('device_name', None) 211 device_name = data.get('device_name', None)
...@@ -182,27 +227,48 @@ class Remote(APIView): ...@@ -182,27 +227,48 @@ class Remote(APIView):
182 return Response({ 227 return Response({
183 'msg' : 'success remote unlock' 228 'msg' : 'success remote unlock'
184 }, status = status.HTTP_200_OK) 229 }, status = status.HTTP_200_OK)
230 +
185 except FieldDoesNotExist as error: 231 except FieldDoesNotExist as error:
186 return Response({ 232 return Response({
187 'error': "FieldDoesNotExist ", 233 'error': "FieldDoesNotExist ",
188 'date': datetime.now() 234 'date': datetime.now()
189 }, status=status.HTTP_400_BAD_REQUEST) 235 }, status=status.HTTP_400_BAD_REQUEST)
236 + except PermissionDenied as error :
237 + return Response({
238 + 'error' : "PermissionDenied",
239 + 'date' : datetime.now()
240 + }, status = status.HTTP_400_BAD_REQUEST)
190 241
191 242
192 243
193 # 비디오 목록 조회 244 # 비디오 목록 조회
194 class VideoList(APIView) : 245 class VideoList(APIView) :
195 def get(self, request, format = None) : 246 def get(self, request, format = None) :
196 - queryset = Video.objects.all() 247 + try :
197 - serializer = VideoSerializer(queryset, many = True) 248 + if request.auth == None :
198 - res = { 249 + raise PermissionDenied
199 - 'videoList': serializer.data 250 + queryset = Video.objects.all()
200 - } # 응답코드에 포함될 데이터 251 + serializer = VideoSerializer(queryset, many = True)
201 - return Response(res, status = status.HTTP_200_OK) 252 + res = {
253 + 'videoList': serializer.data
254 + } # 응답코드에 포함될 데이터
255 + return Response(res, status = status.HTTP_200_OK)
256 + except FieldDoesNotExist as error:
257 + return Response({
258 + 'error': "FieldDoesNotExist ",
259 + 'date': datetime.now()
260 + }, status=status.HTTP_400_BAD_REQUEST)
261 + except PermissionDenied as error :
262 + return Response({
263 + 'error' : "PermissionDenied",
264 + 'date' : datetime.now()
265 + }, status = status.HTTP_400_BAD_REQUEST)
202 266
203 # 비디오 수동 삭제 267 # 비디오 수동 삭제
204 def delete(self, request, vid_name, format = None) : # request URI에 vid_name가 포함되어있음 : api/video/{vid_name} 268 def delete(self, request, vid_name, format = None) : # request URI에 vid_name가 포함되어있음 : api/video/{vid_name}
205 try : 269 try :
270 + if request.auth == None :
271 + raise PermissionDenied
206 request_id = vid_name 272 request_id = vid_name
207 if request_id == 'None' : 273 if request_id == 'None' :
208 raise FieldDoesNotExist 274 raise FieldDoesNotExist
...@@ -219,11 +285,18 @@ class VideoList(APIView) : ...@@ -219,11 +285,18 @@ class VideoList(APIView) :
219 'error' : "FieldDoesNotExist ", 285 'error' : "FieldDoesNotExist ",
220 'date' : datetime.now() 286 'date' : datetime.now()
221 }, status = status.HTTP_400_BAD_REQUEST) 287 }, status = status.HTTP_400_BAD_REQUEST)
288 + except PermissionDenied as error :
289 + return Response({
290 + 'error' : "PermissionDenied",
291 + 'date' : datetime.now()
292 + }, status = status.HTTP_400_BAD_REQUEST)
222 293
223 # 비디오 확인(다운로드) 294 # 비디오 확인(다운로드)
224 class VideoDownload(APIView) : 295 class VideoDownload(APIView) :
225 def get(self, request, vid_name, format = None) : # 요청한 URI에 vid_name가 포함되어있음 296 def get(self, request, vid_name, format = None) : # 요청한 URI에 vid_name가 포함되어있음
226 - try : 297 + try :
298 + if request.auth == None :
299 + raise PermissionDenied
227 request_id = vid_name 300 request_id = vid_name
228 if request_id == 'None' : 301 if request_id == 'None' :
229 raise FieldDoesNotExist 302 raise FieldDoesNotExist
...@@ -244,6 +317,11 @@ class VideoDownload(APIView) : ...@@ -244,6 +317,11 @@ class VideoDownload(APIView) :
244 'error' : "ObjectDoesNotExist", 317 'error' : "ObjectDoesNotExist",
245 'date' : datetime.now() 318 'date' : datetime.now()
246 }, status = status.HTTP_404_NOT_FOUND) 319 }, status = status.HTTP_404_NOT_FOUND)
320 + except PermissionDenied as error :
321 + return Response({
322 + 'error' : "PermissionDenied",
323 + 'date' : datetime.now()
324 + }, status = status.HTTP_400_BAD_REQUEST)
247 325
248 # 비디오 자동 삭제 326 # 비디오 자동 삭제
249 class CheckDate(APIView) : 327 class CheckDate(APIView) :
...@@ -261,24 +339,28 @@ class CheckDate(APIView) : ...@@ -261,24 +339,28 @@ class CheckDate(APIView) :
261 class Recording(APIView) : 339 class Recording(APIView) :
262 def get(self, request, format = None) : 340 def get(self, request, format = None) :
263 try : 341 try :
342 + if request.auth == None :
343 + raise PermissionDenied
264 target = Record.objects.get(id = 1) 344 target = Record.objects.get(id = 1)
265 serializer = RecordSerializer(target, many = False) 345 serializer = RecordSerializer(target, many = False)
266 res = { 346 res = {
267 'recording' : serializer.data['recording'] 347 'recording' : serializer.data['recording']
268 } 348 }
269 return Response(res, status = status.HTTP_200_OK) 349 return Response(res, status = status.HTTP_200_OK)
270 - except FieldDoesNotExist as error : 350 + except PermissionDenied as error :
271 return Response({ 351 return Response({
272 - 'error' : "FieldDoesNotExist ", 352 + 'error' : "PermissionDenied",
273 'date' : datetime.now() 353 'date' : datetime.now()
274 - }, status = status.HTTP_400_BAD_REQUEST) 354 + }, status = status.HTTP_400_BAD_REQUEST)
275 355
276 def put(self, request, format = None) : 356 def put(self, request, format = None) :
277 - try : 357 + try :
358 + if request.auth == None :
359 + raise PermissionDenied
278 target = Record.objects.filter(id = 1) 360 target = Record.objects.filter(id = 1)
279 target.update(recording = request.data['recording']) 361 target.update(recording = request.data['recording'])
280 return Response(status = status.HTTP_200_OK) 362 return Response(status = status.HTTP_200_OK)
281 - except FieldDoesNotExist as error : 363 + except PermissionDenied as error :
282 return Response({ 364 return Response({
283 'error' : "FieldDoesNotExist ", 365 'error' : "FieldDoesNotExist ",
284 'date' : datetime.now() 366 'date' : datetime.now()
......
...@@ -44,6 +44,12 @@ INSTALLED_APPS = [ ...@@ -44,6 +44,12 @@ INSTALLED_APPS = [
44 'rest_framework.authtoken', 44 'rest_framework.authtoken',
45 ] 45 ]
46 46
47 +REST_FRAMEWORK = {
48 + 'DEFAULT_AUTHENTICATION_CLASSES' : [
49 + 'rest_framework.authentication.TokenAuthentication',
50 + ]
51 +}
52 +
47 MIDDLEWARE = [ 53 MIDDLEWARE = [
48 'django.middleware.security.SecurityMiddleware', 54 'django.middleware.security.SecurityMiddleware',
49 'django.contrib.sessions.middleware.SessionMiddleware', 55 'django.contrib.sessions.middleware.SessionMiddleware',
......