Skip to content

Instantly share code, notes, and snippets.

@gemmadlou
Created April 12, 2020 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gemmadlou/67ca1abe9e77616ca611cd6c952a5e85 to your computer and use it in GitHub Desktop.
Save gemmadlou/67ca1abe9e77616ca611cd6c952a5e85 to your computer and use it in GitHub Desktop.
Auth0 Vuex based Authentication
import createAuth0Client from '@auth0/auth0-spa-js'
import deepEqual from 'deep-equal'
/**
* A singleton auth0 variable that defines the Auth0 client for single use across the store
*
* @var {Auth0Client}
*/
let auth0 = undefined
export const state = () => ({
/**
* Authentication state
* whether is a user is authenticated or not to access our application
*
* @var {boolean}
*/
isAuthenticated: false,
/**
* User object returned from the Auth0 client
*
* @var {Auth0Client}
*/
user: {},
/**
* Error object from Auth0 client
*
* @var {Error}
*/
error: undefined
})
export const mutations = {
/**
* Sets the user object created by the Auth0 client
*
* @param {object} state
* @param {IdToken} payload
*/
setUser(state, payload) {
state.user = payload
},
/**
* Sets the authentication state
*
* @param {object} state
* @param {boolean} payload
*/
setAuthentication(state, payload) {
state.isAuthenticated = payload
}
}
export const actions = {
/**
* Setups a new client if one does not exist
*
* @param {*} param
* @param {function} param.commit
* @return {Promise<Auth0Client>}
*/
async setUpClient({ commit }) {
this.error = undefined
if (!auth0) {
const auther = await createAuth0Client({
domain: this.state.env.DOMAIN,
client_id: this.state.env.CLIENT_ID,
redirect_uri: `${window.location.href}dashboard`
})
auth0 = auther
return auther
}
},
/**
* Logins in user
*
* @return {Promise}
*/
async login() {
await this.dispatch('auth/setUpClient')
return await auth0.loginWithRedirect({
redirect_uri: `${window.location.href}dashboard`
})
},
/**
* Handles login callback to set the user. This can be called at any time especially if in local storage a user has
* been setup so they don't have to login everytime they appear on a freshly loaded page.
*
* @param {*} param
* @param {function} param.commit
* @return {Promise<Auth0Client>}
*/
async handlePostLogin({ commit }) {
try {
// Setup client
await this.dispatch('auth/setUpClient')
// Handle post login
await auth0.handleRedirectCallback()
// Get user
const user = await auth0.getUser()
// Check is authenticated
const isAuthenticated = await auth0.isAuthenticated()
// Check user has already been set
if (this.state.auth.user && deepEqual(this.state.auth.user, user)) {
return this.state.auth.user
}
commit('setUser', user)
commit('setAuthentication', isAuthenticated)
// Return user
return user
} catch (error) {
this.error = error
this.isAuthenticated = false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment