Skip to content

Instantly share code, notes, and snippets.

@georgeben
Created September 9, 2022 21:18
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 georgeben/559b5774fe0eabf2c9a5d26bec7b58b8 to your computer and use it in GitHub Desktop.
Save georgeben/559b5774fe0eabf2c9a5d26bec7b58b8 to your computer and use it in GitHub Desktop.
Implementing RBAC authorization
const express = require('express')
const app = express()
app.use(express.json())
// Ideally, roles should be stored in your database (as a table or collection)
const roles = [
{
id: 1,
name: 'Teacher',
permissions: ['create-test', 'score-test']
},
{
id: 2,
name: 'Student',
permissions: ['attend-class']
}
]
function checkPermission(permission) {
return (req, res, next) => {
const sampleUser = {
email: 'bobby.newport@gmail.com',
role: 2
}
// Get the user's role
const role = roles.find((el) => el.id === sampleUser.role);
if (!role.permissions.includes(permission)) {
return res.status(403).json({ message: 'You are not allowed to perform this action.' })
}
next()
}
}
/**
* Before granting a request to create a test, make sure you
* check that the user making the request has the right permissions
*/
app.post('/create-test', checkPermission('create-test'), async (req, res) => {
return res.status(200).json({
message: 'Test created!'
})
})
app.listen(5000, () => console.log('App running'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment