Skip to content

Instantly share code, notes, and snippets.

@justinwen
Forked from tmaclean-LV/index.js
Created August 10, 2019 16:21
Show Gist options
  • Save justinwen/1b9e89409d7a72ff4ff57616ff6ebbb1 to your computer and use it in GitHub Desktop.
Save justinwen/1b9e89409d7a72ff4ff57616ff6ebbb1 to your computer and use it in GitHub Desktop.
Control user access to models in Keystone.js
// Place this with the other middleware inclusion in routes/index.js
keystone.pre('admin', middleware.enforcePermissions);
// Place this in routes/middleware.js
/**
Sets navigation and enforces permissions specified in the user models
*/
exports.enforcePermissions = function (req, res, next) {
var nav = {
blog: ['blog', 'tag'],
about: ['page', 'category'],
access: 'users',
};
keystone.set('nav', nav);
if (req.user) {
// This assumes users have a set of boolean fields, "permBlog", "permAbout", etc.
// which control access to these sets of navigation items.
var hideLists = (name, hidden) => keystone.list(name).set('hidden', hidden);
['Blog', 'Tag'].map(list => hideLists(list, !req.user.permBlog));
['Page', 'Category'].map(list => hideLists(list, !req.user.permAbout));
['User'].map(list => hideLists(list, !req.user.permAdmin));
!req.user.permBlog && delete nav.blog;
!req.user.permAbout && delete nav.about;
!req.user.permAccess && delete nav.access;
keystone.nav = keystone.initNav(nav);
}
next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment