Created
August 23, 2015 02:34
-
-
Save nemtsov/33709c7f2aacb6e9a7e0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /* 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