Skip to content
This repository was archived by the owner on Apr 17, 2023. It is now read-only.

Commit 41c00a5

Browse files
committed
Separate api_info out of user_update
Changes to be committed: new file: core/migrations/.DS_Store modified: core/urls.py modified: core/views.py modified: portalusers/settings.py modified: portalusers/urls.py
1 parent 408858f commit 41c00a5

File tree

5 files changed

+126
-103
lines changed

5 files changed

+126
-103
lines changed

core/migrations/.DS_Store

6 KB
Binary file not shown.

core/urls.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
from django.urls import path
2-
from .views import current_user, add_api, remove_api, UserList, update_user, index
2+
from .views import current_user, add_api, remove_api, CreateUser, update_user
33
# For favicon and any other static files
44
from django.contrib.staticfiles.storage import staticfiles_storage
55
from django.views.generic.base import RedirectView
6+
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token
67

78
urlpatterns = [
89
path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('img/favicon.ico'))),
910
path('users/current_user/', current_user),
1011
path('users/add_api/', add_api),
1112
path('users/remove_api/', remove_api),
12-
path('users/list/', UserList.as_view()),
13+
path('users/list/', CreateUser.as_view()),
1314
path('users/update_user/', update_user),
14-
path('users/', index, name='index')
15+
path('users/token-auth/', obtain_jwt_token),
16+
path('users/token-refresh/', refresh_jwt_token),
17+
path('users/token-verify/', verify_jwt_token)
1518
]

core/views.py

Lines changed: 118 additions & 94 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,104 @@
1-
from django.http import HttpResponseRedirect, HttpResponse
2-
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
3-
from django.contrib.auth.models import User
4-
from .models import ApiInfo, Profile
1+
import json
2+
from drf_yasg import openapi
3+
from drf_yasg.utils import swagger_auto_schema
54
from rest_framework import permissions, status
65
from rest_framework.decorators import api_view
76
from rest_framework.response import Response
87
from rest_framework.views import APIView
8+
from django.http import HttpResponseRedirect, HttpResponse
9+
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
10+
from django.contrib.auth.models import User
11+
from .models import ApiInfo, Profile
912
from .serializers import ApiSerializer, UserSerializer, UserSerializerWithToken
1013

1114
from django.db.models.signals import post_save
1215
from django.dispatch import receiver
1316

14-
# POST body parsing.
15-
import json
17+
class CreateUser(APIView):
18+
"""
19+
Create a new user
20+
21+
Create a new user
22+
"""
1623

24+
permission_classes = (permissions.AllowAny,)
25+
request_body = openapi.Schema(
26+
type=openapi.TYPE_OBJECT,
27+
title="Account Creation Schema",
28+
description="Account creation schema description.",
29+
required=['username', 'email', 'password'],
30+
properties={
31+
'username': openapi.Schema(type=openapi.TYPE_STRING,
32+
description='Hostname of the User Database.'),
33+
'email' : openapi.Schema(type=openapi.TYPE_STRING,
34+
description='Email address of user.'),
35+
'password': openapi.Schema(type=openapi.TYPE_STRING,
36+
description='Token returned with new user being '),
37+
'profile' : openapi.Schema(
38+
type=openapi.TYPE_OBJECT,
39+
description='Token returned with new user being ',
40+
required=['username'],
41+
properties={
42+
'username': openapi.Schema(type=openapi.TYPE_STRING,
43+
description='Username for the profile user object. Should be the same as above.'),
44+
'public' : openapi.Schema(type=openapi.TYPE_BOOLEAN,
45+
description='Boolean to indicate if this users profile is publicly viewable.'),
46+
'affiliation': openapi.Schema(type=openapi.TYPE_STRING,
47+
description='Affiliation of the User.'),
48+
'orcid': openapi.Schema(type=openapi.TYPE_STRING,
49+
description='ORCID for the User.')
50+
} ),
51+
})
52+
53+
@swagger_auto_schema(request_body=request_body, responses={
54+
200: "Account creation is successful.",
55+
400: "Bad request.",
56+
403: "Invalid token.",
57+
409: "Account has already been authenticated or requested.",
58+
500: "Unable to save the new account or send authentication email."
59+
}, tags=["Account Management"])
60+
61+
def post(self, request, format=None):
62+
63+
print('request.data: ')
64+
print(request.data)
65+
print('===============')
1766

