-
Notifications
You must be signed in to change notification settings - Fork 359
/
Copy pathapp.js
164 lines (133 loc) · 3.88 KB
/
app.js
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// The Auth0 client, initialized in configureClient()
let auth0Client = null;
/**
* Starts the authentication flow
*/
const login = async (targetUrl) => {
try {
console.log("Logging in", targetUrl);
const options = {
authorizationParams: {
redirect_uri: window.location.origin
}
};
if (targetUrl) {
options.appState = { targetUrl };
}
await auth0Client.loginWithRedirect(options);
} catch (err) {
console.log("Log in failed", err);
}
};
/**
* Executes the logout flow
*/
const logout = async () => {
try {
console.log("Logging out");
await auth0Client.logout({
logoutParams: {
returnTo: window.location.origin
}
});
} catch (err) {
console.log("Log out failed", err);
}
};
/**
* Retrieves the auth configuration from the server
*/
const fetchAuthConfig = () => fetch("/auth_config.json");
/**
* Initializes the Auth0 client
*/
const configureClient = async () => {
const response = await fetchAuthConfig();
const config = await response.json();
auth0Client = await auth0.createAuth0Client({
domain: config.domain,
clientId: config.clientId,
authorizationParams: {
audience: config.audience
}
});
};
/**
* Checks to see if the user is authenticated. If so, `fn` is executed. Otherwise, the user
* is prompted to log in
* @param {*} fn The function to execute if the user is logged in
*/
const requireAuth = async (fn, targetUrl) => {
const isAuthenticated = await auth0Client.isAuthenticated();
if (isAuthenticated) {
return fn();
}
return login(targetUrl);
};
/**
* Calls the API endpoint with an authorization token
*/
const callApi = async () => {
try {
const token = await auth0Client.getTokenSilently();
const response = await fetch("/api/external", {
headers: {
Authorization: `Bearer ${token}`
}
});
const responseData = await response.json();
const responseElement = document.getElementById("api-call-result");
responseElement.innerText = JSON.stringify(responseData, {}, 2);
document.querySelectorAll("pre code").forEach(hljs.highlightBlock);
eachElement(".result-block", (c) => c.classList.add("show"));
} catch (e) {
console.error(e);
}
};
// Will run when page finishes loading
window.onload = async () => {
await configureClient();
// If unable to parse the history hash, default to the root URL
if (!showContentFromUrl(window.location.pathname)) {
showContentFromUrl("/");
window.history.replaceState({ url: "/" }, {}, "/");
}
const bodyElement = document.getElementsByTagName("body")[0];
// Listen out for clicks on any hyperlink that navigates to a #/ URL
bodyElement.addEventListener("click", (e) => {
if (isRouteLink(e.target)) {
const url = e.target.getAttribute("href");
if (showContentFromUrl(url)) {
e.preventDefault();
window.history.pushState({ url }, {}, url);
}
} else if (e.target.getAttribute("id") === "call-api") {
e.preventDefault();
callApi();
}
});
const isAuthenticated = await auth0Client.isAuthenticated();
if (isAuthenticated) {
console.log("> User is authenticated");
window.history.replaceState({}, document.title, window.location.pathname);
updateUI();
return;
}
console.log("> User not authenticated");
const query = window.location.search;
const shouldParseResult = query.includes("code=") && query.includes("state=");
if (shouldParseResult) {
console.log("> Parsing redirect");
try {
const result = await auth0Client.handleRedirectCallback();
if (result.appState && result.appState.targetUrl) {
showContentFromUrl(result.appState.targetUrl);
}
console.log("Logged in!");
} catch (err) {
console.log("Error parsing redirect:", err);
}
window.history.replaceState({}, document.title, "/");
}
updateUI();
};