Skip to content

Instantly share code, notes, and snippets.

@nemtsov
Created August 23, 2015 02:34
Show Gist options
  • Save nemtsov/33709c7f2aacb6e9a7e0 to your computer and use it in GitHub Desktop.
Save nemtsov/33709c7f2aacb6e9a7e0 to your computer and use it in GitHub Desktop.
/* eslint no-console: 0, new-cap: 0 */
import Acl from 'acl';
import express from 'express';
import bodyParser from 'body-parser';
import {parallel} from 'async';
import AclMongoDBBackend from './backend';
import mongodb from 'mongodb';
mongodb.connect('mongodb://127.0.0.1:27017/acltest', (error, db) => {
if (error) return console.error(error);
const useSingle = true;
const backend = new AclMongoDBBackend(db, 'acl_', useSingle);
const acl = new Acl(backend);
function createUser(id, cb) {
const role = `role_${id}`;
const resource = `/users/${id}`;
parallel([
c => acl.allow(role, resource, 'get', c),
c => acl.allow(role, `${resource}/email`, 'post', c),
c => acl.addUserRoles(id, role, c)
], cb);
}
parallel([
c => createUser('mary', c),
c => createUser('joe', c)
], err => {
if (err) return console.error(err);
console.log('users created');
});
//-------
const app = express();
const users = {
mary: {name: 'Mary'},
joe: {name: 'Joe'}
};
app.use(bodyParser.json());
app.use((req, res, next) => {
req.session = {userId: 'joe'}
next();
});
app.param('userId', (req, res, next, userId) => {
req.user = users[userId];
if (!req.user) res.status(404).json('user not found');
next();
});
app.get('/', (req, res) => {
res.json('ok');
});
app.use(acl.middleware());
app.get('/users/:userId', (req, res) => {
res.json(req.user);
});
app.post('/users/:userId/email', (req, res) => {
req.user.email = req.body;
res.json('ok');
});
app.use((err, req, res, next) => {
if (err.name !== 'HttpError') return next(err);
res.status(err.errorCode).json(err.message);
});
app.listen(3000, () => console.log('on :3000'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment