Skip to content

Instantly share code, notes, and snippets.

@mgwedd
Last active April 27, 2023 02:39
Show Gist options
  • Save mgwedd/0476f97426de9c9bad7394418e233cee to your computer and use it in GitHub Desktop.
Save mgwedd/0476f97426de9c9bad7394418e233cee to your computer and use it in GitHub Desktop.
RBAC example for fine grained auth on booklets
app.put('/booklets/:bookletId', async (req, res) => {
const bookletId = req.params.bookletId;
const userId = req.user.sub; // Assuming you've set req.user.sub to the user's ID from the JWT.
// Fetch the user's role for the booklet.
// role could be an enum
const result = await db.query('SELECT role FROM UserBooklets WHERE user_id = $1 AND booklet_id = $2', [userId, bookletId]);
// If there's no role, the user doesn't have any relationship with the booklet.
if (result.rows.length === 0) {
return res.status(403).send('Forbidden');
}
const role = result.rows[0].role;
// Check the user's role.
if (role === 'editor') {
// If the user is an editor, allow the edit.
// Fetch the new booklet content from the request.
const newContent = req.body.content;
// Update the booklet in the database.
await db.query('UPDATE Booklets SET content = $1 WHERE id = $2', [newContent, bookletId]);
res.send('Booklet updated');
} else {
// If the user isn't an editor, deny the request.
res.status(403).send('Forbidden');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment