• Stars
    star
    751
  • Rank 60,419 (Top 2 %)
  • Language
    JavaScript
  • Created over 12 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Provides dynamic roles based authorisation for node.js connect and express servers.

Connect Roles

Sponsor

Connect roles is designed to work with connect or express. It is an authorisation provider, not an authentication provider. It is designed to support context sensitive roles/abilities, through the use of middleware style authorisation strategies.

If you're looking for an authentication system I suggest you check out passport.js, which works perfectly with this module.

Build Status Dependency Status NPM version

Installation

$ npm install connect-roles

Usage

var authentication = require('your-authentication-module-here');
var ConnectRoles = require('connect-roles');
var express = require('express');
var app = express();

var user = new ConnectRoles({
  failureHandler: function (req, res, action) {
    // optional function to customise code that runs when
    // user fails authorisation
    var accept = req.headers.accept || '';
    res.status(403);
    if (~accept.indexOf('html')) {
      res.render('access-denied', {action: action});
    } else {
      res.send('Access Denied - You don\'t have permission to: ' + action);
    }
  }
});

app.use(authentication)
app.use(user.middleware());

//anonymous users can only access the home page
//returning false stops any more rules from being
//considered
user.use(function (req, action) {
  if (!req.isAuthenticated()) return action === 'access home page';
})

//moderator users can access private page, but
//they might not be the only ones so we don't return
//false if the user isn't a moderator
user.use('access private page', function (req) {
  if (req.user.role === 'moderator') {
    return true;
  }
})

//admin users can access all pages
user.use(function (req) {
  if (req.user.role === 'admin') {
    return true;
  }
});


app.get('/', user.can('access home page'), function (req, res) {
  res.render('private');
});
app.get('/private', user.can('access private page'), function (req, res) {
  res.render('private');
});
app.get('/admin', user.can('access admin page'), function (req, res) {
  res.render('admin');
});

app.listen(3000);

API

To access all methods, you must construct an instance via:

var ConnectRoles = require('connect-roles');
var roles = new ConnectRoles(options);

options:

  • failureHandler {Function} - a function that takes (req, res) when the user has failed authorisation
  • async {Boolean} - experimental support for async rules
  • userProperty {String} - the property name for the user object on req. Defaults to "user"
  • matchRelativePaths {Boolean} - by default, rules use absolute paths from the root of the application.

roles.use(fn(req, action))

Define an authorisation strategy which takes the current request and the action being performed. fn may return true, false or undefined/null

If true is returned then no further strategies are considered, and the user is granted access.

If false is returned, no further strategies are considered, and the user is denied access.

If null/undefined is returned, the next strategy is considerd. If it is the last strategy then access is denied.

roles.use(action, fn(req))

The strategy fn is only used when the action is equal to action. It has the same behaviour with regards to return values as roles.use(fn(req, action)) (see above).

It is equivallent to calling:

roles.use(function (req, act) {
  if (act === action) {
    return fn(req);
  }
});

N.B. The action must not start with a / character

roles.use(action, path, fn(req))

Path must be an express style route. It will then attach any parameters to req.params.

e.g.

roles.use('edit user', '/user/:userID', function (req) {
  if (req.params.userID === req.user.id) return true;
});

Note that this authorisation strategy will only be used on routes that match path.

It is equivallent to calling:

var keys = [];
var exp = pathToRegexp(path, key);
roles.use(function (req, act) {
  var match;
  if (act === action && match = exp.exec(req.path)) {
    req = Object.create(req);
    req.params = Object.create(req.params || {});
    keys.forEach(function (key, i) {
      req.params[key.name] = match[i + 1];
    });
    return fn(req);
  }
});

roles.can(action) and roles.is(action)

can and is are synonyms everywhere they appear.

You can use these as express route middleware:

var user = roles;

