Access

Allow or deny access on certain resources from your application, e.g.

// register extension
Grown.use(require('@grown/access'));

// overload definition
Grown('Access', {
  access_filter: ctx => {
    // retrieve role from the URL
    const matches = ctx.req.url.match(/[&?]role=(\w+)/);

    if (matches) {
      return matches[1];
    }
  },
});

// setup rules
server.plug([
  Grown.Access.rules({
    roles: [
      'Guest.User.Admin',
    ],
    resources: {
      // this rule will block all requests
      Website: '/**',

      // but only these requests will be allowed
      Public: /^\/(?:login|logout|public)/,
    },
    permissions: {
      Website: {
        // User and its parents' roles get access too!
        User: 'allow',
      },
      Public: 'allow',
    },
  }),
]);

// once Access is plugged on the server
// all new middleware gets protected by default
server.mount(ctx => {
  ctx.res.write('You are welcome!');

  // validate against undefined rules
  return ctx.check('Foo', 'Bar', 'baz')
    .catch(() => {
      ctx.res.write('\nNot here...');
    });
});

Click ▷ RUN above and then try different URLs like /etc or /login below.


Methods mixin

  • check(role, resource[, action]) — Validate given rules through the current connection, returns a promise. If no role is given it'll try to call access_filter to retrieve one.

Public props static

  • resources — Collected resources from rules calls.
  • permissions — Collected permissions from rules calls.

Public methods static

  • $install(ctx) — Used by server.plug calls.
  • $mixins() — Extra Grown.Conn.Builder definitions.
  • rules(config) — Compile given config as access rules and returns a middleware.
  • access_filter(ctx) — When given, it'll be used as described on check. It must be passed through patching the extension.

Private* props static

  • _groups — Graph from collected roles.
  • _ruleset — Collection of compiled rules.

Private* methods static

  • _reduceHandler(handler, permissions) — Check if handler exists within permissions, returns null otherwise.
  • _compileMatch(rule) — Turns a single rule into a middleware callback.
  • _makeMatcher(ruleset) — Iterates the given ruleset and compile each one. It returns a middleware callback.
  • _makeTree(role, groups, property) — Returns a flat representation of the given role in the groups graph, property can be children or parent.
  • _runACL(ctx, role, handlers) — Validate role access through ctx. Given handlers should be an array of single resources and actions. It returns a promise.