This repository was archived by the owner on Oct 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathuser.py
465 lines (394 loc) · 16 KB
/
user.py
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import re
import cognito
from cognito_groups import get_group_by_name
import config
from logger import LOG
# This class represents a user and performs
# the necessary validations with cognito
class User:
def __init__(self, email_address):
self.email_address = (
email_address.strip().lower().encode("latin1").decode("utf-8")
)
self.details = {}
self.cognito_client = cognito.get_boto3_client()
def name(self):
return self.get_details().get("name", "")
def phone_number(self):
return self.get_details().get("phone_number", "")
def phone_number_verified(self):
return self.get_details().get("phone_number_verified", "")
def __custom_paths_str(self):
return self.get_details().get("custom:paths", "")
def custom_paths(self):
return self.__custom_paths_str().split(";") if self.__custom_paths_str() else []
def created_at(self):
return self.get_details().get("createdate", "")
def modified_at(self):
return self.get_details().get("lastmodifieddate", "")
def enabled(self):
return self.get_details().get("enabled", "")
def status(self):
return self.get_details().get("status", "")
def group_name(self):
return self.get_details().get("group", {}).get("value", "")
def __is_la_str(self):
return self.get_details().get("custom:is_la", "0")
def is_la(self):
return True if self.__is_la_str() == "1" else False
"""
Create and set properties of cognito user
Create user in cognito user pool
If successful then:
- Set MFA preference to SMS
- Set MFA SMS phone number
- Add user to the requested cognito group
"""
def create(self, name, phone_number, custom_paths, is_la, group_name):
"""
Create a new user in Cognito user pool
Validate the inputs.
A user is only valid if their MFA and group settings
are correct.
Return True only if all steps are processed successfully.
"""
error = None
steps = {}
# Validate email
if not self.email_address_is_valid():
steps["email_valid"] = False
error = "Email address is invalid."
# Validate phone number
phone_number = self.sanitise_phone(phone_number)
if phone_number == "":
steps["phone_valid"] = False
error = "Phone number is empty."
# Validate user custom settings
if not self.user_paths_are_valid(is_la, custom_paths, group_name):
steps["paths_valid"] = False
error = "The granted access permissions are not valid."
# Only attempt create if all previous steps passed
if all(steps.values()):
steps["created"] = cognito.create_user(
name, self.email_address, phone_number, is_la, custom_paths
)
if steps.get("created"):
steps["set_mfa"] = self.set_mfa_preferences()
steps["set_settings"] = self.set_user_settings()
steps["added_to_group"] = self.add_to_group(group_name)
else:
error = "Failed to create user."
if steps.get("created") and not all(steps.values()):
# If the user was created successfully
# but the group or SMS 2FA operations fail
# the user should be disabled.
if steps.get("created"):
cognito.disable_user(self.email_address)
if error:
config.set_session_var("error_message", error)
LOG.error(
{
"message": "User operation failed",
"action": "user.create",
"status": steps,
}
)
# Return True only if all settings were successfully set
return all(steps.values())
def set_mfa_preferences(self):
is_set = cognito.set_mfa_preferences(self.email_address)
if not is_set:
config.set_session_var("error_message", "Failed to set MFA preferences.")
return is_set
def set_user_settings(self):
is_set = cognito.set_user_settings(self.email_address)
if not is_set:
config.set_session_var(
"error_message", "Failed to set preferred MFA to mobile."
)
return is_set
def add_to_group(self, group_name=None):
is_set = cognito.add_to_group(self.email_address, group_name)
if not is_set:
config.set_session_var(
"error_message", f"Failed to add user to {group_name} group."
)
return is_set
def set_group(self, new_group_name):
if new_group_name is None:
return
if not isinstance(new_group_name, str):
raise ValueError("ERR: %s: new_group_name is not str")
current_group_name = self.details["group"]["value"]
if current_group_name != new_group_name:
removed = cognito.remove_from_group(self.email_address, current_group_name)
if removed:
self.add_to_group(new_group_name)
def sanitise_phone(self, phone_number):
if phone_number != "":
phone_number = re.sub(r"[^0-9]", "", phone_number)
if phone_number.startswith("0"):
phone_number = "+44" + phone_number[1:]
if phone_number.startswith("44"):
phone_number = "+44" + phone_number[2:]
return phone_number
return ""
def sanitise_name(self, name):
# remove invalid characters
name = re.sub(r"[^a-zA-Z0-9-_\']", " ", name)
# remove multiple spaces
name = re.sub(r"\s+", " ", name)
# remove leading / trailing spaces
name = name.strip()
return name
def update(self, name, phone_number, custom_paths, is_la, group):
"""
Validate the input fields and existing user settings.
Perform update only if all validation steps pass.
Return True only if all steps pass.
"""
error = None
steps = {}
# Check user exists
steps["user_found"] = self.get_details() != {}
if not steps.get("user_found"):
error = "Failed to get user details to update."
# Check input parameters are all set
steps["inputs_valid"] = all(
[
name is not None,
phone_number is not None,
custom_paths is not None,
is_la is not None,
group is not None,
]
)
if not steps.get("inputs_valid"):
error = "The new value for a field is missing or blank."
# Check the earlier steps have passed
if all(steps.values()):
user_attributes = []
try:
user_attributes += self.__attribute("custom:is_la", is_la)
user_attributes += self.__attribute("name", self.sanitise_name(name))
user_attributes += self.__custom_path_attribute(
is_la, custom_paths, group
)
user_attributes += self.__phone_number_attribute(phone_number)
self.set_group(group)
except ValueError:
error = "The current value for a field is missing or blank."
steps["current_valid"] = False
# If all tests have passed try the update
if all(steps.values()):
steps["updated"] = cognito.update_user(self.email_address, user_attributes)
if not steps.get("updated"):
error = "The fields were valid but the user failed to update."
if error:
config.set_session_var("error_message", error)
LOG.error(
{
"message": "User operation failed",
"action": "user.update",
"status": steps,
}
)
# Return True if valid and updated
return all(steps.values())
def __attribute(self, field_name, value):
if value is None:
return []
if isinstance(value, str):
return [{"Name": field_name, "Value": value}]
else:
raise ValueError(f"{value}: is not expected value for field: {field_name}")
def __custom_path_attribute(self, is_la, custom_paths, group_name):
if custom_paths is None:
return []
if isinstance(custom_paths, str):
group_name = (
group_name if group_name is not None else self.details["group"]["value"]
)
if not self.user_paths_are_valid(is_la, custom_paths, group_name):
raise ValueError("custom paths: is not expected value")
return [{"Name": "custom:paths", "Value": custom_paths}]
else:
raise ValueError("custom paths: is not expected value")
def user_paths_are_valid(self, is_la, paths_semicolon_separated, group_name):
all_user_paths_are_valid = True
# All non-admin users should have a non-empty path in custom:paths
if "admin" not in group_name and paths_semicolon_separated == "":
LOG.error(
{
"user": self.email_address,
"group": group_name,
"message": "Path is missing for non-admin user",
}
)
all_user_paths_are_valid = False
app_authorised_paths = [config.get("bucket_main_prefix", "web-app-prod-data")]
user_authorised_paths = paths_semicolon_separated.split(";")
# Local Authority users: is_la = 1
# can only be granted access to [main_prefix]/local_authority/* paths
# Non Local Authority users: is_la = 0
# can only be granted access to [main_prefix]/other/* paths
for authorised_path in app_authorised_paths:
for path in user_authorised_paths:
la_path = "{}/local_authority/".format(authorised_path)
user_is_local_authority = is_la == "1"
path_is_local_authority = path.startswith(la_path)
if user_is_local_authority != path_is_local_authority:
LOG.error(
{
"user": self.email_address,
"group": group_name,
"path": path,
"is_la": is_la,
"message": "Path is invalid for user type",
}
)
all_user_paths_are_valid = False
return all_user_paths_are_valid
def __phone_number_attribute(self, phone_number):
sanitised_phone = self.sanitise_phone(phone_number)
phone_attribute = self.__attribute("phone_number", sanitised_phone)
if sanitised_phone == self.details["phone_number"]:
return phone_attribute
else:
return phone_attribute + [
{"Name": "phone_number_verified", "Value": "false"}
]
def delete(self):
if not self.email_address_is_valid():
LOG.error(
"ERR: %s: the email %s is not valid", "user-admin", self.email_address
)
return False
return cognito.delete_user(self.email_address)
def disable(self):
if not self.email_address_is_valid():
LOG.error(
"ERR: %s: the email %s is not valid", "user-admin", self.email_address
)
return False
return cognito.disable_user(self.email_address)
def enable(self):
if not self.email_address_is_valid():
LOG.error(
"ERR: %s: the email %s is not valid", "user-admin", self.email_address
)
return False
return cognito.enable_user(self.email_address)
def reinvite(self):
details = self.get_details()
if details != {}:
LOG.debug(details)
deleted = self.delete()
LOG.debug({"action": "delete", "status": deleted})
if deleted:
created = self.create(
self.name(),
self.phone_number(),
self.__custom_paths_str(),
self.__is_la_str(),
self.group_name(),
)
LOG.debug({"action": "create", "status": created})
return created
return False
def get_details(self):
if self.details == {}:
aws_details = cognito.get_user(self.email_address)
self.details = User.normalise(aws_details)
return self.details
def email_address_is_valid(self):
return "@" in self.email_address and self.domain_is_allowed()
def domain_is_allowed(self):
for domain in self.allowed_domains():
if self.email_address.endswith(domain):
return True
return False
def allowed_domains(self):
return [
".gov.uk", # allow any *.gov.uk email
"@brake.co.uk", # allow @brake.co.uk (wholesaler)
"@nhs.net",
"@tesco.com",
"@ocadoretail.com",
"@morrisonsplc.co.uk",
"@sainsburys.co.uk",
"@iceland.co.uk",
"@coop.co.uk",
"@asda.co.uk",
"@johnlewis.co.uk",
"@capita.com",
"@coreconsultants.io",
]
@staticmethod
def list(email_starts_filter="", token="", limit=20):
arguments = {
"AttributesToGet": [
"name",
"email",
"email_verified",
"phone_number",
"phone_number_verified",
"cognito:user_status",
"custom:paths",
"custom:is_la",
],
"Limit": limit,
}
if email_starts_filter != "":
arguments["Filter"] = 'email ^= "{}"'.format(email_starts_filter)
if token != "":
arguments["PaginationToken"] = token
cognito_client = cognito.get_boto3_client()
response = cognito_client.list_users(**arguments)
token = ""
users = []
if "Users" in response:
for aws_user_details in response["Users"]:
user = User.normalise(aws_user_details)
if user != {}:
users.append(user)
if "PaginationToken" in response:
token = response["PaginationToken"]
# Edge case where users could be blank but there is
# a token for getting more users
if not any(response["Users"]) and not token:
return list(
email_starts_filter=email_starts_filter, limit=limit, token=token
)
return {"users": users, "token": token}
@staticmethod
def normalise(aws_details):
result = {}
if "Username" in aws_details:
result = {
"username": aws_details["Username"],
"status": aws_details["UserStatus"],
"createdate": aws_details["UserCreateDate"],
"lastmodifieddate": aws_details["UserLastModifiedDate"],
"enabled": aws_details["Enabled"],
}
for attr in aws_details[
"Attributes" if "Attributes" in aws_details else "UserAttributes"
]:
result[attr["Name"]] = attr["Value"]
if "username" in result:
result["group"] = User.group(result["username"])
return result
@staticmethod
def group(username):
response = cognito.list_groups_for_user(username)
groups = []
if "Groups" in response:
for group in response["Groups"]:
if "GroupName" in group:
groups.append(group["GroupName"])
# Currently you can attach a list of users in cognito
# but we're currently only interested in the first group
group_name = None if len(groups) == 0 else groups[0]
LOG.debug("User group returns: %s", group_name)
return get_group_by_name(group_name)