Skip to content

Commit

Permalink
User Logout code
Browse files Browse the repository at this point in the history
  • Loading branch information
atomjar committed May 14, 2019
1 parent 8a35cad commit c7337e1
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/components/AppNav.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
<router-link to="/">
Home
</router-link>
<router-link to="/dashboard">
<router-link v-if="loggedIn" to="/dashboard">
Dashboard
</router-link>
<router-link v-if="!loggedIn" to="/login" class="button">
Login
</router-link>
<button v-else type="button" class="logoutButton" @click="logout">
Logout
</button>
</div>
</template>

Expand All @@ -17,6 +20,11 @@ import { authComputed } from '../vuex/helpers.js'
export default {
computed: {
...authComputed
},
methods: {
logout () {
this.$store.dispatch('logout')
}
}
}
</script>
Expand Down
12 changes: 11 additions & 1 deletion src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ const router = new Router({
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard
component: Dashboard,
meta: { requiresAuth: true }
},
{
path: '/register',
Expand All @@ -34,4 +35,13 @@ const router = new Router({
]
})

router.beforeEach((to, from, next) => {
const loggedIn = localStorage.getItem('user')

if (to.matched.some(record => record.meta.requiresAuth) && !loggedIn) {
next('/')
}
next()
})

export default router
7 changes: 7 additions & 0 deletions src/vuex/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ export default new Vuex.Store({
axios.defaults.headers.common['Authorization'] = `Bearer ${
userData.token
}`
},
CLEAR_USER_DATA () {
localStorage.removeItem('user')
location.reload()
}
},
actions: {
Expand All @@ -31,6 +35,9 @@ export default new Vuex.Store({
.then(({ data }) => {
commit('SET_USER_DATA', data)
})
},
logout ({ commit }) {
commit('CLEAR_USER_DATA')
}
},
getters: {
Expand Down

0 comments on commit c7337e1

Please sign in to comment.