README
Authoritah is an unopinionated, tiny, library for node that provides a convenient API for scrutinizing an object against a set of rules. This is used internally at Coding Blocks for the authorization subsystems of various applications, but is unopinionated enough to be useful in any scenario.
Author
Prajjwal Singh
Usage
Authoritah implements a rule based system, where a rule looks like this:
{ ... } { ... }
Here, both predicate()
and test()
are functions returning booleans. For each
rule where the predicate returns true
for the object under scrutiny(supplied
via respect()
, see below), Authoritah ensures that the corresponding test()
returns a truthy value as well. Note that predicate()
must always be
synchronous.
A sample rule used internally at Coding Blocks looks like this:
const onlyAdminsCanDeleteRecords = httpErrorCode: 401 errorCode: 006)
First, create a context:
const A =
To add the rule:
A
addRule()
also returns a boolean value indicating whether your rule was added
or not.
Finally, ensure every rule passes against object x
with:
// If all your tests are synchronous:A // In case you have one or more async tests:A
This returns a boolean indicating whether every rule passed or not.
To check the number of rules that have been added, use A.ruleCount()
.
To clear all existing rules (useful for switching contexts), use
A.clearRules()
.
Example
const Authoritah = ; let manBearPig = species: "ManBearPig" manFraction: 05 bearFraction: 05 pigFraction: 05 let fakeManBearPig = species: "ManBearPig" manFraction: 01 bearFraction: 01 pigFraction: 08 let notManBearPig = species: "NotManBearPig" // Instantiate a context. You can do this multiple times to create different// contexts for different uses.const A = // Create a Rule for only creatures whose species is "ManBearPig", asserting// that all such creatures should be half man, half bear, and half pig.//// - You can add as many rules as you like.// - A rule will not be added if it lacks the required properties, ie, either a// predicate, a test, or both.A // Test various objects against the registered rules. This only returns true if// ALL rules attached to an object pass.A // => trueA // => falseA // => true, because the rule is only for ManBearPigs // A much more useful method is disrespectedRules(), which returns a list of all// rules that were violated. Sorry about the naming, but the south park// references are more important than code comprehension.A // => []A // => [{ ... }] A 0 errorMessage // => "That's no ManBearPig!" A // => [] // Get the number of registered rules.A // => 1 // Clear all rules, and return the cleared onesA // => [{ ... }, ...]A // => 0
Running Tests
$> yarn test