Skip to content

Commit 33bb7c8

Browse files
author
Michael Brewer
authored
docs(data-classes): Add more cognito code examples (#340)
1 parent 542eb5b commit 33bb7c8

File tree

3 files changed

+215
-11
lines changed

3 files changed

+215
-11
lines changed

Diff for: aws_lambda_powertools/utilities/data_classes/common.py

+5
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ def __eq__(self, other: Any) -> bool:
1919
def get(self, key: str) -> Optional[Any]:
2020
return self._data.get(key)
2121

22+
@property
23+
def raw_event(self) -> Dict[str, Any]:
24+
"""The original raw event dict"""
25+
return self._data
26+
2227

2328
def get_header_value(headers: Dict[str, str], name: str, default_value: str, case_sensitive: bool) -> Optional[str]:
2429
"""Get header value by name"""

Diff for: docs/utilities/data_classes.md

+197
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,8 @@ Define Auth Challenge | `data_classes.cognito_user_pool_event.DefineAuthChalleng
236236
Create Auth Challenge | `data_classes.cognito_user_pool_event.CreateAuthChallengeTriggerEvent`
237237
Verify Auth Challenge | `data_classes.cognito_user_pool_event.VerifyAuthChallengeResponseTriggerEvent`
238238

239+
#### Post Confirmation Example
240+
239241
=== "app.py"
240242

241243
```python
@@ -248,6 +250,201 @@ Verify Auth Challenge | `data_classes.cognito_user_pool_event.VerifyAuthChalleng
248250
do_something_with(user_attributes)
249251
```
250252

253+
#### Define Auth Challenge Example
254+
255+
!!! warning "NOTE "
256+
In this example we are modifying the wrapped dict response fields, so we need to return the json serializable wrapped event in `event.raw_event`
257+
258+
!!! info "NOTE "
259+
This example is based on the AWS Cognito docs for [Define Auth Challenge Lambda Trigger](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-define-auth-challenge.html){target="_blank"}
260+
261+
=== "app.py"
262+
263+
```python
264+
from aws_lambda_powertools.utilities.data_classes.cognito_user_pool_event import DefineAuthChallengeTriggerEvent
265+
266+
def handler(event: dict, context) -> dict:
267+
event: DefineAuthChallengeTriggerEvent = DefineAuthChallengeTriggerEvent(event)
268+
if (
269+
len(event.request.session) == 1
270+
and event.request.session[0].challenge_name == "SRP_A"
271+
):
272+
event.response.issue_tokens = False
273+
event.response.fail_authentication = False
274+
event.response.challenge_name = "PASSWORD_VERIFIER"
275+
elif (
276+
len(event.request.session) == 2
277+
and event.request.session[1].challenge_name == "PASSWORD_VERIFIER"
278+
and event.request.session[1].challenge_result
279+
):
280+
event.response.issue_tokens = False
281+
event.response.fail_authentication = False
282+
event.response.challenge_name = "CUSTOM_CHALLENGE"
283+
elif (
284+
len(event.request.session) == 3
285+
and event.request.session[2].challenge_name == "CUSTOM_CHALLENGE"
286+
and event.request.session[2].challenge_result
287+
):
288+
event.response.issue_tokens = True
289+
event.response.fail_authentication = False
290+
else:
291+
event.response.issue_tokens = False
292+
event.response.fail_authentication = True
293+
294+
return event.raw_event
295+
```
296+
=== "SPR_A response"
297+
298+
```json hl_lines="25-27"
299+
{
300+
"version": "1",
301+
"region": "us-east-1",
302+
"userPoolId": "us-east-1_example",
303+
"userName": "UserName",
304+
"callerContext": {
305+
"awsSdkVersion": "awsSdkVersion",
306+
"clientId": "clientId"
307+
},
308+
"triggerSource": "DefineAuthChallenge_Authentication",
309+
"request": {
310+
"userAttributes": {
311+
"sub": "4A709A36-7D63-4785-829D-4198EF10EBDA",
312+
"email_verified": "true",
313+
"name": "First Last",
314+
"email": "define-auth@mail.com"
315+
},
316+
"session": [
317+
{
318+
"challengeName": "SRP_A",
319+
"challengeResult": true
320+
}
321+
]
322+
},
323+
"response": {
324+
"issueTokens": false,
325+
"failAuthentication": false,
326+
"challengeName": "PASSWORD_VERIFIER"
327+
}
328+
}
329+
```
330+
=== "PASSWORD_VERIFIER success response"
331+
332+
```json hl_lines="30-32"
333+
{
334+
"version": "1",
335+
"region": "us-east-1",
336+
"userPoolId": "us-east-1_example",
337+
"userName": "UserName",
338+
"callerContext": {
339+
"awsSdkVersion": "awsSdkVersion",
340+
"clientId": "clientId"
341+
},
342+
"triggerSource": "DefineAuthChallenge_Authentication",
343+
"request": {
344+
"userAttributes": {
345+
"sub": "4A709A36-7D63-4785-829D-4198EF10EBDA",
346+
"email_verified": "true",
347+
"name": "First Last",
348+
"email": "define-auth@mail.com"
349+
},
350+
"session": [
351+
{
352+
"challengeName": "SRP_A",
353+
"challengeResult": true
354+
},
355+
{
356+
"challengeName": "PASSWORD_VERIFIER",
357+
"challengeResult": true
358+
}
359+
]
360+
},
361+
"response": {
362+
"issueTokens": false,
363+
"failAuthentication": false,
364+
"challengeName": "CUSTOM_CHALLENGE"
365+
}
366+
}
367+
368+
```
369+
=== "CUSTOM_CHALLENGE success response"
370+
371+
```json hl_lines="34 35"
372+
{
373+
"version": "1",
374+
"region": "us-east-1",
375+
"userPoolId": "us-east-1_example",
376+
"userName": "UserName",
377+
"callerContext": {
378+
"awsSdkVersion": "awsSdkVersion",
379+
"clientId": "clientId"
380+
},
381+
"triggerSource": "DefineAuthChallenge_Authentication",
382+
"request": {
383+
"userAttributes": {
384+
"sub": "4A709A36-7D63-4785-829D-4198EF10EBDA",
385+
"email_verified": "true",
386+
"name": "First Last",
387+
"email": "define-auth@mail.com"
388+
},
389+
"session": [
390+
{
391+
"challengeName": "SRP_A",
392+
"challengeResult": true
393+
},
394+
{
395+
"challengeName": "PASSWORD_VERIFIER",
396+
"challengeResult": true
397+
},
398+
{
399+
"challengeName": "CUSTOM_CHALLENGE",
400+
"challengeResult": true
401+
}
402+
]
403+
},
404+
"response": {
405+
"issueTokens": true,
406+
"failAuthentication": false
407+
}
408+
}
409+
```
410+
411+
#### Create Auth Challenge Example
412+
413+
!!! info "NOTE "
414+
This example is based on the AWS Cognito docs for [Create Auth Challenge Lambda Trigger](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-create-auth-challenge.html){target="_blank"}
415+
416+
=== "app.py"
417+
418+
```python
419+
from aws_lambda_powertools.utilities.data_classes.cognito_user_pool_event import CreateAuthChallengeTriggerEvent
420+
421+
def handler(event: dict, context) -> dict:
422+
event: CreateAuthChallengeTriggerEvent = CreateAuthChallengeTriggerEvent(event)
423+
if event.request.challenge_name == "CUSTOM_CHALLENGE":
424+
event.response.public_challenge_parameters = {"captchaUrl": "url/123.jpg"}
425+
event.response.private_challenge_parameters = {"answer": "5"}
426+
event.response.challenge_metadata = "CAPTCHA_CHALLENGE"
427+
return event.raw_event
428+
```
429+
430+
#### Verify Auth Challenge Response Example
431+
432+
!!! info "NOTE "
433+
This example is based on the AWS Cognito docs for [Verify Auth Challenge Response Lambda Trigger](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-verify-auth-challenge-response.html){target="_blank"}
434+
435+
=== "app.py"
436+
437+
```python
438+
from aws_lambda_powertools.utilities.data_classes.cognito_user_pool_event import VerifyAuthChallengeResponseTriggerEvent
439+
440+
def handler(event: dict, context) -> dict:
441+
event: VerifyAuthChallengeResponseTriggerEvent = VerifyAuthChallengeResponseTriggerEvent(event)
442+
event.response.answer_correct = (
443+
event.request.private_challenge_parameters.get("answer") == event.request.challenge_answer
444+
)
445+
return event.raw_event
446+
```
447+
251448
### Connect Contact Flow
252449

253450
=== "app.py"

Diff for: tests/functional/test_lambda_trigger_events.py

+13-11
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ def message(self) -> str:
7373
assert DataClassSample(data1) is not data1
7474
assert data1 is not DataClassSample(data1)
7575

76+
assert DataClassSample(data1).raw_event is data1
77+
7678

7779
def test_cloud_watch_trigger_event():
7880
event = CloudWatchLogsEvent(load_event("cloudWatchLogEvent.json"))
@@ -81,7 +83,7 @@ def test_cloud_watch_trigger_event():
8183
assert event.decompress_logs_data == decompressed_logs_data
8284

8385
json_logs_data = event.parse_logs_data()
84-
assert event.parse_logs_data()._data == json_logs_data._data
86+
assert event.parse_logs_data().raw_event == json_logs_data.raw_event
8587
log_events = json_logs_data.log_events
8688
log_event = log_events[0]
8789

@@ -97,7 +99,7 @@ def test_cloud_watch_trigger_event():
9799
assert log_event.extracted_fields is None
98100

99101
event2 = CloudWatchLogsEvent(load_event("cloudWatchLogEvent.json"))
100-
assert event._data == event2._data
102+
assert event.raw_event == event2.raw_event
101103

102104

103105
def test_cognito_pre_signup_trigger_event():
@@ -493,7 +495,7 @@ def test_s3_trigger_event():
493495
assert s3.get_object.version_id is None
494496
assert s3.get_object.sequencer == "0C0F6F405D6ED209E1"
495497
assert record.glacier_event_data is None
496-
assert event.record._data == event["Records"][0]
498+
assert event.record.raw_event == event["Records"][0]
497499
assert event.bucket_name == "lambda-artifacts-deafc19498e3f2df"
498500
assert event.object_key == "b21b84d653bb07b05b1e6b33684dc11b"
499501

@@ -559,7 +561,7 @@ def test_ses_trigger_event():
559561
assert headers[0].value == "<janedoe@example.com>"
560562
common_headers = mail.common_headers
561563
assert common_headers.return_path == "janedoe@example.com"
562-
assert common_headers.get_from == common_headers._data["from"]
564+
assert common_headers.get_from == common_headers.raw_event["from"]
563565
assert common_headers.date == "Wed, 7 Oct 2015 12:34:56 -0700"
564566
assert common_headers.to == [expected_address]
565567
assert common_headers.message_id == "<0123456789example.com>"
@@ -573,12 +575,12 @@ def test_ses_trigger_event():
573575
assert receipt.spf_verdict.status == "PASS"
574576
assert receipt.dmarc_verdict.status == "PASS"
575577
action = receipt.action
576-
assert action.get_type == action._data["type"]
577-
assert action.function_arn == action._data["functionArn"]
578-
assert action.invocation_type == action._data["invocationType"]
579-
assert event.record._data == event["Records"][0]
580-
assert event.mail._data == event["Records"][0]["ses"]["mail"]
581-
assert event.receipt._data == event["Records"][0]["ses"]["receipt"]
578+
assert action.get_type == action.raw_event["type"]
579+
assert action.function_arn == action.raw_event["functionArn"]
580+
assert action.invocation_type == action.raw_event["invocationType"]
581+
assert event.record.raw_event == event["Records"][0]
582+
assert event.mail.raw_event == event["Records"][0]["ses"]["mail"]
583+
assert event.receipt.raw_event == event["Records"][0]["ses"]["receipt"]
582584

583585

584586
def test_sns_trigger_event():
@@ -604,7 +606,7 @@ def test_sns_trigger_event():
604606
assert sns.unsubscribe_url == "https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe"
605607
assert sns.topic_arn == "arn:aws:sns:us-east-2:123456789012:sns-lambda"
606608
assert sns.subject == "TestInvoke"
607-
assert event.record._data == event["Records"][0]
609+
assert event.record.raw_event == event["Records"][0]
608610
assert event.sns_message == "Hello from SNS!"
609611

610612

0 commit comments

Comments
 (0)