Add JWT example source code (#3746)

* Add JWT exmaple source code

* add sample code

* [fix] eslint

* Update index.js

* [fix] rename middleware\ / to middleware/

* Add default value for demo
This commit is contained in:
Junya Kono 2018-08-17 14:49:06 +09:00 committed by Sébastien Chopin
parent f9bdac2452
commit 7161c6f191
7 changed files with 99 additions and 0 deletions

View File

@ -0,0 +1,3 @@
# Auth External API (JWT) with Nuxt.js
https://nuxtjs.org/examples/auth-external-jwt

View File

@ -0,0 +1,6 @@
export default function ({ store, redirect }) {
// If the user is not authenticated
if (!store.state.auth) {
return redirect('/login')
}
}

View File

@ -0,0 +1,6 @@
export default function ({ store, redirect }) {
// If the user is authenticated redirect to home page
if (store.state.auth) {
return redirect('/')
}
}

View File

@ -0,0 +1,13 @@
{
"name": "example-auth-jwt",
"dependencies": {
"cookieparser": "^0.1.0",
"js-cookie": "^2.2.0",
"nuxt": "latest"
},
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start"
}
}

View File

@ -0,0 +1,34 @@
<template>
<div class="container">
<h1>login view</h1>
<div>
<label for="email">
<input id="email" type="email" value="test">
</label>
<label for="password">
<input id="password" type="password" value="test">
</label>
<button @click="postLogin">login</button>
</div>
</div>
</template>
<script>
import Cookie from 'js-cookie'
export default {
middleware: 'notAuthenticated',
methods: {
postLogin() {
setTimeout(() => { // we simulate the async request with timeout.
const auth = {
accessToken: 'someStringGotFromApiServiceWithAjax'
}
this.$store.commit('update', auth) // mutating to store for client rendering
Cookie.set('auth', auth) // saving token in cookie for server rendering
this.$router.push('/')
}, 1000)
}
}
}
</script>

View File

@ -0,0 +1,9 @@
<template>
<h1>this is secret page.</h1>
</template>
<script>
export default {
middleware: 'authenticated'
}
</script>

View File

@ -0,0 +1,28 @@
import Vuex from 'vuex'
const cookieparser = process.server ? require('cookieparser') : undefined
const createStore = () => {
return new Vuex.Store({
state: {
auth: null
},
mutations: {
update(state, data) {
state.auth = data
}
},
actions: {
nuxtServerInit({ commit }, { req }) {
let accessToken = null
if (req.headers.cookie) {
const parsed = cookieparser.parse(req.headers.cookie)
accessToken = JSON.parse(parsed.auth)
}
commit('update', accessToken)
}
}
})
}
export default createStore