Skip to content
Permalink
Browse files

add api auth

  • Loading branch information...
galvez committed Apr 28, 2019
1 parent 6316365 commit fc5404272c6accdf8b6f5c1d00d2e51b3593c6dc
Showing with 52 additions and 5 deletions.
  1. +30 −1 api.js
  2. +4 −0 db.js
  3. +1 −1 middleware/auth.js
  4. +2 −1 nuxt.config.js
  5. +7 −2 pages/index.vue
  6. +8 −0 plugins/http.js
31 api.js
@@ -1,7 +1,7 @@
import { sign, verify } from 'jsonwebtoken' import { sign, verify } from 'jsonwebtoken'
import { json } from 'body-parser' import { json } from 'body-parser'
import { parse } from 'cookie' import { parse } from 'cookie'
import { addUser, authUser } from './db' import { addUser, authUser, getUser } from './db'


const expiresIn = '90d' const expiresIn = '90d'
const sessionSecret = 'some truly random value' const sessionSecret = 'some truly random value'
@@ -45,6 +45,35 @@ export default [
res.end() res.end()
} }
}, },
(req, res, next) => {
if (!req.url.startsWith('/api')) {
return next()
}
if (!req.headers.authorization) {
res.statusCode = 401
res.end()
return
}
const tokenMatch = req.headers.authorization.match(/Bearer (.+)/)
if (tokenMatch) {
const jwtData = verify(tokenMatch[1], sessionSecret)
if (jwtData) {
req.email = jwtData.email
req.token = tokenMatch[1]
return next()
}
}
res.statusCode = 401
res.end()
},
{
path: '/api/user',
async handler(req, res, next) {
const user = await getUser(req.email)
res.json({ user })
res.end()
}
},
(req, res, next) => { (req, res, next) => {
const cookies = req.headers.cookie || '' const cookies = req.headers.cookie || ''
const parsedCookies = parse(cookies) || {} const parsedCookies = parse(cookies) || {}
4 db.js
@@ -33,3 +33,7 @@ export function authUser({ email, password }) {
} }
return false return false
} }

export function getUser(email) {
return db.users[email]
}
@@ -6,6 +6,6 @@ export default function ({ store, route, redirect, req }) {
}) })
} }
if (!store.state.user.authenticated) { if (!store.state.user.authenticated) {
redirect('/register') return redirect('/register')
} }
} }
@@ -8,5 +8,6 @@ export default {
}, },
http: { http: {
baseURL: 'http://localhost:3030' baseURL: 'http://localhost:3030'
} },
plugins: ['~/plugins/http']
} }
@@ -1,6 +1,6 @@
<template> <template>
<div> <div>
Hello, {{ user.email }}! Hello, {{ user.name }}!
</div> </div>
</template> </template>


@@ -9,6 +9,11 @@ import { mapState } from 'vuex'
export default { export default {
middleware: 'auth', middleware: 'auth',
computed: mapState(['user']) data: () => ({
user: {}
}),
async asyncData({ $http, store }) {
return $http.$get('api/user')
}
} }
</script> </script>
@@ -0,0 +1,8 @@
export default function ({ $http, store }) {
$http.onRequest((config) => {
if (store.state.user.authenticated) {
config.headers.set('Authorization', `Bearer ${store.state.user.token}`)
}
return config
})
}

0 comments on commit fc54042

Please sign in to comment.
You can’t perform that action at this time.