forked from aws-samples/cloudfront-authorization-at-edge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
80 lines (74 loc) · 2.08 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
80
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
import { stringify as stringifyQueryString } from "querystring";
import { CloudFrontRequestHandler } from "aws-lambda";
import {
getCompleteConfig,
extractAndParseCookies,
generateCookieHeaders,
createErrorHtml,
} from "../shared/shared";
let CONFIG: ReturnType<typeof getCompleteConfig>;
export const handler: CloudFrontRequestHandler = async (event) => {
if (!CONFIG) {
CONFIG = getCompleteConfig();
CONFIG.logger.debug("Configuration loaded:", CONFIG);
}
CONFIG.logger.debug("Event:", event);
const request = event.Records[0].cf.request;
const domainName = request.headers["host"][0].value;
const { idToken, accessToken, refreshToken } = extractAndParseCookies(
request.headers,
CONFIG.clientId,
CONFIG.cookieCompatibility
);
if (!idToken) {
const response = {
body: createErrorHtml({
title: "Signed out",
message: "You are already signed out",
linkUri: `https://${domainName}${CONFIG.redirectPathSignOut}`,
linkText: "Proceed",
}),
status: "200",
headers: {
...CONFIG.cloudFrontHeaders,
"content-type": [
{
key: "Content-Type",
value: "text/html; charset=UTF-8",
},
],
},
};
CONFIG.logger.debug("Returning response:\n", response);
return response;
}
const qs = {
logout_uri: `https://${domainName}${CONFIG.redirectPathSignOut}`,
client_id: CONFIG.clientId,
};
const response = {
status: "307",
statusDescription: "Temporary Redirect",
headers: {
location: [
{
key: "location",
value: `https://${
CONFIG.cognitoAuthDomain
}/logout?${stringifyQueryString(qs)}`,
},
],
"set-cookie": generateCookieHeaders.signOut({
tokens: {
id: idToken,
},
...CONFIG,
}),
...CONFIG.cloudFrontHeaders,
},
};
CONFIG.logger.debug("Returning response:\n", response);
return response;
};