Created
September 9, 2022 21:18
-
-
Save georgeben/559b5774fe0eabf2c9a5d26bec7b58b8 to your computer and use it in GitHub Desktop.
Implementing RBAC authorization
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
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: '[email protected]', | |
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