Make user CRUD route's protected behind auth

This commit is contained in:
Adrian Obelmejias
2016-02-15 16:37:00 -05:00
parent 409520d9f1
commit f691bae41d
4 changed files with 6 additions and 41 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ import session from 'koa-generic-session'
import passport from 'koa-passport' import passport from 'koa-passport'
import config from './config' import config from './config'
import { errorMiddleware } from '../src/utils' import { errorMiddleware } from '../src/middleware'
const app = new Koa() const app = new Koa()
app.keys = [config.session] app.keys = [config.session]
+5
View File
@@ -2,10 +2,12 @@ import Router from 'koa-router'
import User from '../models/users' import User from '../models/users'
import config from '../../config/config' import config from '../../config/config'
import jwt from 'jsonwebtoken' import jwt from 'jsonwebtoken'
import { ensureUser } from '../middleware/validators'
const router = new Router({ prefix: '/users' }) const router = new Router({ prefix: '/users' })
router.get('/', router.get('/',
ensureUser,
async (ctx) => { async (ctx) => {
const users = User.find({}, '-password -salt') const users = User.find({}, '-password -salt')
ctx.body = users ctx.body = users
@@ -13,6 +15,7 @@ router.get('/',
) )
router.get('/:id', router.get('/:id',
ensureUser,
async (ctx) => { async (ctx) => {
const user = await User.findById(ctx.params.id, '-password -salt') const user = await User.findById(ctx.params.id, '-password -salt')
if (!user) { if (!user) {
@@ -46,6 +49,7 @@ router.post('/',
) )
router.put('/:id', router.put('/:id',
ensureUser,
async (ctx) => { async (ctx) => {
const user = await User.findById(ctx.params.id) const user = await User.findById(ctx.params.id)
@@ -62,6 +66,7 @@ router.put('/:id',
) )
router.delete('/:id', router.delete('/:id',
ensureUser,
async (ctx) => { async (ctx) => {
const user = await User.findById(ctx.params.id) const user = await User.findById(ctx.params.id)
-11
View File
@@ -1,11 +0,0 @@
export function errorMiddleware() {
return async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.status = err.status || 500
ctx.body = err.message
ctx.app.emit('error', err, ctx)
}
}
}
-29
View File
@@ -1,29 +0,0 @@
import User from '../models/users'
import config from '../../config/config'
import { verify } from 'jsonwebtoken'
export async function ensureUser(ctx, next) {
const { token } = ctx.query
if (!token) {
ctx.throw(401)
}
let decoded = null
try {
decoded = verify(token, config.tokenSecret)
} catch (err) {
ctx.throw(401)
}
try {
const user = await User.findById(decoded.id)
if (!user) {
ctx.throw(401)
}
} catch (err) {
ctx.throw(500)
}
return next()
}