18-
def index(request):
19-
return HttpResponse("Hello, world. You're at the polls index.")
67+
# Does this user already exist?
68+
if User.objects.filter(username = request.data['username']).exists():
2069

70+
# Bad request because the user already exists.
71+
return Response(status=status.HTTP_409_CONFLICT)
72+
73+
else:
74+
profile_object = request.data['profile']
75+
del request.data['profile']
76+
serializer = UserSerializerWithToken(data=request.data)
77+
78+
if serializer.is_valid():
79+
serializer.save()
2180

81+
user_object = User.objects.get(username=request.data['username'])
82+
Profile.objects.create(
83+
username=user_object,
84+
public=profile_object['public'],
85+
affiliation=profile_object['affiliation'],
86+
orcid=profile_object['orcid'])
87+
88+
return Response(serializer.data, status=status.HTTP_201_CREATED)
89+
90+
else:
91+
92+
# The request didn't provide what we needed.
93+
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
94+
95+
@swagger_auto_schema(method="get", tags=["Account Management"])
2296
@api_view(['GET'])
2397
def current_user(request):
2498
"""
2599
Determine the current user by their token, and return their data
26100
"""
101+
27102
print('HERE')
28103
serializer = UserSerializer(request.user)
29104

@@ -33,45 +108,8 @@ def current_user(request):
33108

34109
return Response(serializer.data)
35110

36-
37-
@api_view(['POST'])
38-
def add_api(request):
39-
"""
40-
Update a user's information based on their token.
41-
"""
42-
43-
# Get the user.
44-
print('U check')
45-
print(UserSerializer(request.user).data)
46-
user = UserSerializer(request.user).data['username']
47-
48-
# TODO: right way to do this?
49-
# Get the user ID so that we can link across tables.
50-
user_object = User.objects.get(username = user)
51-
52-
# Get the bulk information.
53-
bulk = json.loads(request.body)
54-
55-
# Add the key for the user.
56-
updated = ApiInfo(
57-
local_username = user_object,
58-
username = bulk['username'],
59-
hostname = bulk['hostname'],
60-
human_readable_hostname = bulk['human_readable_hostname'],
61-
public_hostname = bulk['public_hostname'],
62-
token = bulk['token'],
63-
other_info = bulk['other_info']
64-
)
65-
updated.save()
66-
67-
print('========')
68-
print(user)
69-
print(updated)
70-
print('=========')
71-
return(Response(UserSerializer(request.user).data, status=status.HTTP_201_CREATED))
72-
73-
74-
@api_view(['POST', 'DELETE'])
111+
@swagger_auto_schema(method="delete", tags=["API Management"])
112+
@api_view(['DELETE'])
75113
def remove_api(request):
76114
"""
77115
Remove API information
@@ -107,50 +145,46 @@ def remove_api(request):
107145
print('=========')
108146
return (Response(UserSerializer(request.user).data, status=status.HTTP_200_OK))
109147

110-
111-
class UserList(APIView):
148+
@swagger_auto_schema(method="post", tags=["API Management"])
149+
@api_view(['POST'])
150+
def add_api(request):
112151
"""
113-
Create a new user. It's called 'UserList' because normally we'd have a get
114-
method here too, for retrieving a list of all User objects.
152+
Update a user's information based on their token.
115153
"""
154+
155+
# Get the user.
156+
print('U check')
157+
print(UserSerializer(request.user).data)
158+
user = UserSerializer(request.user).data['username']
116159

117-
permission_classes = (permissions.AllowAny,)
118-
119-
def post(self, request, format=None):
120-
121-
print('request.data: ')
122-
print(request.data)
123-
print('===============')
124-
125-
# Does this user already exist?
126-
if User.objects.filter(username = request.data['username']).exists():
160+
# TODO: right way to do this?
161+
# Get the user ID so that we can link across tables.
162+
user_object = User.objects.get(username = user)
127163

128-
# Bad request because the user already exists.
129-
return Response(status=status.HTTP_409_CONFLICT)
130-
131-
else:
132-
profile_object = request.data['profile']
133-
del request.data['profile']
134-
serializer = UserSerializerWithToken(data=request.data)
135-
136-
if serializer.is_valid():
137-
serializer.save()
164+
# Get the bulk information.
165+
bulk = json.loads(request.body)
138166

139-
user_object = User.objects.get(username=request.data['username'])
140-
Profile.objects.create(
141-
username=user_object,
142-
public=profile_object['public'],
143-
affiliation=profile_object['affiliation'],
144-
orcid=profile_object['orcid'])
145-
146-
return Response(serializer.data, status=status.HTTP_201_CREATED)
147-
148-
else:
167+
# Add the key for the user.
168+
api_object = ApiInfo(
169+
local_username = user_object,
170+
username = bulk['username'],
171+
hostname = bulk['hostname'],
172+
human_readable_hostname = bulk['human_readable_hostname'],
173+
public_hostname = bulk['public_hostname'],
174+
token = bulk['token'],
175+
other_info = bulk['other_info']
176+
)
177+
178+
api_object.save()
149179

150-
# The request didn't provide what we needed.
151-
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
180+
print('========')
181+
print(user)
182+
print(api_object)
183+
print('=========')
184+
return(Response(UserSerializer(request.user).data, status=status.HTTP_201_CREATED))
152185

153186

187+
@swagger_auto_schema(method="post", tags=["Account Management"])
154188
@api_view(['POST'])
155189
def update_user(request):
156190
"""
@@ -163,9 +197,6 @@ def update_user(request):
163197
# Get the user with associated username
164198
user_object = User.objects.get(username=user)
165199

