Skip to content

Instantly share code, notes, and snippets.

@timboslice69
Created April 27, 2015 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save timboslice69/8bf205a0d4121722d515 to your computer and use it in GitHub Desktop.
Save timboslice69/8bf205a0d4121722d515 to your computer and use it in GitHub Desktop.
Role based security in KeystoneJS
var keystone = require('keystone'),
// pull in the schemaPermissions lib
// rootRequire is a custom function that fixes the path to always be from the root of the application
schemaPermissions = rootRequire('lib/schemaPermissions'),
Types = keystone.Field.Types;
/**
* Page Model
* ==========
*/
var Page = new keystone.List('Page', {
map: { name: 'name' },
autokey: { path: 'slug', from: 'name', unique: true },
plural: 'Pages'
});
Page.add(
{
name: {
type: String,
required: true
}
},
'Content', {
title: {
type: String,
required: true,
initial: true
},
subtitle: {
type: String
},
ingress: {
type: Types.Textarea,
collapse: true
},
body: {
type: Types.Textarea,
collapse: true
}
},
'Publishing', {
state: {
type: Types.Select,
options: 'draft, published, archived',
default: 'draft',
index: true
},
active: {
type: Types.Datetime,
default: Date.now
},
expires: {
type: Types.Datetime
}
}
);
// Use the schemaPermissions publish function on save hook (save hook is always called in keystoneJS)
Page.schema.pre('save', schemaPermissions.publish);
/**
* User Model
* ==========
*/
var User = new keystone.List('User');
User.add(
{
name: {
type: Types.Name,
required: true,
index: true
},
email: {
type: Types.Email,
initial: true,
required: true,
index: true
},
password: {
type: Types.Password,
initial: true,
required: true
}
},
'Permissions', {
isAdmin: {
type: Boolean,
label: 'Can access Keystone',
index: true
},
role: {
type: Types.Select,
options: 'editor, publisher, admin',
default: 'editor',
required: true,
index: true
}
}
);
var keystone = require('keystone'),
middleware = require('./middleware'),
importRoutes = keystone.importer(__dirname);
// Common Middleware
keystone.pre('routes', middleware.initLocals);
// Use the globaliseUser middleware
keystone.pre('routes', middleware.globaliseUser);
keystone.pre('render', middleware.flashMessages);
// Import Route Controllers
var routes = {
views: importRoutes('./views')
};
// Setup Route Bindings
exports = module.exports = function(app) {
// routes go in here
}
/*
You need to be able to access the logged in user to be able to check their role
so we need some middleware to attach the user into the global scope.
*/
/**
* adds the request user object to the global scope
* @param req
* @param res
* @param next
*/
exports.globaliseUser = function(req, res, next){
if (req.user) global.__user = req.user;
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment