Skip to content

Instantly share code, notes, and snippets.

@samuelkarani
Last active December 16, 2022 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelkarani/43cf6da86bb124bc01d66a870a309042 to your computer and use it in GitHub Desktop.
Save samuelkarani/43cf6da86bb124bc01d66a870a309042 to your computer and use it in GitHub Desktop.
const ROLES = {...}
// middleware
function checkRole(role) {
return (req, res, next) => {
if (req.user.role !== role) {
res.status(401)
return res.send('Not allowed')
}
next()
}
}
app.get('/admin', checkRole(ROLE.ADMIN), ... (req, res) => {
res.send('Admin Page')
})
app.get('/user', checkRole(ROLE.USER), ... (req, res) => {
res.send('User Page')
})
// scoping
const scope = (user, list) => list.filter(item => {
if (user.role === ROLE.ADMIN) return true;
else return item.user.id === user.id)
})
app.get('/', (req, res) => {
res.json(scope(req.user, req.list))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment