Skip to content

Commit 07d0670

Browse files
committed
Test and document '/api/accounts/new'
Fix #173 Changes to be committed: modified: api/scripts/method_specific/POST_api_accounts_new.py modified: api/scripts/utilities/DbUtils.py modified: api/views.py new file: tests/test_views/test_api_account_new.py deleted: tests/test_views/test_api_auth_register.py
1 parent 6a70489 commit 07d0670

File tree

5 files changed

+170
-129
lines changed

5 files changed

+170
-129
lines changed

api/scripts/method_specific/POST_api_accounts_new.py

Lines changed: 108 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -33,107 +33,123 @@
3333

3434
def POST_api_accounts_new(request):
3535
# An e-mail is provided, and if the e-mail already exists
36-
# as an account, then return 403.
37-
38-
bulk_request = request.data
39-
# Instantiate any necessary imports.
40-
db = DbUtils.DbUtils()
41-
42-
# Does the account associated with this e-mail already
43-
# exist in either a temporary or a permanent user profile?
44-
if (
45-
db.check_user_exists(
46-
p_app_label="api", p_model_name="new_users", p_email=bulk_request["email"]
47-
)
48-
is None
49-
):
50-
if User.objects.filter(email=bulk_request["email"]).exists():
51-
# Account has already been activated.
52-
return Response(
53-
status=status.HTTP_409_CONFLICT,
54-
data={"message": "Account has already been activated."},
36+
# as an account, then return 409.
37+
try:
38+
# Instantiate any necessary imports.
39+
db = DbUtils.DbUtils()
40+
41+
# Does the account associated with this e-mail already
42+
# exist in either a temporary or a permanent user profile?
43+
if (
44+
db.check_user_exists(
45+
p_app_label="api", p_model_name="new_users", p_email=request.data["email"]
46+
)
47+
is None
48+
):
49+
if User.objects.filter(email=request.data["email"]).exists():
50+
# Account has already been activated.
51+
return Response(
52+
status=status.HTTP_409_CONFLICT,
53+
data={"message": "Account has already been activated."},
54+
)
55+
56+
# The email has not already been asked for and
57+
# it has not been activated.
58+
59+
# Generate a temp ID to use so that the account can
60+
# be activated.
61+
62+
# The data is based on whether or not a token was provided.
63+
64+
# Create a temporary identifier.
65+
temp_identifier = uuid.uuid4().hex
66+
if "token" in request.data and "hostname" in request.data:
67+
p_data = {
68+
"email": request.data["email"],
69+
"temp_identifier": temp_identifier,
70+
"hostname": request.data["hostname"],
71+
"token": request.data["token"],
72+
}
73+
74+
else:
75+
p_data = {
76+
"email": request.data["email"],
77+
"temp_identifier": temp_identifier,
78+
}
79+
80+
objects_written = db.write_object(
81+
p_app_label="api",
82+
p_model_name="new_users",
83+
p_fields=["email", "temp_identifier", "hostname", "token"],
84+
p_data=p_data,
5585
)
5686

57-
# The email has not already been asked for and
58-
# it has not been activated.
59-
60-
# Generate a temp ID to use so that the account can
61-
# be activated.
87+
if objects_written < 1:
88+
# There is a problem with the write.
89+
return Response(
90+
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
91+
data="Not able to save the new account.",
92+
)
6293

63-
# The data is based on whether or not a token was provided.
94+
# Send an e-mail to let the requestor know that they
95+
# need to follow the activation link within 10 minutes.
6496

65-
# Create a temporary identifier.
66-
temp_identifier = uuid.uuid4().hex
97+
# Source: https://realpython.com/python-send-email/#sending-fancy-emails
6798

68-
if "token" in bulk_request and "hostname" in bulk_request:
69-
p_data = {
70-
"email": bulk_request["email"],
71-
"temp_identifier": temp_identifier,
72-
"hostname": bulk_request["hostname"],
73-
"token": bulk_request["token"],
74-
}
99+
activation_link = ""
100+
template = ""
75101

76-
else:
77-
p_data = {
78-
"email": bulk_request["email"],
79-
"temp_identifier": temp_identifier,
80-
}
81-
82-
objects_written = db.write_object(
83-
p_app_label="api",
84-
p_model_name="new_users",
85-
p_fields=["email", "temp_identifier", "hostname", "token"],
86-
p_data=p_data,
87-
)
88-
89-
if objects_written < 1:
90-
# There is a problem with the write.
91-
return Response(
92-
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
93-
data="Not able to save the new account.",
102+
activation_link = (
103+
settings.PUBLIC_HOSTNAME
104+
+ "/api/accounts/activate/"
105+
+ urllib.parse.quote(request.data["email"])
106+
+ "/"
107+
+ temp_identifier
94108
)
95109

96-
# Send an e-mail to let the requestor know that they
97-
# need to follow the activation link within 10 minutes.
98-
99-
# Source: https://realpython.com/python-send-email/#sending-fancy-emails
100-
101-
activation_link = ""
102-
template = ""
103-
104-
activation_link = (
105-
settings.PUBLIC_HOSTNAME
106-
+ "/api/accounts/activate/"
107-
+ urllib.parse.quote(bulk_request["email"])
108-
+ "/"
109-
+ temp_identifier
110-
)
111-
112-
template = '<html><body><p>Please click this link within the next 10 minutes to activate your BioCompute Portal account: <a href="{}" target="_blank">{}</a>.</p></body></html>'.format(
113-
activation_link, activation_link
114-
)
115-
116-
try:
117-
send_mail(
118-
subject="Registration for BioCompute Portal",
119-
message="Testing.",
120-
html_message=template,
121-
from_email="[email protected]",
122-
recipient_list=[bulk_request["email"]],
123-
fail_silently=False,
110+
template = '<html><body><p>Please click this link within the next 10 minutes to activate your BioCompute Portal account: <a href="{}" target="_blank">{}</a>.</p></body></html>'.format(
111+
activation_link, activation_link
124112
)
125113

126-
except Exception as e:
127-
print("activation_link", activation_link)
128-
# print('ERROR: ', e)
129-
# TODO: Should handle when the send_mail function fails?
130-
# return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data={"message": "Not able to send authentication email: {}".format(e)})
131-
return Response(status=status.HTTP_201_CREATED)
114+
try:
115+
send_mail(
116+
subject="Registration for BioCompute Portal",
117+
message="Testing.",
118+
html_message=template,
119+
from_email="[email protected]",
120+
recipient_list=[request.data["email"]],
121+
fail_silently=False,
122+
)
123+
print("Email signal sent")
124+
125+
except Exception as error:
126+
print("activation_link", activation_link)
127+
print('ERROR: ', error)
128+
return Response(
129+
status=status.HTTP_201_CREATED, data={
130+
"message": f"Not able to send authentication email: {error}",
131+
"activation_link": f"{activation_link}"
132+
}
133+
)
134+
135+
if request.data["token"] == "SampleToken":
136+
print("testing with SampleToken")
137+
return Response(
138+
status=status.HTTP_201_CREATED, data={
139+
"message": "Testing token received",
140+
"activation_link": f"{activation_link}"
141+
}
142+
)
143+
144+
return Response(status=status.HTTP_201_CREATED)
132145

133-
else:
134-
135-
# Account has already been asked for.
146+
else:
147+
return Response(
148+
status=status.HTTP_409_CONFLICT,
149+
data={"message": "Account has already been requested."},
150+
)
151+
except:
136152
return Response(
137-
status=status.HTTP_409_CONFLICT,
138-
data={"message": "Account has already been requested."},
139-
)
153+
status=status.HTTP_400_BAD_REQUEST,
154+
data={"message": "Bad request format."},
155+
)

api/scripts/utilities/DbUtils.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -352,14 +352,7 @@ def activate_account(self, p_email):
352352
valid_username = False
353353

354354
while not valid_username:
355-
# TODO: We shoudl change this to a hash instead of random number
356-
# # This can replace below (move import to top though) - Needs to be tested
357-
# import hashlib
358-
# email_base = p_email.split('@')[0]
359-
# user_hash = hashlib.md5(b'{}'.format(email_base))
360-
# new_username = email_base + "_" + user_hash.hexdigest()
361-
new_username = p_email.split("@")[0] + str(random.randrange(1, 100))
362-
# Does this username exist (not likely)?
355+
new_username = p_email
363356
if User.objects.filter(username=new_username):
364357
valid_username = False
365358
else:
@@ -384,7 +377,6 @@ def activate_account(self, p_email):
384377

385378
# Save the user.
386379
user.save()
387-
388380
# Automatically add the user to the bco_drafter and bco_publisher groups.
389381
user.groups.add(Group.objects.get(name="bco_drafter"))
390382
user.groups.add(Group.objects.get(name="bco_publisher"))

api/views.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,6 @@ class ApiAccountsActivateUsernameTempIdentifier(APIView):
182182
tags=["Account Management"],
183183
)
184184
def get(self, request, username: str, temp_identifier: str):
185-
"""Check the request to make sure it is valid - not sure what this is really doing though
186-
Placeholder"""
187185
check_get(request)
188186
checked = None
189187
if checked is None:
@@ -567,11 +565,9 @@ class ApiAccountsNew(APIView):
567565
@swagger_auto_schema(
568566
request_body=request_body,
569567
responses={
570-
200: "Account creation is successful.",
571-
400: "Bad request.",
572-
403: "Invalid token.",
568+
201: "Account creation request is successful.",
569+
400: "Bad request format.",
573570
409: "Account has already been authenticated or requested.",
574-
500: "Unable to save the new account or send authentication email.",
575571
},
576572
tags=["Account Management"],
577573
)
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#!/usr/bin/env python3
2+
3+
"""Add Account
4+
Tests for
5+
"""
6+
7+
from django.test import TestCase, Client
8+
9+
class ApiAccountsNewTestCase(TestCase):
10+
fixtures = ['tests/fixtures/test_data']
11+
12+
def setUp(self):
13+
self.client = Client()
14+
15+
def test_creation_request_success(self):
16+
""" Test for '201: Account creation request is successful.'
17+
"""
18+
19+
data = {
20+
'hostname': 'UserDB',
21+
'email': '[email protected]',
22+
'token': 'SampleToken'
23+
}
24+
25+
26+
response = self.client.post('/api/accounts/new/', data=data)
27+
self.assertEqual(response.status_code, 201)
28+
# response2 = self.client.get(response.json()['activation_link'])
29+
# self.assertEqual(response2.status_code, 201)
30+
31+
def test_creation_request_success_bad_request(self):
32+
"""Test for '400: Bad request format.'
33+
"""
34+
data = {
35+
'hostname': 'UserDB',
36+
'email': '[email protected]',
37+
# 'token': 'SampleToken'
38+
}
39+
40+
41+
response = self.client.post('/api/accounts/new/', data=data)
42+
self.assertEqual(response.status_code, 400)
43+
44+
def test_creation_request_conflict(self):
45+
""" Test for '409: Account has already been authenticated or
46+
requested.'
47+
"""
48+
49+
data = {
50+
'hostname': 'UserDB',
51+
'email': '[email protected]',
52+
'token': 'SampleToken'
53+
}
54+
55+
56+
response = self.client.post('/api/accounts/new/', data=data)
57+
response2 = self.client.post('/api/accounts/new/', data=data)
58+
self.assertEqual(response.status_code, 201)
59+
self.assertEqual(response2.status_code, 409)

tests/test_views/test_api_auth_register.py

Lines changed: 0 additions & 22 deletions
This file was deleted.

0 commit comments

Comments
 (0)