All Projects → lotivo → sequelize-guard

lotivo / sequelize-guard

Licence: MIT License
An Authorization library for Sequelize.js

Programming Languages

javascript
184084 projects - #8 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to sequelize-guard

sequelize-adapter
Sequelize adapter for Casbin
Stars: ✭ 51 (+96.15%)
Mutual labels:  acl, sequelize, authorization
rbac-tool
Rapid7 | insightCloudSec | Kubernetes RBAC Power Toys - Visualize, Analyze, Generate & Query
Stars: ✭ 546 (+2000%)
Mutual labels:  acl, authorization
nova-permissions
Add Permissions based authorization for your Nova installation via User-based Roles and Permissions. Roles are defined in the database whereas Permissions are defined in the code base.
Stars: ✭ 115 (+342.31%)
Mutual labels:  acl, authorization
dart-casbin
An authorization library that supports access control models like ACL, RBAC, ABAC in Dart/Flutter
Stars: ✭ 30 (+15.38%)
Mutual labels:  acl, authorization
Rbac
Hierarchical Role-Based Access Control for Node.js
Stars: ✭ 254 (+876.92%)
Mutual labels:  acl, authorization
spicedb
Open Source, Google Zanzibar-inspired fine-grained permissions database
Stars: ✭ 3,358 (+12815.38%)
Mutual labels:  acl, authorization
lua-casbin
An authorization library that supports access control models like ACL, RBAC, ABAC in Lua (OpenResty)
Stars: ✭ 43 (+65.38%)
Mutual labels:  acl, authorization
Awesome Iam
👤 Identity and Access Management Knowledge for Cloud Platforms
Stars: ✭ 186 (+615.38%)
Mutual labels:  acl, authorization
browser-acl
Simple acceess control (ACL) library for the browser inspired by Laravel's guards and policies.
Stars: ✭ 36 (+38.46%)
Mutual labels:  acl, authorization
feathers-casl
feathers.js + casl: hooks & channels
Stars: ✭ 25 (-3.85%)
Mutual labels:  acl, authorization
casbin-ex
An authorization library that supports access control models like ACL, RBAC, ABAC in Elixir
Stars: ✭ 37 (+42.31%)
Mutual labels:  acl, authorization
Chi Authz
chi-authz is an authorization middleware for Chi
Stars: ✭ 248 (+853.85%)
Mutual labels:  acl, authorization
Bouncer
Eloquent roles and abilities.
Stars: ✭ 2,763 (+10526.92%)
Mutual labels:  acl, authorization
dynamic-data-and-capabilities
[ARCHIVED] Dynamic Data and Capabilities in IPFS Working Group
Stars: ✭ 57 (+119.23%)
Mutual labels:  acl, authorization
Caddy Authz
Caddy-authz is a middleware for Caddy that blocks or allows requests based on access control policies.
Stars: ✭ 221 (+750%)
Mutual labels:  acl, authorization
caddy-security
🔐 Authentication, Authorization, and Accounting (AAA) App and Plugin for Caddy v2. 💎 Implements Form-Based, Basic, Local, LDAP, OpenID Connect, OAuth 2.0 (Github, Google, Facebook, Okta, etc.), SAML Authentication. MFA/2FA with App Authenticators and Yubico. 💎 Authorization with JWT/PASETO tokens. 🔐
Stars: ✭ 696 (+2576.92%)
Mutual labels:  acl, authorization
core
🔥 Antares Core Implemenation. Most important project layer, this is the heart for your app. ACL, notifiter, console, geoip, areas, utils and many more...
Stars: ✭ 24 (-7.69%)
Mutual labels:  acl, authorization
Think Authz
An authorization library that supports access control models like ACL, RBAC, ABAC in ThinkPHP 6.0 .
Stars: ✭ 155 (+496.15%)
Mutual labels:  acl, authorization
Casbin Server
Casbin as a Service (CaaS)
Stars: ✭ 171 (+557.69%)
Mutual labels:  acl, authorization
objection-authorize
isomorphic, "magical" authorization integration with Objection.js 🎉
Stars: ✭ 71 (+173.08%)
Mutual labels:  acl, authorization

SequelizeGuard

Build Status Coverage Status

An Authorization library for Sequelize.js.

Fast, Easy, Roles & Permissions based Authorization.

  • Fluent, easy to use semantic API.
  • Assign multiple Roles, Permissions to User.
  • Super FAST cache based permission resolution system.
  • Listen for Events related to authorization. Check Events
  • No dependency on Node-acl.

to know more see documentation.

let me know how you feela about this library:


Demo

After installation you can do stuff like

  • Setup
//Assign Role to a user.
user.assignRole('admin');

//assign permission to a role.
guard.init().allow('admin').to(['view', 'edit']).on('blog').commit();

//or if you like one liners
guard.allow('admin', ['view', 'edit'], 'blog');
  • Authorize

by permission

//view blog
user.can('view blog');

//All Actions on blog
user.can('* blog');

//view All Resources, eg. analyst
user.can('view *');

//All Action on All Resources, superadmin
user.can('*');

or by Role

//check if user is editor
user.isA('editor');

//use isAn where you require
user.isAn('admin');

//use isAnyOf to check either of roles
user.isAnyOf(['admin', 'moderator']);

Installation

NPM page

npm i sequelize-guard

or

yarn add sequelize-guard

Make sure, Sequelize is setup in your project. If not, follow Sequelize Getting Started first.

Usage

Getting Started

Migrations

sequelize-guard will automatically register and sync needed schemas.

Or you can use following code in a migration file

var SequelizeGuard = require('sequelize-guard');

module.exports = {
  up: (queryInterface, Sequelize) => {
    return SequelizeGuard.migration.up(queryInterface, Sequelize, options);
  },
  down: (queryInterface, Sequelize) => {
    return SequelizeGuard.migration.down(queryInterface, Sequelize, options);
  },
};

