Skip to content

Instantly share code, notes, and snippets.

@prettydiff
Created August 24, 2017 09:57
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 prettydiff/4ea3830d3dfe8b22b3ce5c466fc9ce76 to your computer and use it in GitHub Desktop.
Save prettydiff/4ea3830d3dfe8b22b3ce5c466fc9ce76 to your computer and use it in GitHub Desktop.
users.put('/users/:id', (req, res, next) => {
function validateAuthentication(userId) {
if (userId) {
throw Unauthenticated('You have to log in');
}
}
function ValidateOtherPermission(user) {
const hasPermission = checkPermission({
actualRole: user.Role,
requiredPermissions: ['can_update_users', 'can_change_secrets'],
});
if (user.role === "admin" || hasPermission) {
return user;
}
}
validateAuthentication(req.session.userId);
validateUserAuthorization();
validateProtectedRoles(Object.keys(req.body));
fetchUser(req.session.id)
.then(validateUserAuthentication(user))
.then(ValidateOtherPermission(user))
.then(updateUser({id: userId, user: req.body}))
});
function checkUserAuthentication(user, req.body) {
if (user.role === "user" && user.id !== req.params.id) {
throw PermissionError("you are not allowed to update another user");
}
const forbiddenAttributes = ['role', 'foo'];
const requestUserAttributes = Object.keys(req.body);
const hasForbiddenUserAttributes = (intersection(forbiddenAttributes, requestUserAttributes).length > 0);
if (user.role === "user" && hasForbiddenUserAttributes) {
throw PermissionError("you are not allowed to change the role or foo of a user");
}
if (user.role === "user" && user.id !== req.params.id) {
throw PermissionError("you are not allowed to update another user");
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment