Skip to content

Commit 9b50a0e

Browse files
author
Sachin Maheshwari
committed
adding new version of auth setup lib, login with redirect
1 parent fbd62f7 commit 9b50a0e

File tree

2 files changed

+340
-2
lines changed

2 files changed

+340
-2
lines changed
Lines changed: 338 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,338 @@
1+
var script = document.createElement('script');
2+
script.src = "https://cdn.auth0.com/js/auth0-spa-js/1.10/auth0-spa-js.production.js";
3+
script.type = 'text/javascript';
4+
script.defer = true;
5+
document.getElementsByTagName('head').item(0).appendChild(script);
6+
7+
/**
8+
* read query string
9+
*
10+
*/
11+
const qs = (function (a) {
12+
if (a == "") return {};
13+
let b = {};
14+
for (let i = 0; i < a.length; ++i) {
15+
let p = a[i].split('=', 2);
16+
if (p.length == 1)
17+
b[p[0]] = "";
18+
else
19+
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
20+
}
21+
return b;
22+
})(window.location.search.substr(1).split('&'));
23+
24+
const authSetup = function () {
25+
26+
const domain = 'topcoder-dev.auth0.com';
27+
const clientId = 'BXWXUWnilVUPdN01t2Se29Tw2ZYNGZvH';
28+
const useLocalStorage = false;
29+
const useRefreshTokens = false;
30+
const v3JWTCookie = 'v3jwt';
31+
const tcJWTCookie = 'tcjwt';
32+
const tcSSOCookie = 'tcsso';
33+
const cookieExpireIn = 12 * 60; // 12 hrs
34+
const refreshTokenInterval = 60000; // in milliseconds
35+
const refreshTokenOffset = 65; // in seconds
36+
const returnAppUrl = qs['retUrl'];
37+
const shouldLogout = qs['logout'];
38+
const regSource = qs['regSource'];
39+
const utmSource = qs['utm_source'];
40+
const appUrl = qs['appUrl'] || false;
41+
const loggerMode = "dev";
42+
const IframeLogoutRequestType = "LOGOUT_REQUEST";
43+
44+
45+
var auth0 = null;
46+
var isAuthenticated = false;
47+
var idToken = null;
48+
var callRefreshTokenFun = null;
49+
var host = window.location.protocol + "//" + window.location.host
50+
const registerSuccessUrl = host + '/register_success.html';
51+
52+
const init = function () {
53+
correctOldUrl();
54+
createAuth0Client({
55+
domain: domain,
56+
client_id: clientId,
57+
cacheLocation: useLocalStorage
58+
? 'localstorage'
59+
: 'memory',
60+
useRefreshTokens: useRefreshTokens
61+
}).then(_init);
62+
window.addEventListener("message", receiveMessage, false);
63+
};
64+
65+
const _init = function (authObj) {
66+
auth0 = authObj
67+
if (qs['code'] && qs['state']) {
68+
auth0.handleRedirectCallback().then(function (data) {
69+
logger('handleRedirectCallback() success: ', data);
70+
showAuth0Info();
71+
storeToken();
72+
}).catch(function (e) {
73+
logger('handleRedirectCallback() error: ', e);
74+
});
75+
} else if (shouldLogout) {
76+
host = returnAppUrl ? returnAppUrl : host;
77+
logout();
78+
return;
79+
} else if (!isLoggedIn() && returnAppUrl) {
80+
login();
81+
} else {
82+
logger("User already logged in", true);
83+
postLogin();
84+
}
85+
showAuthenticated();
86+
};
87+
88+
const showAuthenticated = function () {
89+
auth0.isAuthenticated().then(function (isAuthenticated) {
90+
isAuthenticated = isAuthenticated;
91+
logger("_init:isAuthenticated", isAuthenticated);
92+
});
93+
};
94+
95+
const refreshToken = function () {
96+
let d = new Date();
97+
logger('checking token status at: ', `${d.getHours()}::${d.getMinutes()}::${d.getSeconds()} `);
98+
var token = getCookie(tcJWTCookie);
99+
if (!token || isTokenExpired(token)) {
100+
logger('refreshing token... at: ', `${d.getHours()}::${d.getMinutes()}::${d.getSeconds()} `);
101+
auth0.getTokenSilently().then(function (token) {
102+
showAuth0Info();
103+
storeToken();
104+
}).catch(function (e) {
105+
logger("Error in refreshing token: ", e)
106+
if (e.error && ((e.error == "login_required") || (e.error == "timeout"))) {
107+
clearInterval(callRefreshTokenFun);
108+
}
109+
}
110+
);
111+
}
112+
};
113+
114+
const showAuth0Info = function () {
115+
auth0.getUser().then(function (user) {
116+
logger("User Profile: ", user);
117+
});
118+
auth0.getIdTokenClaims().then(function (claims) {
119+
idToken = claims.__raw;
120+
logger("JWT Token: ", idToken);
121+
});
122+
};
123+
124+
const login = function () {
125+
auth0
126+
.loginWithRedirect({
127+
redirect_uri: host + '?appUrl=' + returnAppUrl,
128+
regSource: regSource,
129+
utmSource: utmSource
130+
})
131+
.then(function () {
132+
auth0.isAuthenticated().then(function (isAuthenticated) {
133+
isAuthenticated = isAuthenticated;
134+
if (isAuthenticated) {
135+
showAuth0Info();
136+
storeToken();
137+
postLogin();
138+
}
139+
});
140+
});
141+
};
142+
143+
const logout = function () {
144+
auth0.logout({
145+
returnTo: host
146+
});
147+
// TODO
148+
setCookie(tcJWTCookie, "", -1);
149+
setCookie(v3JWTCookie, "", -1);
150+
setCookie(tcSSOCookie, "", -1);
151+
};
152+
153+
const isLoggedIn = function () {
154+
var token = getCookie(tcJWTCookie);
155+
return token ? !isTokenExpired(token) : false;
156+
};
157+
158+
const redirectToApp = function () {
159+
logger("redirect to app", appUrl);
160+
if (appUrl) {
161+
window.location = appUrl;
162+
}
163+
};
164+
165+
const postLogin = function () {
166+
logger('calling postLogin: ', true);
167+
logger('callRefreshTokenFun: ', callRefreshTokenFun);
168+
if (callRefreshTokenFun != null) {
169+
clearInterval(callRefreshTokenFun);
170+
}
171+
refreshToken();
172+
callRefreshTokenFun = setInterval(refreshToken, refreshTokenInterval);
173+
}
174+
175+
const storeToken = function () {
176+
auth0.getIdTokenClaims().then(function (claims) {
177+
idToken = claims.__raw;
178+
let userActive = false;
179+
Object.keys(claims).findIndex(function (key) {
180+
if (key.includes('active')) {
181+
userActive = claims[key];
182+
return true;
183+
}
184+
return false;
185+
});
186+
if (userActive) {
187+
let tcsso = '';
188+
Object.keys(claims).findIndex(function (key) {
189+
if (key.includes(tcSSOCookie)) {
190+
tcsso = claims[key];
191+
return true;
192+
}
193+
return false;
194+
});
195+
logger('Storing token...', true);
196+
setCookie(tcJWTCookie, idToken, cookieExpireIn);
197+
setCookie(v3JWTCookie, idToken, cookieExpireIn);
198+
setCookie(tcSSOCookie, tcsso, cookieExpireIn);
199+
redirectToApp();
200+
} else {
201+
logger("User active ? ", userActive);
202+
host = registerSuccessUrl;
203+
logout();
204+
}
205+
}).catch(function(e) {
206+
logger("Error in fetching token from auth0: ", e);
207+
});
208+
};
209+
210+
/////// Token.js
211+
212+
function getTokenExpirationDate(token) {
213+
const decoded = decodeToken(token);
214+
if (typeof decoded.exp === 'undefined') {
215+
return null;
216+
}
217+
const d = new Date(0); // The 0 here is the key, which sets the date to the epoch
218+
d.setUTCSeconds(decoded.exp);
219+
return d;
220+
}
221+
222+
function decodeToken(token) {
223+
const parts = token.split('.');
224+
225+
if (parts.length !== 3) {
226+
throw new Error('The token is invalid');
227+
}
228+
229+
const decoded = urlBase64Decode(parts[1])
230+
231+
if (!decoded) {
232+
throw new Error('Cannot decode the token');
233+
}
234+
235+
// covert base64 token in JSON object
236+
let t = JSON.parse(decoded);
237+
return t;
238+
}
239+
240+
function isTokenExpired(token, offsetSeconds = refreshTokenOffset) {
241+
const d = getTokenExpirationDate(token)
242+
243+
if (d === null) {
244+
return false;
245+
}
246+
247+
// Token expired?
248+
return !(d.valueOf() > (new Date().valueOf() + (offsetSeconds * 1000)));
249+
}
250+
251+
function urlBase64Decode(str) {
252+
let output = str.replace(/-/g, '+').replace(/_/g, '/')
253+
254+
switch (output.length % 4) {
255+
case 0:
256+
break;
257+
258+
case 2:
259+
output += '=='
260+
break;
261+
262+
case 3:
263+
output += '='
264+
break;
265+
266+
default:
267+
throw 'Illegal base64url string!';
268+
}
269+
return decodeURIComponent(escape(atob(output))); //polyfill https://github.com/davidchambers/Base64.js
270+
}
271+
272+
function setCookie(cname, cvalue, exMins) {
273+
const cdomain = getHostDomain();
274+
275+
let d = new Date();
276+
d.setTime(d.getTime() + (exMins * 60 * 1000));
277+
278+
let expires = ";expires=" + d.toUTCString();
279+
document.cookie = cname + "=" + cvalue + cdomain + expires + ";path=/";
280+
}
281+
282+
function getCookie(name) {
283+
const v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
284+
return v ? v[2] : undefined;
285+
}
286+
// end token.js
287+
288+
function getHostDomain() {
289+
let hostDomain = "";
290+
if (location.hostname !== 'localhost') {
291+
hostDomain = ";domain=." +
292+
location.hostname.split('.').reverse()[1] +
293+
"." + location.hostname.split('.').reverse()[0];
294+
}
295+
return hostDomain;
296+
}
297+
298+
function correctOldUrl() {
299+
const pattern = '#!/member';
300+
const sso_pattern = '/#!/sso-login';
301+
const logout_pattern = '/#!/logout?';
302+
303+
if (window.location.href.indexOf(pattern) > -1) {
304+
window.location.href = window.location.href.replace(pattern, '');
305+
}
306+
307+
if (window.location.href.indexOf(sso_pattern) > -1) {
308+
window.location.href = window.location.href.replace(sso_pattern, '');
309+
}
310+
311+
if (window.location.href.indexOf(logout_pattern) > -1) {
312+
window.location.href = window.location.href.replace(logout_pattern, '/?logout=true&');
313+
}
314+
}
315+
316+
function logger(label, message) {
317+
if (loggerMode === "dev") {
318+
console.log(label, message);
319+
}
320+
}
321+
322+
/**
323+
* will receive message from iframe
324+
*/
325+
function receiveMessage(e) {
326+
logger("received Event:", e);
327+
if (e.data && e.data.type && e.origin) {
328+
if (e.data.type === IframeLogoutRequestType) {
329+
host = e.origin;
330+
logout();
331+
}
332+
}
333+
334+
}
335+
336+
// execute
337+
init();
338+
};

web-assets/static-pages/index.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
77
<meta name="viewport" content="width=device-width, initial-scale=1" />
88
<link rel="shortcut icon" href="./images/favicon.ico" />
9-
<script src="./setupAuth0.js"></script>
9+
<script src="./setupAuth0WithRedirect.js"></script>
1010
<script type="text/javascript" src="https://cdn.userway.org/widget.js"></script>
1111
<link
1212
href="https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;500;700&display=swap"
@@ -36,7 +36,7 @@
3636
<a id="contentarea" tabindex="-1"></a>
3737
<h1 id="page-title-heading" class="page-title-heading">loading...</h1>
3838
<p class="page-description">
39-
Wait - Login pop-up is loading...
39+
Wait Login/Logout processing ...
4040
</p>
4141
</main>
4242
</div>

0 commit comments

Comments
 (0)