-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.html
51 lines (49 loc) · 2.23 KB
/
auth.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Auth page</title>
</head>
<body>
<script src="js/stringvalue.js"></script>
<script>
// CSRF prevention
let is_valid = new URLSearchParams(window.location.search).has("state") && localStorage.getItem("zalo_auth_state") == new URLSearchParams(window.location.search).get("state");
if (is_valid) {
// Obtain the Access Token by performing a POST request to the Access Token URL
let data = new URLSearchParams({
app_id: APP_ID,
code: new URLSearchParams(window.location.search).get("code"),
code_verifier: localStorage.getItem("zalo_code_verifier"),
grant_type: "authorization_code"
}).toString();
fetch(ZALO_ACCESS_TOKEN_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: data
}).then(response => response.json())
.then(auth => {
// store the Access Token in localStorage
localStorage.setItem("zalo_access_token", JSON.stringify({
access_token: auth.access_token,
expires_in: auth.expires_in
}));
// store the Refresh Token in a secured HTTP only cookie
let expr = new Date(new Date().getTime() + (3 * 30 * 24 * 60 * 60 * 1000)); // 3 months?
document.cookie = `zalo_refresh_token=${auth.refresh_token};expires=${expr.toUTCString()};path=/refresh;domain=${window.location.hostname};secure;HttpOnly`;
// clean up the one-time-use state variables
localStorage.removeItem("zalo_auth_state");
localStorage.removeItem("zalo_code_verifier");
// Go back to index.html
window.location.replace("index.html");
});
} else {
// Otherwise response an error
document.body.innerHTML = 'Bad Request';
}
</script>
</body>
</html>