app.get('/profile/:id', user.can('edit profile'), function (req, res) {
  req.render('profile-edit', { id: req.params.id });
})
app.get('/admin', user.is('admin'), function (req, res) {
  res.render('admin');
}

If you want to skip only the current routes, you can also use .here

app.get('/', user.can('see admin page').here, function (req, res, next) {
  res.render('admin-home-page');
});
app.get('/', function (req, res, next) {
  res.render('default-home-page');
});

req.userCan(action) and req.userIs(action)

can and is are synonyms everywhere they appear.

These functions return true or false depending on whether the user has access.

e.g.

app.get('/', function (req, res) {
  if (req.userIs('admin')) {
    res.render('home/admin');
  } else if (req.userCan('login')) {
    res.render('home/login');
  } else {
    res.render('home');
  }
})

user.can(action) and user.is(action)

Inside the views of an express application you may use userCan and userIs which are equivallent to req.userCan and req.userIs

e.g.

<% if (userCan('impersonate')) { %>
  <button id="impersonate">Impersonate</button>
<% } %>

or in jade:

if userCan('impersonate')
  button#impersonate Impersonate

N.B. not displaying a button doesn't mean someone can't do the thing that the button would do if clicked. The view is not where your security should go, but it is important for useability that you don't display buttons that will just result in 'access denied'.

License

MIT

More Repositories

1

redux-optimist

Optimistically apply actions that can be later commited or reverted.
JavaScript
779
star
2

atdatabases

TypeScript clients for databases that prevent SQL Injection
TypeScript
551
star
3

throat

Throttle a collection of promise returning functions
JavaScript
481
star
4

express-route-tester

Attempts to give you an idea of what urls will be accepted by an express route (please fork and extend it)
HTML
408
star
5

browserify-middleware

express middleware for browserify, done right
JavaScript
381
star
6

ajax

Standalone AJAX library inspired by jQuery/zepto
JavaScript
363
star
7

taxi-rank

A JSDom based Selenium Webdriver API
TypeScript
349
star
8

sync-request

Make synchronous web requests with cross platform support.
TypeScript
324
star
9

github-real-names

A plugin for Google Chrome that adds a button to toggle showing real names instead of usernames on GitHub
JavaScript
268
star
10

typescript-json-validator

Automatically generate a validator using JSON Schema and AJV for any TypeScript type.
TypeScript
227
star
11

promisejs.org

a promise website to document and promote
CSS
217
star
12

umd

Universal Module Definition for use in automated build systems
JavaScript
145
star
13

run-browser

The simplest way to run testling type tests in the browser
JavaScript
102
star
14

authentication

Modular, strongly typed, promise based, independent implementations of various authentication protocols
TypeScript
87
star
15

regexplained.co.uk

Regular Expression playgorund inspired by regexper.com and LeaVerou/regexplained
JavaScript
80
star
16

react-code-mirror

CodeMirror component for Facebook React
JavaScript
79
star
17

sync-rpc

Run asynchronous commands synchronously by putting them in a separate process
JavaScript
74
star
18

cabbie

WebDriver for the masses
JavaScript
71
star
19

react-data-fetching-demo

A demo of different ways of doing data fetching in react
JavaScript
65
star
20

react-digit-input

Higher Order Component for passcode/separated digit input.
TypeScript
61
star
21

graphql-schema-gen

Generate JavaScript GraphQL schema from the GraphQL language
JavaScript
57
star
22

ink-console

Render a scrollable terminal log in your ink app
TypeScript
57
star
23

define-form

strongly typed forms using [final-form](https://github.com/final-form/final-form)
TypeScript
49
star
24

acorn-globals

Use acorn to detect global variables in JavaScript
JavaScript
45
star
25

dehumanize-date

Parse dates in all the formats humans like to use.
JavaScript
43
star
26

stop

stop complicating your static website building
JavaScript
41
star
27

tsgen

TypeScript
40
star
28

seed-random

Generate random numbers with a seed, useful for reproducible tests
JavaScript
37
star
29

spawn-sync

Pollyfill v0.12/iojs spawnSync method
JavaScript
35
star
30

QEJS

Asyncronous Embedded JavaScript Templates with Q
JavaScript
31
star
31

redux-wait

A helper to let you wait for redux actions to be processed in a universal app.
JavaScript
30
star
32

jade-brackets

Brackets and code-mirror modes for jade
HTML
29
star
33

regexp

Regular Expression Parser in Pure JS
JavaScript
28
star
34

sync-mysql

Make synchronous queries to a mysql database
JavaScript
28
star
35

barrage

Extensions to streams (as a mixin)
TypeScript
27
star
36

closest

Find the closest parent that matches a selector
JavaScript
27
star
37

is-browser

Test whether you're a component in browser or a package in npm
JavaScript
27
star
38

legacy-encoding

Support as many legacy encodings as possible
JavaScript
25
star
39

sha

Check and get file hashes using sha1, md5 etc....
JavaScript
22
star
40

end-to-end-testing-react-applications

TypeScript
22
star
41

uglify-to-browserify

A transform to make UglifyJS work in browserify
JavaScript
21
star
42

uptime-robot

A simple node.js API for uptime robot
JavaScript
20
star
43

docker-over-ssh

🐳Efficiently transfer docker containers over ssh connections
TypeScript
19
star
44

cancellation

A method for making async operations cancellable
JavaScript
19
star
45

pull-request

All the tools you need to commit to GitHub repos via the API and create pull requests
JavaScript
18
star
46

rfileify

Convert any code using rfile and derivatives so that it supports browserify
JavaScript
17
star
47

unpkg-bot

JavaScript
17
star
48

halting-problem

Solves the halting problem :)
JavaScript
16
star
49

vscode-sql-template-literal

Syntax highlighting for template literals tagged as "sql" in vscode
JavaScript
16
star
50

mandate

The easy way to deploy websites to S3
JavaScript
15
star
51

supermarked

marked with syntax highlighting and LaTeX maths support
JavaScript
15
star
52

character-parser

Parse JavaScript one character at a time to look for snippets in Templates
TypeScript
15
star
53

thread-sleep

A native module for when you just need node to back off for a few milliseconds
JavaScript
13
star
54

type-assertions

Assertions to test your TypeScript types.
TypeScript
13
star
55

N1-GitHub

JavaScript
13
star
56

brackets-globals

Highlight global variables in brackets
JavaScript
13
star
57

opaque-types

Support for opaque and nominal types in typescript via a transformation.
TypeScript
13
star
58

graphql-merge-unmerge

Batch GraphQL queries by merging them and un-merging the results
TypeScript
12
star
59

code-mirror

This is now deprecated, use the official CodeMirror implementation
JavaScript
12
star
60

brcdn.org

Browserify CDN
CSS
12
star
61

typescript-for-react-developers

TypeScript
12
star
62

base64

base64 encode/decode in JavaScript
JavaScript
11
star
63

ascii-math

node.js version of http://www1.chapman.edu/~jipsen/mathml/asciimath.html
JavaScript
11
star
64

github-bot

Everything you need to build a bot for submitting automated pull requests
JavaScript
11
star
65

github-actions-workflow-builder

Build workflows for GitHub Actions using TypeScript
TypeScript
11
star
66

http-basic

low level wrapper around http.request/https.request with caching, redirects, gzip etc.
TypeScript
10
star
67

lsr

Recursive readdir (`ls -R`)
TypeScript
10
star
68

react-abstract-button

TypeScript
8
star
69

submit

form upload and progress api
JavaScript
8
star
70

deviate

Redirecting middlware for express
JavaScript
8
star
71

rfile

require a plain text or binary file in node.js
JavaScript
8
star
72

gethub

Download a github repository to a folder using the .tar.gz bundle
JavaScript
8
star
73

npm-fetch

Fetch npm modules
JavaScript
8
star
74

yieldify

Compiler for ES6 with no runtime component
JavaScript
8
star
75

ert

Express routing templates provides a simple micro-templating syntax for building strings from a template and a request object.
JavaScript
8
star
76

object-explorer

A browser module to create an extensible gui to explore objects
JavaScript
7
star
77

bulletproof-react-workshop

JavaScript
7
star
78

jwt-cache

Cache an async function for generating a JSON Web Token
TypeScript
7
star
79

testit

Because the world needs a simpler testing framework
JavaScript
7
star
80

imsave

Imgur image upload API
JavaScript
7
star
81

QJS

Use the await keyword in node.js code with Q promises.
JavaScript
7
star
82

npm-package-template

πŸ“¦A template for npm packages built in TypeScript
JavaScript
7
star
83

base64-decode

Decode base-64 strings with JavaScript
JavaScript
6
star
84

acorn-has-side-effect

A simple module to check whether an expression has any side effects.
JavaScript
6
star
85

cssdeps

Take some CSS, figure out what files it depends on.
JavaScript
6
star
86

unescape-html

The reverse of escape-html
JavaScript
6
star
87

simple-queue-service

Simple interface to amazon's simple queue service
JavaScript
6
star
88

arrayify

Convert array like items or individual items into arrays
JavaScript
6
star
89

work-token

Simple proof of work generation and verification library based on hashcachgen
JavaScript
6
star
90

component-release

Node.js based git-release for use with component
JavaScript
6
star
91

base64-encode

Encode base-64 strings with JavaScript
JavaScript
6
star
92

svgo-unique-id

svgo plugin to generate unique IDs
JavaScript
6
star
93

interpret

An interpreter for executing un-trusted Esprima Parse Trees with powerful extensibility to aid asynchronous programming
JavaScript
6
star
94

data-action

Bind all sorts of things to html click events
JavaScript
5
star
95

stable-sha1

Get a consistent sha1 hash for a JSON object in both browser and node
JavaScript
5
star
96

babel-live

Live reloading for servers written in node.js using babel
JavaScript
5
star
97

intro-to-react

WIP React Workshop
JavaScript
5
star
98

inline-code

tools to help you inline a variety of function calls in JavaScript code
JavaScript
5
star
99

parameter-reducers

Use reducers to build type safe CLI parameter parsers
TypeScript
5
star
100

booting-nav

Fixes subnav to the top when it scrolls out of view (intended to work with bootstrap)
HTML
5
star