-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathindex.ts
More file actions
70 lines (59 loc) · 2.29 KB
/
index.ts
File metadata and controls
70 lines (59 loc) · 2.29 KB
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
import { CognitoIdentityProvider, DescribeUserPoolCommand } from '@aws-sdk/client-cognito-identity-provider';
import type {
CloudFormationCustomResourceHandler,
CloudFormationCustomResourceResponse,
CloudFormationCustomResourceDeleteEvent,
CloudFormationCustomResourceUpdateEvent,
} from 'aws-lambda';
import axios from 'axios';
const awsRegion = process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION;
const COGNITO_CLIENT = new CognitoIdentityProvider({
region: awsRegion,
});
async function ensureCognitoUserPoolDomain(userPoolId: string): Promise<string> {
const { UserPool: userPool } = await COGNITO_CLIENT.send(
new DescribeUserPoolCommand({
UserPoolId: userPoolId,
}),
);
if (!userPool) {
throw new Error(`User pool ${userPoolId} not found.`);
}
const { Domain: domainPrefix, CustomDomain: customDomain } = userPool;
if (!domainPrefix && !customDomain) {
throw new Error('Cognito auth domain is missing! Either a domain prefix or a custom domain must be configured.');
}
return userPool.CustomDomain ?? `${userPool.Domain}.auth.${awsRegion}.amazoncognito.com`;
}
export const handler: CloudFormationCustomResourceHandler = async (event) => {
const { LogicalResourceId, RequestId, RequestType, StackId, ResponseURL, ResourceProperties } = event;
const { PhysicalResourceId: physicalResourceId } = event as
| CloudFormationCustomResourceDeleteEvent
| CloudFormationCustomResourceUpdateEvent;
let response: CloudFormationCustomResourceResponse;
try {
const domainName =
RequestType !== 'Delete' ? await ensureCognitoUserPoolDomain(ResourceProperties.UserPoolId as string) : undefined;
response = {
LogicalResourceId,
PhysicalResourceId: physicalResourceId || `${ResourceProperties.UserPoolId}-user-pool-domain`,
Status: 'SUCCESS',
RequestId,
StackId,
Data: {
DomainName: domainName,
},
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (err: any) {
response = {
LogicalResourceId,
PhysicalResourceId: physicalResourceId || `failed-to-create-${Date.now()}`,
Status: 'FAILED',
Reason: err.stack || err.message,
RequestId,
StackId,
};
}
await axios.put(ResponseURL, response, { headers: { 'content-type': '' } });
};