166-
# Get ApiInfo associated with user
167-
api_object = ApiInfo.objects.get(local_username=user_object)
168-
169200
try:
170201
profile_object = Profile.objects.get(username=user_object)
171202
except:
@@ -184,16 +215,9 @@ def update_user(request):
184215
setattr(user_object, key, value)
185216
elif (key == 'orcid') or (key == 'affiliation') or (key == 'public'):
186217
setattr(profile_object, key, value)
187-
else:
188-
old_info = api_object.other_info
189-
old_info[key] = value
190-
191-
setattr(api_object, 'other_info', old_info)
192218

193219
user_object.save()
194220

195-
api_object.save()
196-
197221
profile_object.save()
198222

199223
# properly formatted response
@@ -210,4 +234,4 @@ def update_user(request):
210234

211235
# So, write to the table, then change the token.
212236
# We could have gone with a temporary token here, but
213-
# that may be too much too worry about.
237+
# that may be too much too worry about.

portalusers/settings.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,8 @@
172172
JWT_AUTH = {
173173
'JWT_RESPONSE_PAYLOAD_HANDLER': 'portalusers.utils.my_jwt_response_handler',
174174
'JWT_EXPIRATION_DELTA': timedelta(seconds=604800),
175-
'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=7),
175+
'JWT_REFRESH_EXPIRATION_DELTA': timedelta(days=14),
176+
'JWT_ALLOW_REFRESH': True,
176177
}
177178

178179
# LOGGING

portalusers/urls.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@
1616
from django.contrib import admin
1717
from django.urls import path, include, re_path
1818

19-
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token
20-
2119
# drf_yasg code starts here
2220
# https://www.jasonmars.org/2020/04/22/add-swagger-to-django-rest-api-quickly-4-mins-without-hiccups/
2321

@@ -46,8 +44,5 @@
4644
path('users/redoc/', schema_view.with_ui('redoc', cache_timeout=0),
4745
name='schema-redoc'), # Here
4846
path('users/admin/', admin.site.urls),
49-
path('users/token-auth/', obtain_jwt_token),
50-
path('users/token-refresh/', refresh_jwt_token),
51-
path('users/token-verify/', verify_jwt_token),
5247
path('', include('core.urls'))
5348
]

0 commit comments

Comments
 (0)