example: Update example to make it easier to understand

This commit is contained in:
Sébastien Chopin 2018-08-17 08:29:58 +02:00
parent 7161c6f191
commit 4c18320da1
5 changed files with 44 additions and 10 deletions

View File

@ -0,0 +1,26 @@
<template>
<div>
<div v-if="$store.state.auth">
<p>You are authenticated. You can see the
<nuxt-link to="/secret">secret page</nuxt-link>!
</p>
<button @click="logout">Logout</button>
</div>
<p v-else>Please
<nuxt-link to="/login">login</nuxt-link>.
</p>
</div>
</template>
<script>
const Cookie = process.browser ? require('js-cookie') : undefined
export default {
methods: {
logout() {
Cookie.remove('auth')
this.$store.commit('setAuth', null)
}
}
}
</script>

View File

@ -1,6 +1,6 @@
<template>
<div class="container">
<h1>login view</h1>
<h1>Sign in to access the secret page</h1>
<div>
<label for="email">
<input id="email" type="email" value="test">
@ -9,12 +9,13 @@
<input id="password" type="password" value="test">
</label>
<button @click="postLogin">login</button>
<p>The crendentials are not verified for the example purpose.</p>
</div>
</div>
</template>
<script>
import Cookie from 'js-cookie'
const Cookie = process.browser ? require('js-cookie') : undefined
export default {
middleware: 'notAuthenticated',
@ -24,7 +25,7 @@ export default {
const auth = {
accessToken: 'someStringGotFromApiServiceWithAjax'
}
this.$store.commit('update', auth) // mutating to store for client rendering
this.$store.commit('setAuth', auth) // mutating to store for client rendering
Cookie.set('auth', auth) // saving token in cookie for server rendering
this.$router.push('/')
}, 1000)

View File

@ -1,5 +1,8 @@
<template>
<h1>this is secret page.</h1>
<div>
<h1>This is secret page.</h1>
<nuxt-link to="/">Back home</nuxt-link>
</div>
</template>
<script>

View File

@ -8,18 +8,22 @@ const createStore = () => {
auth: null
},
mutations: {
update(state, data) {
state.auth = data
setAuth(state, auth) {
state.auth = auth
}
},
actions: {
nuxtServerInit({ commit }, { req }) {
let accessToken = null
let auth = null
if (req.headers.cookie) {
const parsed = cookieparser.parse(req.headers.cookie)
accessToken = JSON.parse(parsed.auth)
try {
auth = JSON.parse(parsed.auth)
} catch (err) {
// No valid cookie found
}
commit('update', accessToken)
}
commit('setAuth', auth)
}
}
})