Created
November 19, 2015 18:38
-
-
Save darkyen/b6249042311f75ad3f6e to your computer and use it in GitHub Desktop.
Async fluxxy login using auth0 and es7 with localForage for storage.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AUTH0_URI = 'YOUR_URI'; | |
const AUTH0_TOKEN = 'YOUR_TOKEN'; | |
let lock = new Auth0Lock(AUTH0_TOKEN, AUTH0_URI); | |
import dispatcher from 'PATH_TO_DISPATCHER'; | |
import localForage from 'localForage'; | |
// Maybe you can drop this as its | |
// 2016 already ! | |
import Promise from 'bluebird'; | |
async function getProfile(userToken){ | |
return new Promise((resolve, reject) => { | |
lock.getProfile(userToken, function(err, profile){ | |
if( err ){ | |
reject(err); | |
} | |
resolve(profile); | |
}); | |
}); | |
} | |
async function attemptLogin(){ | |
let userToken = await localForage.getItem('userToken'); | |
let authHash = lock.parseHash(window.location.hash); | |
if( !userToken ){ | |
// Try login | |
if( !authHash ){ | |
return lock.show(); | |
} | |
if( authHash.error ){ | |
return dispatcher.dispatch({ | |
type: 'user-login-error', | |
payload: authHash | |
}) | |
} | |
if( authHash.id_token ){ | |
userToken = authHash.id_token; | |
} | |
} | |
// get profile cause we have the token. | |
await localForage.setItem('userToken', userToken); | |
dispatcher.dispatch({ | |
type: 'user-login-complete', | |
payload: authHash | |
}); | |
let profile = await getProfile(userToken); | |
dispatcher.dispatch({ | |
type: 'user-profile-update', | |
payload: {profile} | |
}); | |
} | |
async attemptLogout(){ | |
await localForage.removeItem('userToken'); | |
dispatcher.dispatch({ | |
type: 'user-logout-complete' | |
}); | |
} | |
export default { | |
login(){ | |
dispatcher.dispatch({ | |
type: 'user-login-attempted', | |
}); | |
attemptLogin(); | |
}, | |
logout(){ | |
dispatcher.dispatch({ | |
type: 'user-logout-requested' | |
}); | |
attemptLogout(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment