# koa-predicate-factory

> generate predicates for koa authorization

Latest version **1.0.1** (published 2016-07-29) · MIT license · 0 weekly downloads

## Install

```sh
npm install koa-predicate-factory
pnpm add koa-predicate-factory
yarn add koa-predicate-factory
bun add koa-predicate-factory
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.1 |
| Published | 2016-07-29 |
| First published | 2016-07-29 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 0 |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Rotem Tamir |
| Maintainers | rotemtam |
| Keywords | koa.js, authorization, node.js |

## Links

- npm: https://www.npmjs.com/package/koa-predicate-factory
- Repository: https://github.com/rotemtam/koa-predicate-factory
- Homepage: https://github.com/rotemtam/koa-predicate-factory#readme
- Issues: https://github.com/rotemtam/koa-predicate-factory/issues
- npm.io page: https://npm.io/package/koa-predicate-factory

## Alternatives

- [@pothos/plugin-authz](https://npm.io/package/@pothos/plugin-authz.md) — 12.4K weekly downloads
- [@bounded-sh/client](https://npm.io/package/@bounded-sh/client.md) — 3.2K weekly downloads
- [@luigi-project/plugin-auth-oauth2](https://npm.io/package/@luigi-project/plugin-auth-oauth2.md) — 2.3K weekly downloads
- [@nocobase/plugin-verification](https://npm.io/package/@nocobase/plugin-verification.md) — 2.0K weekly downloads
- [escher-request](https://npm.io/package/escher-request.md) — 545 weekly downloads

## Recent versions

- 1.0.1 (latest) — 2016-07-29
- 1.0.0 — 2016-07-29

## README

# koa-predicate-factory (WIP)

### Why?

Checking authorization to resources in web-apps usually gets messy.  Your beautiful succint RESTful API ends up looking like it went through deep spaghettization once you're done applying all the auth logic.

Usually, something like:

```js
function *postArticle() {
    try {
      let res = yield Article.create(this.params);
      this.body = {success: true}
    } catch(err) {
      this.status = 400;
      this.body = {err: err}
    }
}
app.use(router.post('/article', createArticle);
```

Turns into:

```js
function *postArticle() {
    let permissions = this.req.user && this.req.user.permissions ? this.req.user.permissions : null;
    if ( permissions && permissions.indexOf('create-article') > -1) {
        try {
          let res = yield Article.create(this.params);
          this.body = {success: true}
        } catch(err) {
          this.status = 400;
          this.body = {err: err}
        }    
    } else {
        this.status = 403;
        this.body = {err: 'Unauthorized'};
    }
}
app.use(router.post('/article', createArticle));
```

What's worse is that you end up redoing this permission checking mess over and over again with small changes.  Great place to use the factory pattern. Wouldn't it be nicer to:

```js
function *postArticle() {
    // .. code ..
}
app.use(router.post('/article', canCreateArticle(postArticle)));
```

### Getting Started

Install:
```bash
npm install koa-predicate-factory
```

Create a predicate:
```js
// predicates.js
'use strict';
const predicateFactory = require('koa-predicate-factory');

function hasValidApiKey() {
    // check something and return a boolean
    return this.request.headers['x-api-key'] == '21GL4hVbxDQz'
}

module.exports = {
    hasValidApiKey: predicateFactory(hasValidApiKey, 403, 'Not authorized');
}
```

Use it:
```js
// index.js
'use strict';

const koa = require('koa')
  , router = require('koa-router')()
  , predicates = require('./predicates')
  ;

var app = koa();

app.use(router.routes())
   .use(router.allowedMethods())
   ;

router.get('/resource', predicates.hasValidApiKey(getResource));

function *getResource() {
    this.body = 'Hello, world!';
}

app.listen(8000);
```

### API

#### predicateFactory(compareFn, errorCode, errorMessage)

Parameters

* __compareFn__ - a function that return true if the request should be processed
* __errorCode__ - an HTTP code to return if the check fails, i.e 403, 401, etc
* __errorMessage__ - if the check fails, this error message will be returned to
the user like ```{"message": "<errorMessage>"}```

Returns: function

__predicateFactory__ returns a function which you can use to wrap your controller methods to decorate them with the permissions checking functionality.

__Example__

```js
let isLoggedIn = predicateFactory(function() { /* ... */}, 401, 'Must be logged in');
app.use(isLoggedIn(controllers.home))
```

---
_Source: https://npm.io/package/koa-predicate-factory · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