1. Create Sequelize Object

Create sequelize object with your database configuration.

For example we have used default Sequelize setup file for models.

//models/index.js

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize( ... );
}

2. Initialize Sequelize-guard

Initialize SequelizeGuard object after you have already initialized your models.

//Import library
var SequelizeGuard = require('sequelize-guard');

...
//initialize Sequelize
...

//initialize SequelizeGuard & add to db for global use
var guard = new SequelizeGuard(sequelize, options);

db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.guard = guard;  // <---------- Add this line

module.exports = db;

Please Note:

  • Make sure you pass same same options to migration and SequelizeGuard constructor,
  • If you have your own User Model implemented, make sure you pass it during initialization,
    • not required for migrations.

Expert Mode

Options

//defaults
{
    prefix : 'guard_',
    primaryKey : 'id',
    timestamps : false,
    paranoid : false,
    sync: true,
    debug: false,
    userModel: null,
    userPk : 'id', //User Primary Key
    safeGuardDeletes : true,
    userCache: true,
    userCacheTime: 60, // 60
}
  • prefix : custom prefix for for all tables
  • primaryKey : custom primary key for all guard tables (to be implemented) ,
  • timestamps : (bool | false), add timestamps to table
  • paranoid : (bool | false), soft deletes
  • sync: (bool | true), if set to true, database tables will be created without migrations
  • debug: (bool | false), print database queries to console.
  • userModel: (Sequelize Model | null), custom used model you want to use, instead of default User Model.
  • userPk : (string | 'id' ), Primary key for User Model, in case your custom model has primaryKey other than 'id'.
  • safeGuardDeletes : (bool | true), if set to true, role or permissions can't be deleted as long as they are associated with any other data. To remove you must break all other associations (to be tested).
  • userCache : (bool | true), roles of user will be cached, this will allow faster permission resolution and less database connections.
  • userCacheTime : (int | 60), time for which roles of user will be cached (in seconds), this number should be inversely proportional to your user traffic.

Assigning Roles and Permissions

GuardControl API

  • GuardControl is API layer over SequelizeGuard.
  • Makes API calls chainable, which means you can call them in whichever order you prefer. [ exception : commit() ].

We are going to use same instance guard of SequelizeGuard we created during setup.

It's best to learn from examples. So here we will take a basic example.

guard.init().allow('admin').to(['view', 'edit']).on('blog').commit();

(There's a one liner alternative available. Read below in SequelizeAPI)

Looks natural and easy right? Let's break the above example.

1. init()

To initialize an GuardControl call init() method on guard instance. This function returns a brand new instance of GuardControl.

2. allow()

parameter : Role (string)

  • Pass name of role for which you are making control statement.
  • Currently only supports one role at time. (Planning on allowing multiple roles soon).

Note: If you call this multiple times, whatever you passed most recently is considered.

3. to()

parameter : Action(s) (string | array)

  • accepts action as string or array of string.
  • eg. view, edit, update, delete, wildcard (*)

4. on()

parameter : Resource(s) (string | array)

  • pass name of resources as string or array of strings.
  • eg. blog, post, image, article, wildcard(*)

5. commit()

Asynchronous call which saves all the data provided in database, using magic of SequelizeGuard and Sequelize.

  • If permission is already created before, same permission is used.
  • If Role is already created same role is assigned permission given.

Returns : object with properties roles, permission. All the roles and permissions specified (created or old) by this GuardControl statement are returned.

User Model API

SequelizeGuard adds some api calls to User Model that you provide in options. So you can assign roles straight from your user object that is logged in.

  • user.assignRole
  • user.assignRoles
  • user.rmAssignedRoles

SequelizeGuard API

for handling permissions

  • createPerms
  • createPermsBulk
  • findPerms

for handling roles

  • makeRole
  • makeRoles
  • deleteRoles
  • allRoles
  • getRole
  • findRoles

for associations between user/role/permission

  • allow : GuardControl in one line
  • addPermsToRole
  • rmPermsFromRole
  • assignRoles
  • rmAssignedRoles

For More information check SequelizeGuard API Reference.

Authorization

User API

Permission based Authorization

user.can()

parameter : 'action resource' (string) returns : bool

Pass permission you are testing for as follows. returns true if allowed.

//view blogs
user.can('view blogs');

//All Actions on blogs
user.can('* blogs');

//view All Resources, eg. analyst
user.can('view *');

//All Action on All Resources, superadmin
user.can('*');

Role based authorization

You can use following methods to have perform role based authorization.

  • user.isAllOf(roles)
  • user.isAnyOf(roles)
  • user.isA(role)
  • user.isAn(role)

For More information check SequelizeGuard API Reference.

Events

You can listen to following events. They can be helpful for logging or updating user cache

  • onRolesCreated : with created roles
  • onRolesDeleted : with data of deleted roles
  • onPermsCreated : with created permissions
  • onPermsAddedToRole : with data after permissions added
  • onPermsRemovedFromRole : with data after permissions are removed

Road map

  • Make seeders better, see branch dev-seeder for progress.
  • Implement "allow except" kind of permissions.
  • Role priority, which will allow to do things like
    • user.atleast('admin')
    • user.atmost('admin')

Influences

  • Spaties's Laravel-permission, Authorization Library for Laravel.
  • Node-ACL for Node.js

Alternative

  • Node-ACL is versatile library which has support for most ORMs. I actually tried to use that before writing this, but somehow wasn't feeling the power or freedom I wanted. But it is quite popular and mostly used.

Contributions

For docs or tests or even code, feel free to send Pull Requests.

Feel free to create issues.

License

The MIT License (MIT). Please see License File for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].