Last active
March 1, 2017 16:51
-
-
Save jacky810124/333a46a5077d2a20fb565515091f2f30 to your computer and use it in GitHub Desktop.
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
const express = require('express') | |
const app = new express() | |
const router = express.Router() | |
const pathToRegexp = require('path-to-regexp') | |
const permission = () => (req, res, next) => { | |
const config = { | |
user: { | |
permissions: [ | |
{ | |
resource: '/api/users/:id/name', | |
methods: ['GET'], | |
action: 'DENY', | |
}, { | |
resource: '/api/users', | |
methods: ['GET', 'POST'], | |
action: 'ALLOW', | |
} | |
] | |
}, | |
admin: { | |
permissions: [ | |
{ | |
resource: '/api/users/:id/name', | |
methods: ['GET'], | |
action: 'ALLOW', | |
} | |
] | |
} | |
} | |
const url = req.url | |
const role = req.user.role | |
const method = req.method.toUpperCase() | |
const permissions = config[role] | |
.permissions | |
.filter(p => url.match(pathToRegexp(p.resource)) !== null) | |
const permission = permissions[0] | |
if (permissions.length === 0) { | |
next() | |
} else { | |
const isMatch = permission.methods.map(m => m.toUpperCase()).indexOf(method) !== -1 | |
const isAllow = permission.action.toUpperCase() === 'ALLOW' | |
if (!(isMatch ^ isAllow)) { | |
next() | |
} else { | |
next({ | |
status: 403, | |
message: 'NOTALLOW' | |
}) | |
} | |
} | |
} | |
router.get('/api/users', (req, res, next) => { | |
res.status(200).json({ message: '/api/users' }) | |
}) | |
router.get('/api/users/:id/name', (req, res, next) => { | |
res.status(200).json({ message: '/api/users/:id/name' }) | |
}) | |
router.post('/api/users', (req, res, next) => { | |
res.status(200).json({ message: 'ok' }) | |
}) | |
router.patch('/api/users', (req, res, next) => { | |
res.status(200).json({ message: 'ok' }) | |
}) | |
app.use((req, res, next) => { | |
req.user = { role: 'user' } | |
next() | |
}) | |
app.use(permission()) | |
app.use(router) | |
app.use((err, req, res, next) => { | |
console.log(err) | |
res.json(err) | |
}) | |
app.listen(3001) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment