Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Mar 15, 2019

This helps a lot. Thank you.

@bishopZ

This comment has been minimized.

Copy link

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;

@mehhrad

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.