-
Notifications
You must be signed in to change notification settings - Fork 0
/
login.ts
89 lines (78 loc) · 2.6 KB
/
login.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
81
82
83
84
85
86
87
88
89
import { Handler } from "@netlify/functions";
import {
error,
getFallbackRawUrl,
Options,
loadOptionsFromEnvironment,
validateUrl,
} from "./utils";
export function getLoginHandler(options: Options = {}): Handler {
// Primary lambda function handler
const handler: Handler = async (event, context) => {
loadOptionsFromEnvironment(options);
const prodBaseUrl = options.prodBaseUrl;
if (!prodBaseUrl) {
return error(500, "Production URL not configured.");
}
const prodLoginUrl = new URL("/.netlify/functions/login", prodBaseUrl);
const rawUrl = event.rawUrl
? new URL(event.rawUrl)
: getFallbackRawUrl(
event.headers.host,
"/.netlify/functions/login",
prodLoginUrl.protocol
); // Netlify's local env doesn't have rawUrl 😞
const isPreviewSite = rawUrl.hostname !== prodLoginUrl.hostname;
let targetRedirectUrl = options.oktaUrl;
let redirectToJs = '" + window.location.href + "';
if (isPreviewSite) {
const authUrl = new URL(rawUrl);
authUrl.pathname = "/.netlify/functions/auth";
authUrl.search = "";
authUrl.hash = "";
prodLoginUrl.search =
"?redirect_to=" + encodeURIComponent(authUrl.toString());
targetRedirectUrl = prodLoginUrl.toString();
} else if (event.queryStringParameters?.redirect_to) {
redirectToJs = validateUrl(event.queryStringParameters.redirect_to, "/");
}
if (!targetRedirectUrl) {
return error(500, "OKTA URL not configured.");
}
const targetLabel = isPreviewSite ? "production site" : "Okta";
return {
statusCode: 200,
headers: { "Content-Type": "text/html" },
body: `<!DOCTYPE html>
<html lang="en">
<head>
<title>Login${
options.siteTitle ? ": " + options.siteTitle : ""
}</title>
</head>
<body>
<p>Redirecting to ${targetLabel} to login...</p>
<script>
document.cookie = "redirect_to=${redirectToJs}; path=/";
</script>
${
options?.unsafe?.debug
? `
<p><a href="${targetRedirectUrl}">Proceed to ${targetLabel}</a> (local dev mode)</p>
<h2>Event</h2>
<pre>${JSON.stringify(event, undefined, 2)}</pre>
<h2>Context</h2>
<pre>${JSON.stringify(context, undefined, 2)}</pre>
`
: `
<script>
window.location.href = "${targetRedirectUrl}";
</script>
`
}
</body>
</html>`,
};
};
return handler;
}