-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.py
653 lines (511 loc) · 21.4 KB
/
handler.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
import json
import os
import boto3
import decimal
import requests
import datetime
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError
dynamodb = boto3.resource('dynamodb')
calendar_table_name = os.environ['DYNAMODB_CALENDAR']
#=========================================#
#======= Helper Functions ========#
#=========================================#
def create_response(status_code: int, message):
"""Returns a given status code."""
return {
'statusCode': status_code,
'headers': {
# Required for CORS support to work
'Access-Control-Allow-Origin': '*',
# Required for cookies, authorization headers with HTTPS
'Access-Control-Allow-Credentials': 'true',
},
'body': message
}
class DecimalEncoder(json.JSONEncoder):
"""Helper class to convert a DynamoDB item to JSON."""
def default(self, o):
if isinstance(o, set):
return list(o)
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
def get_utc_iso_time():
"""Returns formatted UTC datetime string of current time."""
return datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
def getEvent(eventId, eventStart):
"""Returns details of a requested event from the calendar database."""
print(f'eventId: {eventId}')
print(f'eventStart: {eventStart}')
table = dynamodb.Table(calendar_table_name)
try:
response = table.get_item(
Key={
'event_id': eventId,
'start': eventStart,
}
)
print(f"getEvent response: {response}")
return response['Item']
except Exception as e:
print(f"error with getEvent")
print(e)
return ''
def getEventsDuringTime(time, site):
"""Gets calendar events at a site that are active during a given time.
Args:
time (str): UTC datestring (eg. '2022-05-14T17:30:00Z').
site (str): sitecode (eg. 'saf').
Returns:
A list of event objects matching time and site criteria.
"""
table = dynamodb.Table(calendar_table_name)
response = table.query(
IndexName="site-end-index",
KeyConditionExpression=
Key('site').eq(site)
& Key('end').gte(time),
FilterExpression=Key('start').lte(time)
)
print(f"Items during {time}: {response['Items']}")
return response['Items']
def getProject(project_name, created_at):
"""Get project details from the projects backend.
Args:
project_name (str):
Name of the project in the projects-{stage} database.
created_at (str):
UTC datestring at creation (eg. '2022-05-14T17:30:00Z').
Returns:
Requested project details JSON, if response code 200.
"""
# Use the same projects deployment as the one running the calendar.
# E.g. The dev calendar backend will call the dev projects backend
stage = os.getenv('STAGE')
# The production projects url replaces 'prod' with 'projects' in the url
if stage == 'prod':
stage = 'projects'
url = f"https://projects.photonranch.org/{stage}/get-project"
body = json.dumps({
"project_name": project_name,
"created_at": created_at,
})
response = requests.post(url, body)
if response.status_code == 200:
return response.json()
else:
return "Project not found."
def remove_expired_scheduler_events(cutoff_time, site):
""" Method for deleting calendar events created in response to the LCO scheduler.
This method takes a site and a cutoff time, and deletes all events that satisfy the following conditions:
- the event belongs to the given site
- the event starts after the cutoff_time (specifically, the event start is greater than the cutoff_time)
- the event origin is 'lco'
It returns an array of project IDs that were associated with the deleted events so that they can be deleted as well.
Args:
cutoff_time (str):
Formatted yyyy-MM-ddTHH:mmZ (UTC, 24-hour format)
Any events that start before this time are not deleted.
site (str):
Only delete events from the given site (e.g. 'mrc')
Returns:
(array of str) project IDs for any projects that were connected to deleted events.
"""
table = dynamodb.Table(calendar_table_name)
index_name = "site-end-index"
# Query items from the secondary index with 'site' as the partition key and 'end' greater than the specified end_date
# We're using 'end' time for the query because it's part of a pre-existing GSI that allows for efficient queries.
# But ultimately we want this to apply to events that start after the cutoff, so add that as a filter condition too.
query = table.query(
IndexName=index_name,
KeyConditionExpression=Key('site').eq(site) & Key('end').gt(cutoff_time),
FilterExpression=Attr('origin').eq('lco') & Attr('start').gt(cutoff_time)
)
items = query.get('Items', [])
# Extract key attributes for deletion (use the primary key attributes, not the index keys)
key_names = [k['AttributeName'] for k in table.key_schema]
with table.batch_writer() as batch:
for item in items:
batch.delete_item(Key={k: item[k] for k in key_names if k in item})
# Handle pagination if results exceed 1MB
while 'LastEvaluatedKey' in query:
query = table.query(
IndexName=index_name,
KeyConditionExpression=Key('site').eq(site) & Key('end').gt(cutoff_time),
FilterExpression=Attr('origin').eq('lco') & Attr('start').gt(cutoff_time),
ExclusiveStartKey=query['LastEvaluatedKey']
)
items = query.get('Items', [])
with table.batch_writer() as batch:
for item in items:
batch.delete_item(Key={k: item[k] for k in key_names if k in item})
associated_projects = [x["project_id"] for x in items]
return associated_projects
#=========================================#
#======= API Endpoints ========#
#=========================================#
def addNewEvent(event, context):
"""Endpoint to add a new event (reservation) to the calendar.
Args:
event.body.event_id (str):
Unique id generated for each new event (eg. '999xx09b-xxxx-...').
event.body.start (str):
UTC datestring of starting time (eg. '2022-05-14T17:30:00Z').
event.body.site (str):
sitecode (eg. 'saf').
Returns:
200 status code with new calendar event if successful.
400 status code if missing required keys or otherwise unsuccessful.
"""
try:
event_body = json.loads(event.get("body", ""))
table = dynamodb.Table(calendar_table_name)
print("event_body:")
print(event_body)
# Check that all required keys are present.
required_keys = ['event_id', 'start', 'site']
actual_keys = event_body.keys()
for key in required_keys:
if key not in actual_keys:
msg = f"Error: missing required key {key}"
print(msg)
return create_response(400, msg)
# Add creation date
event_body["last_modified"] = get_utc_iso_time()
table_response = table.put_item(Item=event_body)
message = json.dumps({
'table_response': table_response,
'new_calendar_event': event_body,
})
return create_response(200, message)
# Something else went wrong, return a Bad Request status code.
except Exception as e:
print(f"Exception: {e}")
return create_response(400, json.dumps(e))
def modifyEvent(event, context):
"""Endpoint to update an existing calendar events with changes.
A user may only modify their own events in the calendar,
unless they are an admin.
Args:
event.body.event_id (str):
Unique id generated for each new event (eg. '999xx09b-xxxx-...').
event.body.start (str):
UTC datestring of starting time (eg. '2022-05-14T17:30:00Z').
context.requestContext.authorizer.principalID (str):
Auth0 user 'sub' token (eg. 'google-oauth2|xxxxxxxxxxxxx').
context.requestContext.authorizer.userRoles (str):
Global user account type (eg. 'admin').
Returns:
200 status code with modified project body if successful.
403 status code if user is unauthorized.
"""
table = dynamodb.Table(calendar_table_name)
event_body = json.loads(event.get("body", ""))
originalEvent = event_body['originalEvent']
modifiedEvent = event_body['modifiedEvent']
originalId = originalEvent['event_id']
originalStart = originalEvent['start']
# Make sure the user is admin, or modifying their own event
creatorId = getEvent(originalId, originalStart)['creator_id']
userMakingThisRequest = event["requestContext"]["authorizer"]["principalId"]
userRoles = json.loads(event["requestContext"]["authorizer"]["userRoles"])
if creatorId != userMakingThisRequest and 'admin' not in userRoles:
return create_response(403, "You may only modify your own events.")
# Delete and recreate the item since start time is the sort key for our table
delRes = table.delete_item(
Key={
'event_id': originalId,
'start': originalStart,
}
)
print(f"delete response: {delRes}")
# Ensure the eventId and creator do not change
modifiedEvent['event_id'] = originalId
modifiedEvent['creator_id'] = creatorId
# Update last modified time
modifiedEvent['last_modified'] = get_utc_iso_time()
response = table.put_item(Item=modifiedEvent)
print(f"put response: {response}")
return create_response(200, json.dumps(response))
def addProjectsToEvents(event, context):
"""Endpoint to add project ids to calendar events.
Args:
event.body.project_id (str):
Id of the project to add to the event
(eg. 'Orion Assignment#2022-02-14T17:30:00Z').
event.body.events (arr):
Contains dicts for each calendar event we want to add the
project to. Each dict has keys 'event_id' and 'start',
which are the partition key and sort key for the event.
Returns:
200 status code with list of items updated in the calendar database.
"""
event_body = json.loads(event.get("body", ""))
table = dynamodb.Table(calendar_table_name)
print("event")
print(json.dumps(event))
project_id = event_body['project_id']
events = event_body['events']
responses = []
for event in events:
resp = table.update_item(
Key={
"event_id": event["event_id"],
"start": event["start"],
},
UpdateExpression="SET project_id = :id",
ExpressionAttributeValues={
":id": project_id,
}
)
responses.append(resp)
return create_response(200, json.dumps(responses, indent=4, cls=DecimalEncoder))
def removeProjectFromEvents(event, context):
"""Endpoint to remove projects from calendar events.
Args:
event.body.events (arr):
Contains dicts for each calendar event we want to add the
project to. Each dict has keys 'event_id' and 'start',
which are the partition key and sort key for the event.
Returns:
200 status code with success message.
"""
request_body = json.loads(event.get("body"))
table = dynamodb.Table(calendar_table_name)
events = request_body['events']
print(request_body)
for event_id in events:
# Get the start value from the event with given event_id
# We need both values to do an update_item operation
query_response = table.query(
Key={
"event_id": event_id,
}
)
print(f"query response: {query_response}")
start = query_response['Items'][0]['start']
# Update the item, setting the project_id to 'none'
update_response = table.update_item(
Key={
"event_id": event_id,
"start": start,
},
UpdateExpression="SET project_id = :none",
ExpressionAttributeValues={
":none": "none"
}
)
print(f'update response: {update_response}')
return create_response(200, "Success")
def deleteEventById(event, context):
"""Endpoint to delete calendar events with an event_id.
Args:
event.body.event_id (str):
Unique id for events to delete (eg. '999xx09b-xxxx-...').
event.body.start (str):
UTC datestring of starting time (eg. '2022-05-14T17:30:00Z').
context.requestContext.authorizer.principalID (str):
Auth0 user 'sub' token (eg. 'google-oauth2|xxxxxxxxxxxxx').
context.requestContext.authorizer.userRoles (str):
Global user account type (eg. 'admin').
Returns:
200 status code with response.
Raises:
ClientError: ConditionalCheckFailedException with
status code 403 if the requesting user is unauthorized.
"""
event_body = json.loads(event.get("body", ""))
table = dynamodb.Table(calendar_table_name)
print("event")
print(json.dumps(event))
# Get the user's roles provided by the lambda authorizer
userMakingThisRequest = event["requestContext"]["authorizer"]["principalId"]
print(f"userMakingThisRequest: {userMakingThisRequest}")
userRoles = json.loads(event["requestContext"]["authorizer"]["userRoles"])
print(f"userRoles: {userRoles}")
# Check if the requester is an admin
requesterIsAdmin="false"
if 'admin' in userRoles:
requesterIsAdmin="true"
print(f"requesterIsAdmin: {requesterIsAdmin}")
# Specify the event with our pk (eventToDelete) and sk (startTime)
eventToDelete = event_body['event_id']
startTime = event_body['start']
try:
response = table.delete_item(
Key={
'event_id': eventToDelete,
'start': startTime
},
ConditionExpression=":requesterIsAdmin = :true OR creator_id = :requester_id",
ExpressionAttributeValues = {
":requester_id": userMakingThisRequest,
":requesterIsAdmin": requesterIsAdmin,
":true": "true"
}
)
except ClientError as e:
print(f"error deleting event: {e}")
if e.response['Error']['Code'] == "ConditionalCheckFailedException":
print(e.response['Error']['Message'])
return create_response(403, "You may only modify your own events.")
return create_response(403, e.response['Error']['Message'])
message = json.dumps(response, indent=4, cls=DecimalEncoder)
print(f"success deleting event, message: {message}")
return create_response(200, message)
def clearExpiredSchedule(event, context):
"""Endpoint to delete calendar events with an event_id.
Args:
event.body.site (str):
sitecode for the site we are dealing with
event.body.time (str):
UTC datestring (eg. '2022-05-14T17:30:00Z'). All events that start after this will be removed.
Returns:
200 status code, with list of projects that were associated with the deleted events
"""
event_body = json.loads(event.get("body", ""))
associated_projects = remove_expired_scheduler_events(event_body["cutoff_time"], event_body["site"])
return create_response(200, json.dumps(associated_projects))
def getSiteEventsInDateRange(event, context):
"""Return calendar events within a specified date range at a given site.
Args:
event.body.event_id (str):
Unique id for event (eg. '999xx09b-xxxx-...').
event.body.start (str):
UTC datestring of starting time (eg. '2022-05-14T17:30:00Z').
event.body.end (str):
UTC datestring of ending time (eg. '2022-05-14T18:00:00Z').
Returns:
200 status code with list of matching events objects.
400 status code if a required key is missing.
Sample Python request to this endpoint:
import requests, json
url = "https://calendar.photonranch.org/dev/siteevents"
body = json.dumps({
"site": "saf",
"start": "2022-06-01T01:00:00Z",
"end": "2022-06-02T01:00:00Z",
"full_project_details": True
})
response = requests.post(url, body).json()
"""
request_body = json.loads(event.get("body", ""))
print(request_body)
table = dynamodb.Table(calendar_table_name)
# Check that all required keys are present.
required_keys = ['site', 'start', 'end']
actual_keys = request_body.keys()
for key in required_keys:
if key not in actual_keys:
msg = f"Error: missing required key {key}"
print(msg)
return create_response(400, msg)
start_date = request_body['start']
end_date = request_body['end']
site = request_body['site']
table_response = table.query(
IndexName="site-end-index",
KeyConditionExpression=Key('site').eq(site) & Key('end').between(start_date, end_date)
)
events = table_response['Items']
if 'full_project_details' in request_body and request_body['full_project_details']:
# Get the project details for each event.
for e in events:
project_id = e['project_id']
if project_id != "none":
project_name = project_id.split('#')[-2]
created_at = project_id.split('#')[-1]
e['project'] = getProject(project_name, created_at)
return create_response(200, json.dumps(events, cls=DecimalEncoder))
def getUserEventsEndingAfterTime(event, context):
"""Return a list of user events that are ending after a specified time.
Args:
event.body.time (str):
UTC datestring (eg. '2022-05-14T17:30:00Z').
event.body.user_id (str):
Auth0 user 'sub' (eg. 'google-oauth2|xxxxxxxxxxxxx').
Returns:
200 status code with list of matching event objects.
"""
event_body = json.loads(event.get("body", ""))
table = dynamodb.Table(calendar_table_name)
print("event body:")
print(event_body)
user_id = event_body["user_id"]
time = event_body["time"]
response = table.query(
IndexName="creatorid-end-index",
KeyConditionExpression=
Key('creator_id').eq(user_id)
& Key('end').gte(time)
)
return create_response(200, json.dumps(response['Items'], cls=DecimalEncoder))
def getEventAtTime(event, context):
"""Return events that are happening at a given point in time.
Args:
event.body.time (str): UTC datestring (eg. '2022-05-14T17:30:00Z').
event.body.site (str): Sitecode (eg. 'saf').
Returns:
200 status code with list of matching event objects.
"""
event_body = json.loads(event.get("body", ""))
print("event body:")
print(event_body)
time = event_body["time"]
site = event_body["site"]
events = getEventsDuringTime(time, site)
return create_response(200, json.dumps(events))
def isUserScheduled(event, context):
"""Check if a user is scheduled for an event at a specific site and time.
Args:
event.body.user_id (str):
Auth0 user 'sub' (eg. 'google-oauth2|xxxxxxxxxxxxx').
event.body.site (str):
Sitecode (eg. 'saf').
event.body.time (str):
UTC datestring (eg. '2022-05-14T17:30:00Z').
Returns:
A 200 status code with a list of allowed users for an event.
"""
event_body = json.loads(event.get("body", ""))
print("event body:")
print(event_body)
user = event_body["user_id"]
site = event_body["site"]
time = event_body["time"]
events = getEventsDuringTime(time, site)
allowed_users = [event["creator_id"] for event in events]
print(f"Allowed users: {allowed_users}")
return create_response(200, user in allowed_users)
def doesConflictingEventExist(event, context):
"""Checks for existing calendar events at a given site and time.
Calendar events should only let the designated user use the observatory.
If there are no reservations, anyone can use it.
Args:
event.body.user_id (str):
Auth0 user 'sub' (eg. 'google-oauth2|xxxxxxxxxxxxx').
event.body.site (str):
Sitecode (eg. 'saf').
event.body.time (str):
UTC datestring (eg. '2022-05-14T17:30:00Z').
Returns:
200 status code. bool: True if a different user has a reservation
at the specified time. False otherwise.
"""
event_body = json.loads(event.get("body", ""))
print("event body:")
print(event_body)
user = event_body["user_id"]
site = event_body["site"]
time = event_body["time"]
events = getEventsDuringTime(time, site)
# If any events belong to a different user, return True (indicating conflict)
for event in events:
if event["creator_id"] != user:
return create_response(200, True)
# Otherwise, report no conflicts (return False)
return create_response(200, False)