dkh
04/20/2017, 12:42 AMcomponentWillMount() {
const auth = this.props.route.auth
auth.on('profile_updated', (profile) => {
this.createUser(profile)
})
}
nilan
04/20/2017, 8:19 AMdkh
04/20/2017, 11:06 AM// App.js
componentWillMount() {
const auth = this.props.route.auth
const user = this.props.data.user
const auth0IdToken = window.localStorage.getItem('auth0IdToken')
auth.on('profile_updated', (profile) => {
if (user || auth0IdToken === null) {
console.log('user exists')
} else if (!user && auth0IdToken === null) {
// user exists, but not logged in. login user?
}
else {
// user does not exits, create please
this.createUser(profile)
}
})
}
dkh
04/20/2017, 11:10 AMauth
is a helper class that I’m instantiating in my index.js file and passing down through my / route:
import { EventEmitter } from 'events'
import { isTokenExpired } from './jwtHelper'
import Auth0Lock from 'auth0-lock'
import { browserHistory } from 'react-router'
export default class AuthService extends EventEmitter {
constructor(clientId, domain) {
super()
// Configure Auth0
this.lock = new Auth0Lock(clientId, domain, {
auth: {
redirectUrl: `${window.location.origin}/`,
responseType: 'token'
}
})
// Add callback for lock `authenticated` event
this.lock.on('authenticated', this._doAuthentication.bind(this))
// Add callback for lock `authorization_error` event
this.lock.on('authorization_error', this._authorizationError.bind(this))
// binds login functions to keep this context
this.login = this.login.bind(this)
}
_doAuthentication(authResult){
// Saves the user token
this.setToken(authResult.idToken)
// navigate to the home route
browserHistory.replace('/')
// Async loads the user profile data
this.lock.getProfile(authResult.idToken, (error, profile) => {
if (error) {
console.log('Error loading the Profile', error)
} else {
this.setProfile(profile)
}
})
}
_authorizationError(error){
// Unexpected authentication error
console.log('Authentication Error', error)
}
login() {
// Call the show method to display the widget.
this.lock.show()
}
loggedIn(){
// Checks if there is a saved token and it's still valid
const token = this.getToken()
return !!token && !isTokenExpired(token)
}
setProfile(profile){
// Saves profile data to localStorage
localStorage.setItem('profile', JSON.stringify(profile))
// Triggers profile_updated event to update the UI
this.emit('profile_updated', profile)
}
getProfile(){
// Retrieves the profile data from localStorage
const profile = localStorage.getItem('profile')
return profile ? JSON.parse(localStorage.profile) : {}
}
setToken(idToken){
// Saves user token to localStorage
localStorage.setItem('auth0IdToken', idToken)
}
getToken(){
// Retrieves the user token from localStorage
return localStorage.getItem('auth0IdToken')
}
logout(){
// Clear user token and profile data from localStorage
localStorage.removeItem('auth0IdToken')
localStorage.removeItem('profile')
window.location.replace('/')
}
}
nilan
04/20/2017, 12:04 PM