koa-neo4j
Version:
Rapidly create REST APIs, powered by Koa and Neo4j -- batteries included with built-in role based authentication via JWT and reusable backend components
73 lines (59 loc) • 2.3 kB
JavaScript
;Object.defineProperty(exports, "__esModule", { value: true });exports.userIs = exports.userHasAnyOfRoles = exports.checkOwner = exports.checkWith = undefined;
var _preprocess = require('./preprocess');
var _postprocess = require('./postprocess');
var _data = require('./data');
const checkWith = ({
name = 'checkWith',
condition = (params, ctx) => true,
except = (params, ctx) => false } =
{}) =>
new _data.Procedure({
name: name,
preProcess: [
(params, ctx) => [params, except.apply(null, [params, ctx])],
([params, exception], ctx) => {
if (exception)
params.result = true;else
params.result = condition.apply(null, [params, ctx]);
return params;
}] });
// check Hook
// checkOwner
// params before: {resourceIdParamName} <number> | <string> | <Neo4jInt>
// params after: {resourceIdParamName} <Neo4jInt>
/**
* Created by keyvan on 11/26/16.
*/const checkOwner = ({ name = 'checkOwner', resourceIdParamName = 'id',
pattern = '(user)-[:HAS]->(resource)',
except = (params, ctx) => false } =
{}) =>
new _data.Procedure({
name: name,
preProcess: [
(0, _preprocess.parseIds)(resourceIdParamName),
(params, ctx) => [params, except.apply(null, [params, ctx])],
([params, exception], ctx) => {
if (exception)
params.result = true;else
params.cypher = `MATCH ${pattern} WHERE id(user) = ${ctx.user.id} ` +
`AND id(resource) = {${resourceIdParamName}} ` +
'RETURN count(resource) > 0';
return params;
}],
postProcess: _postprocess.fetchOne });
// Use allowedRoles for this functionality
// Made to be used as 'except', e.g.
// checkOwner({ except: userHasAnyOfRoles(['admin', 'reviewer']) })
const userHasAnyOfRoles = roles => (params, ctx) => {
if (!ctx)
throw new Error("'ctx' not passed to procedure");
if (!ctx.user)
throw new Error('user not logged in');
roles = roles.map(role => role.toLowerCase());
for (const role of roles)
if (ctx.user.roles.indexOf(role.toLowerCase()) >= 0)
return true;
return false;
};
const userIs = role => userHasAnyOfRoles([role]);exports.
checkWith = checkWith;exports.checkOwner = checkOwner;exports.userHasAnyOfRoles = userHasAnyOfRoles;exports.userIs = userIs;