-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAuthCheck.js
More file actions
120 lines (95 loc) · 3.45 KB
/
AuthCheck.js
File metadata and controls
120 lines (95 loc) · 3.45 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
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
function AuthCheck(from) {
const AUTH0_DOMAIN = 'codeworksacademy.auth0.com';
const CLIENT_ID = 'Pr738Hn5ZZhYYahOhTukx3phzlIPGCfl';
const audience = 'https://codeworksacademy.com';
const IS_LOCAL = window.location.hostname === 'localhost';
const REDIRECT_URI = IS_LOCAL ? window.location.origin : 'https://codeworksacademy.com/login';
const FROM_KEY = 'auth_from';
from = from || getUrlParam('from') || localStorage.getItem(FROM_KEY) || getCookie(FROM_KEY);
function getUrlParam(param) {
return new URLSearchParams(window.location.search).get(param);
}
async function exchangeCodeForToken(authCode) {
const codeVerifier = localStorage.getItem('code_verifier') || getCookie('code_verifier');
if (!codeVerifier) {
console.warn('🚨 Code verifier missing. Restarting login flow...');
// redirectToLogin();
return;
}
const response = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
grant_type: 'authorization_code',
client_id: CLIENT_ID,
code: authCode,
redirect_uri: REDIRECT_URI,
code_verifier: codeVerifier,
audience,
}),
});
if (!response.ok) {
console.error('❌ Failed to exchange code:', await response.text());
// redirectToLogin();
return;
}
const data = await response.json();
setCookie('auth_access_token', data.access_token, data.expires_in);
const returnTo = localStorage.getItem(FROM_KEY);
if (!returnTo) return
localStorage.removeItem(FROM_KEY);
window.location.href = returnTo;
}
function setCookie(name, value, seconds) {
const expires = new Date(Date.now() + seconds * 1000).toUTCString();
document.cookie = `${name}=${value}; expires=${expires}; path=/; domain=.codeworksacademy.com; Secure; SameSite=None`;
}
(async function handleAuthFlow() {
const authCode = getUrlParam('code');
if (from) {
localStorage.setItem('auth_from', from);
}
if (authCode) {
await exchangeCodeForToken(authCode);
}
if (getCookie('auth_access_token')) {
return fetchUserInfo();
}
})();
function getCookie(name) {
const match = document.cookie.match(`(^|;)\\s*${name}\\s*=\\s*([^;]+)`);
return match ? decodeURIComponent(match[2]) : null;
}
function deleteCookie(name) {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; Secure; SameSite=None`;
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=.codeworksacademy.com; Secure; SameSite=None`;
}
function fetchUserInfo() {
fetch(`https://${AUTH0_DOMAIN}/userinfo`, {
headers: {
Authorization: `Bearer ${getCookie('auth_access_token')}`
}
})
.then(response => response.json())
.then(data => {
console.log('👋 Welcome back', data.name);
updateNav()
})
.catch(error => {
console.error('❌ Failed to fetch user info:', error);
deleteCookie('auth_access_token');
});
}
function updateNav() {
const loginLink = document.querySelector('#login');
const logoutLink = document.querySelector('#logout');
if (getCookie('auth_access_token')) {
loginLink.style.display = 'none';
logoutLink.style.display = 'block';
} else {
loginLink.style.display = 'block';
logoutLink.style.display = 'none';
}
}
}
AuthCheck()