Skip to content

Instantly share code, notes, and snippets.

@tmaclean-LV
Last active September 23, 2021 14:16
Show Gist options
  • Save tmaclean-LV/919886cb2830da6a5710d35abbce46f4 to your computer and use it in GitHub Desktop.
Save tmaclean-LV/919886cb2830da6a5710d35abbce46f4 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();
}
@bishopZ
Copy link

bishopZ commented Mar 15, 2019

This helps a lot. Thank you.

@bishopZ
Copy link

bishopZ commented Mar 15, 2019

fwiw, If you want to turn off an individual field, rather than an entire list, this seems to be working

keystone.list('User').fields.email.__options.noedit = true;

Copy link

ghost commented May 3, 2019

this solution is just for navbar of admin ui ... i did this and i still can access other models via main page : (

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment