0.0.1 • Published 7 years ago

@bloxite/koa-access-guard v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
7 years ago

Koa DALs

Build Status

Permissions-based access guard for Koa@2

Standard - JavaScript Style Guide

Installation

npm install @bloxite/koa-access-guard --save

Usage

Import guard object

const guard = require('@bloxite/koa-access-guard')
// or in ES6-way
import guard from '@bloxite/koa-access-guard'

This module made for work with koa-router.

Guard#some allows to restrict access only for users who have permissions user or admin:

router.get(
  '/profile', guard.some([ 'user', 'admin' ]),
  () => { /* ... */ }
)

Guard#every allows to restrict access only for users who have permissions user and admin both:

router.get(
  '/admin', guard.every([ 'user', 'admin' ]),
  () => { /* ... */ }
)

Guard#some and Guard#every works very similarly to Array#some and Array#every respectively.

Also you can pass function for permissions validation. Be noted: function will be executed for every user's permission from ctx.state.user.permissions:

router.post(
  '/profile/:id',
  guard.some([ // allowed for "admin" or owner of profile
    'admin',
    (permission, context) =>  // permission name and Koa's context
      context.user.id === context.params.id
  ]),
  () => { /* ... */ }
)

You can use wildcard rules with glob-syntax that provided by minimatch package:

router.put(
  '/posts',
  guard.some([ 'admin', 'moderator:*' ]),
  () => { /* ... */ }
)

Guard is configurable:

import guard from '@bloxite/koa-access-guard'

const myGuard = guard({
  userProperty: 'person', // property from `ctx.state` for store user object
  permissionsProperty: 'scopes', // property for store permissions
  errorConstructor: MyCustomErrorConstructor // custom error that will be thrown
})

router.get(
  '/', myGuard.some(/*...*/),
  () => { /* ... */ }
)

License

MIT License

Copyright (c) 2017 Bloxite

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.