views.py
5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
from api.models import User
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.decorators import action, permission_classes
from rest_framework import status
from api.serializers import UserSerializer, SignUpSerializer
from rest_framework.response import Response
from django.http import HttpResponse, JsonResponse
import jwt
import json
from datetime import datetime, timedelta
from .utils import login_decorator
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-int_id')
serializer_class = UserSerializer
permission_classes = [permissions.IsAuthenticated]
@csrf_exempt
@action(detail=False, methods=['POST'], permission_classes=[permissions.AllowAny], url_path='signup', url_name='singup')
def signup(self, request):
serializer = SignUpSerializer(data=request.data)
if serializer.is_valid():
user = serializer.create(data=request.data)
return Response({
'message': 'user created',
'int_id': user.int_id,
'user_id': user.user_id,
'name': user.name,
'total_size': user.total_size,
'current_size': user.current_size,
'created_time': user.created_time
},
status=status.HTTP_200_OK,
)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
@csrf_exempt
@action(methods=['post'], detail=False, permission_classes=[permissions.AllowAny],
url_path='login', url_name='login')
def login(self, request):
if not request.data:
return Response({'Error': "Please provide user_id/password"}, status=status.HTTP_400_BAD_REQUEST)
user_id = request.POST['user_id']
password = request.POST['password']
try:
user = User.objects.get(user_id=user_id, password=password)
except User.DoesNotExist:
return Response({'Error': "Invalid user_id/password"}, status=status.HTTP_400_BAD_REQUEST)
if user:
payload1 = {
'int_id': user.int_id,
'user_id': user.user_id,
'exp': datetime.utcnow() + timedelta(seconds=300)
}
payload2 = {
'int_id': user.int_id,
'user_id': user.user_id,
'exp': datetime.utcnow() + timedelta(days=5)
}
access = jwt.encode(payload1, settings.SECRET_KEY, algorithm='HS256').decode('utf-8')
refresh = jwt.encode(payload2, settings.SECRET_KEY, algorithm='HS256').decode('utf-8')
exp = jwt.decode(access, settings.SECRET_KEY, algorithm='HS256')['exp']
token = {'access': access,
'refresh': refresh,
'exp': exp}
return JsonResponse(
token,
status=status.HTTP_200_OK,
)
else:
return JsonResponse(
{'Error': "Invalid credentials"},
status=status.HTTP_400_BAD_REQUEST,
)
return JsonResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED)
@csrf_exempt
@login_decorator
@action(methods=['POST'], detail=False, permission_classes=[permissions.IsAuthenticated],
url_path='renew', url_name='renew')
def renew(self, request):
user = request.user
payload1 = {
'int_id': user.int_id,
'user_id': user.user_id,
'exp': datetime.utcnow() + timedelta(seconds=300)
}
payload2 = {
'int_id': user.int_id,
'user_id': user.user_id,
'exp': datetime.utcnow() + timedelta(days=5)
}
access = jwt.encode(payload1, settings.SECRET_KEY, algorithm='HS256').decode('utf-8')
refresh = jwt.encode(payload2, settings.SECRET_KEY, algorithm='HS256').decode('utf-8')
exp = jwt.decode(access, settings.SECRET_KEY, algorithm='HS256')['exp']
token = {'access': access,
'refresh': refresh,
'exp': exp}
return JsonResponse(
token,
status=status.HTTP_200_OK,
)
@login_decorator
@action(methods=['GET'], detail=True, permission_classes=[permissions.IsAuthenticated],
url_path='info', url_name='info')
def info(self, request, pk):
if request.method == 'GET':
user = User.objects.get(id=pk)
data = {
'int_id': user.int_id,
'user_id': user.user_id,
'name': user.name,
'total_size': user.total_size,
'current_size': user.current_size
'created_time': user.created_time
}
return HttpResponse(
data,
status=status.HTTP_200_OK,
content_type="application/json")
return HttpResponse(
{'Error': 'The Method is not allowed.'},
status=status.HTTP_405_METHOD_NOT_ALLOWED,
content_type="application/json")