Last active
September 23, 2021 14:16
-
-
Save tmaclean-LV/919886cb2830da6a5710d35abbce46f4 to your computer and use it in GitHub Desktop.
Control user access to models in Keystone.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Place this with the other middleware inclusion in routes/index.js | |
keystone.pre('admin', middleware.enforcePermissions); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
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;
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
This helps a lot. Thank you.