From e788510d1687b4236844c7a419b2b7e2113fea99 Mon Sep 17 00:00:00 2001 From: Mark Stosberg Date: Fri, 2 Apr 2021 14:51:21 -0400 Subject: [PATCH] document singleton behavior, how to create new instances and how to share state between multiple instances. Fixes #10 --- README.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/README.md b/README.md index 073c71e..1db7495 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,11 @@ methods below. ### `Manager` +To create a new Manager instance use `new auth.Manager();` + +For many projects this is not required as the single instance exported by default is +sufficient. + #### `role(role, getter)` * **role** `string` - Role name (e.g. 'organization.owner'). @@ -250,6 +255,47 @@ Thrown on configuration error. Passed down the middleware chain when a user is not authorized to perform an action. +## Using `authorized` in large projects + +The `authorized` module exports a singleton object. For large projects, you may want to +to create multiple instances of `authorized` and possibly share code between them. + +For a complete separate instance use `new auth.Manager();`. + +You may also want to add some default entities, roles and actions of your own which then share +with independent instances. Here's a pattern you can use to solve that. + +Create a sub-class which calls an `initialize()` method in the constructorl +and then add custom additions there: + +```javascript +var Manager = require('authorized').Manager; + +// Extend authorized with some roles, entities and actions that are always available. +class CorpAuthorized extends Manager { + constructor(options) { + super(options); + this.initialize(); + } + + initialize() { + const auth = this; + auth.entity('admin', (req,done)=>{ + // Custom logic goes here + return done(); + } + }) +module.exports = CorpAuthorized; + +// ... + +const Manager = require('./path/to/your/subclass'); + +// Each instance now has a unique instance with your default rules. +const auth = new Manager(); + +``` + ## What else? This package is strictly about authorization. For a full-featured