Last active
February 6, 2020 20:17
-
-
Save KelvinCampelo/a6b8a8182e5fffd5fc58f2e1002aaedc to your computer and use it in GitHub Desktop.
jwt route protection example node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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