Skip to content

Instantly share code, notes, and snippets.

@KelvinCampelo
Last active February 6, 2020 20:17
Show Gist options
  • Save KelvinCampelo/a6b8a8182e5fffd5fc58f2e1002aaedc to your computer and use it in GitHub Desktop.
Save KelvinCampelo/a6b8a8182e5fffd5fc58f2e1002aaedc to your computer and use it in GitHub Desktop.
jwt route protection example node
import { Router } from 'express'
import { create } from './controller'
import jwt from 'jsonwebtoken'
const router = new Router()
router.post(
'/things',
only(['admin','customer']),
create
)
const only = roles = (req, res, next) => {
try {
req.decoded = jwt.verify(token, 'my-secret')
if(roles.includes(req.decoded.role)
next()
else
throw new Error('Sem permissões') //can use a custom error factory to manage better the responses
} catch(err) {
next(error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment