Skip to content

Instantly share code, notes, and snippets.

@aaguiarz
Created December 13, 2017 02:36
Show Gist options
  • Save aaguiarz/1ea391585054f83d35db4de785b0d605 to your computer and use it in GitHub Desktop.
Save aaguiarz/1ea391585054f83d35db4de785b0d605 to your computer and use it in GitHub Desktop.
Lock v9 Sample
<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<title>Lock 9 Example with Redirect</title>
</head>
<body>
<script src="http://cdn.auth0.com/js/lock-9.min.js"></script>
<script>
var tokenRenewalTimeout;
var lock = new Auth0Lock('WFyt09qw3MYQYVfhZ0Diz4c2jkVzozUs', 'aaguiar.auth0.com');
var hash = lock.parseHash();
if (hash)
{
if (!hash.error)
{
setSession(hash.profile, hash.id_token, hash.access_token, hash.refresh_token);
lock.getProfile(hash.id_token, function(err, profile) {
if (!err)
{
console.log("Hey dude", profile);
}
});
// our just use hash.profile, which already has the profile
}
else
{
console.log("There was an error logging in", hash.error)
}
}
function login()
{
lock.show(
{
callbackURL: "http://localhost:8080/lock_v9.html",
responseType : "token",
authParams: {
scope: 'openid email offline_access'
}
}
);
}
function renewToken() {
refresh_token = localStorage.getItem('refresh_token');
lock.getClient().refreshToken(refresh_token, function (err, delegationResult) {
if (!err)
{
var expires_at = JSON.stringify(delegationResult.expires_in* 1000 + new Date().getTime());
localStorage.setItem('expires_at', expires_at);
localStorage.setItem('id_token', delegationResult.id_token);
scheduleRenewal();
}
}
);
}
function logout() {
// Remove tokens and expiry time from localStorage
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
localStorage.removeItem('expires_at');
localStorage.removeItem('refresh_token');
clearTimeout(tokenRenewalTimeout);
}
function setSession(profile, id_token, access_token, refresh_token)
{
localStorage.setItem('id_token', id_token);
localStorage.setItem('expires_at', JSON.stringify(profile.exp));
localStorage.setItem('access_token', access_token);
localStorage.setItem('refresh_token', refresh_token);
scheduleRenewal();
}
function scheduleRenewal() {
var expiresAt = JSON.parse(localStorage.getItem('expires_at'));
var delay = expiresAt - Date.now();
if (delay > 0) {
tokenRenewalTimeout = setTimeout(function() {
renewToken();
}, delay);
}
}
</script>
<button onclick="login()">Login</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment