Skip to content

Instantly share code, notes, and snippets.

@motia
Last active August 19, 2017 22:15
Show Gist options
  • Save motia/05cf311f501d0768a2c8a318bb644282 to your computer and use it in GitHub Desktop.
Save motia/05cf311f501d0768a2c8a318bb644282 to your computer and use it in GitHub Desktop.
Nuxt JWT
export default async function ({ store, route, redirect }) {
store.dispatch('auth/loadToken')
const hasToken = Boolean(store.state.auth.token)
const isLoggedIn = store.state.auth.loggedIn
// if have a token
if (hasToken) {
if (route.path === '/login') {
redirect('/')
return
}
// assert user have a profile
if (!isLoggedIn) {
// not yet, try to load it
try {
await store.dispatch('auth/loadProfile')
} catch (e) { // invalid token
redirect('/login')
return
}
}
} else if (route.path !== '/login') {
redirect('/login')
}
}
/**
* forked from https://github.com/nuxt/modules/blob/master/modules/auth/store.js
* under MIT Licence
**/
import Cookie from 'cookie'
import Cookies from 'js-cookie'
import {setToken, $get, $post} from '~plugins/axios'
const inBrowser = typeof window !== 'undefined'
const SSR = global.__VUE_SSR_CONTEXT__
function AuthStore (opts) {
const self = this
opts = opts || {}
this.defaultState = {
user: Object.assign({roles: [], scope: [], email: null}, opts.default_user),
loggedIn: false,
token: null
}
this.state = () => { Object.assign({}, self.defaultState) }
this.getters = {}
this.mutations = {
setUser (state, user) {
state.user = Object.assign({}, self.defaultState.user, user)
state.loggedIn = Boolean(user)
},
setToken (state, token) {
state.token = token
// Setup axios
setToken(token)
// Store token in cookies
if (inBrowser) {
if (!token) {
return Cookies.remove('token', opts.tokenCookie)
}
Cookies.set('token', token, opts.tokenCookie)
}
}
}
// ----------------------------------------
// Actions
// ----------------------------------------
this.actions = {
loadToken (ctx) {
// Try to extract token from cookies
const cookieStr = inBrowser ? document.cookie : (SSR.req.headers.cookie)
const cookies = Cookie.parse(cookieStr || '') || {}
const token = cookies.token
ctx.commit('setToken', token)
},
async loadProfile (ctx) {
try {
const user = $get('/auth/user')
ctx.commit('setUser', user)
} catch (e) {
ctx.dispatch('logout')
throw e
}
},
async login (ctx, {fields}) {
const endpoint = '/auth/login'
const {token} = await $post(endpoint, fields)
ctx.commit('setToken', token)
ctx.dispatch('loadToken')
return await ctx.dispatch('loadProfile')
},
logout (ctx) {
ctx.commit('setUser', null)
ctx.commit('setToken', null)
}
}
}
export default new AuthStore()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment