forked from aws-samples/cloudfront-authorization-at-edge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
79 lines (72 loc) · 2.35 KB
/
index.ts
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
/*
Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
This is a CloudFormation custom resource. It's purpose is to:
- Lookup the URL of an existing User Pool Domain
We need to do this in a custom resource to support the scenario of looking up a pre-existing User Pool Domain
*/
import {
CloudFormationCustomResourceHandler,
CloudFormationCustomResourceDeleteEvent,
CloudFormationCustomResourceUpdateEvent,
} from "aws-lambda";
import CognitoIdentityServiceProvider from "aws-sdk/clients/cognitoidentityserviceprovider";
import { sendCfnResponse, Status } from "./cfn-response";
async function ensureCognitoUserPoolDomain(
action: "Create" | "Update" | "Delete",
newUserPoolArn: string,
physicalResourceId?: string
) {
if (action === "Delete") {
return physicalResourceId!;
}
const newUserPoolId = newUserPoolArn.split("/")[1];
const newUserPoolRegion = newUserPoolArn.split(":")[3];
const cognitoClient = new CognitoIdentityServiceProvider({
region: newUserPoolRegion,
});
const { UserPool } = await cognitoClient
.describeUserPool({ UserPoolId: newUserPoolId })
.promise();
if (!UserPool) {
throw new Error(`User Pool ${newUserPoolArn} does not exist`);
}
if (UserPool.CustomDomain) {
return UserPool.CustomDomain;
} else if (UserPool.Domain) {
return `${UserPool.Domain}.auth.${newUserPoolRegion}.amazoncognito.com`;
} else {
throw new Error(
`User Pool ${newUserPoolArn} does not have a domain set up yet`
);
}
}
export const handler: CloudFormationCustomResourceHandler = async (event) => {
console.log(JSON.stringify(event, undefined, 4));
const { ResourceProperties, RequestType } = event;
const { PhysicalResourceId } = event as
| CloudFormationCustomResourceDeleteEvent
| CloudFormationCustomResourceUpdateEvent;
let status = Status.SUCCESS;
let physicalResourceId: string | undefined;
let data: { [key: string]: any } | undefined;
let reason: string | undefined;
try {
physicalResourceId = await ensureCognitoUserPoolDomain(
RequestType,
ResourceProperties.UserPoolArn,
PhysicalResourceId
);
} catch (err) {
console.error(err);
status = Status.FAILED;
reason = err;
}
await sendCfnResponse({
event,
status,
data,
physicalResourceId,
reason,
});
};