<commit_before># jwt-policy

JSON Web Token middleware friendly with Express and Sails.js

[![npm version](https://badge.fury.io/js/jwt-policy.svg)](https://badge.fury.io/js/jwt-policy)

Validates `token` from HTTP request header authorization and sets `req.user`, token is expected to be found at `Authorization: Bearer <token>`.

This module verifies tokens with [node-jsonwebtoken](https://github.com/auth0/node-jsonwebtoken)

## Install

```
$ npm install jwt-policy --save
```

## Usage

### jwtPolicy(options, [callback])

`options`:

* `secret`: is a string containing the secret for decoding token.

Specify callback if you wish to do something with `req.user` or check for possible errors, if callback is not supplied then default behavior will take effect.

### Usage in Sails.js

Default behavior

```javascript
// Will return 401 HTTP status code if any errors occurred.
// policies/jwtAuth.js
module.exports = require('jwt-policy')({ secret: 'my_secret_key' });
```

Override default behavior

```javascript
// policies/jwtAuth.js
module.exports = require('jwt-policy')({
  secret: 'my_secret_key'
}, function(err, req, res, next) {
  if (!err) {
    // user can be found at 'req.user'

    return next();
  }

  return res.status(401).json(err);
});
```

### Usage in Express

Default behavior

```javascript
const jwtPolicy = require('jwt-policy');

app.get('/', jwtPolicy({ secret: 'my_secret_key' }), function(req, res) {
  res.send(req.user);
});
```

Override default behavior

```javascript
const jwtPolicy = require('jwt-policy');

app.use(jwtPolicy({ secret: 'my_secret_key' }, function(err, req, res, next) {
  if (!err) {
    return res.next();
  }

  return res.status(401).json(err);
}));

app.get('/', function(req, res) {
  res.send(req.user);
});
```

## Error handling

### JWTError

Possible thrown errors

| message                                         | code                                 |
| ----------------------------------------------- |:------------------------------------:|
| No Authorization header is present              | `E_AUTHORIZATION_REQUIRED`           |
| Format is :: Authorization: Bearer <token>      | `E_INVALID_AUTHORIZATION_FORMAT`     |
| Authorization token was not found               | `E_AUTHORIZATION_TOKEN_NOT_FOUND`    |
| JSON Web Token provided has expired             | `E_TOKEN_EXPIRED`                    |
| Invalid JSON Web Token provided                 | `E_TOKEN_INVALID`                    |

Suppose `E_TOKEN_EXPIRED` error was thrown

```javascript
app.use(jwtPolicy({ secret: 'my_secret_key' }, function(err, req, res, next) {
  if (err) {
    console.log(err.toJSON());
    /*
      {
        status: 401,
        message: 'JSON Web Token provided has expired',
        code: 'E_TOKEN_EXPIRED'
      }
    */
    
    console.log(err.toString());
    /*
      [JWTError (E_TOKEN_EXPIRED) JSON Web Token provided has expired]
    */
    
    console.trace(err);
    /*
      prints Error Stack since err instanceof Error
    */
  }
}));
```

## Test

```
$ npm test
```<commit_msg>error tables<commit_after># jwt-policy

JSON Web Token middleware friendly with Express and Sails.js

[![npm version](https://badge.fury.io/js/jwt-policy.svg)](https://badge.fury.io/js/jwt-policy)

Validates `token` from HTTP request header authorization and sets `req.user`, token is expected to be found at `Authorization: Bearer <token>`.

This module verifies tokens with [node-jsonwebtoken](https://github.com/auth0/node-jsonwebtoken)

## Install

```
$ npm install jwt-policy --save
```

## Usage

### jwtPolicy(options, [callback])

`options`:

* `secret`: is a string containing the secret for decoding token.

Specify callback if you wish to do something with `req.user` or check for possible errors, if callback is not supplied then default behavior will take effect.

### Usage in Sails.js

Default behavior

```javascript
// Will return 401 HTTP status code if any errors occurred.
// policies/jwtAuth.js
module.exports = require('jwt-policy')({ secret: 'my_secret_key' });
```

Override default behavior

```javascript
// policies/jwtAuth.js
module.exports = require('jwt-policy')({
  secret: 'my_secret_key'
}, function(err, req, res, next) {
  if (!err) {
    // user can be found at 'req.user'

    return next();
  }

  return res.status(401).json(err);
});
```

### Usage in Express

Default behavior

```javascript
const jwtPolicy = require('jwt-policy');

app.get('/', jwtPolicy({ secret: 'my_secret_key' }), function(req, res) {
  res.send(req.user);
});
```

Override default behavior

```javascript
const jwtPolicy = require('jwt-policy');

app.use(jwtPolicy({ secret: 'my_secret_key' }, function(err, req, res, next) {
  if (!err) {
    return res.next();
  }

  return res.status(401).json(err);
}));

app.get('/', function(req, res) {
  res.send(req.user);
});
```

## Error handling

Possible thrown errors

### TokenExtractorError

| message                                         | code                                 |
| ----------------------------------------------- |:------------------------------------:|
| No Authorization header is present              | `E_AUTHORIZATION_REQUIRED`           |
| Format is :: Authorization: Bearer <token>      | `E_AUTHORIZATION_INVALID_FORMAT`     |
| Authorization token was not found               | `E_AUTHORIZATION_TOKEN_NOT_FOUND`    |

### JWTError

| message                                         | code                                 |
| ----------------------------------------------- |:------------------------------------:|
| JSON Web Token provided has expired             | `E_TOKEN_EXPIRED`                    |
| Invalid JSON Web Token provided                 | `E_TOKEN_INVALID`                    |

Suppose `E_TOKEN_EXPIRED` error was thrown

```javascript
app.use(jwtPolicy({ secret: 'my_secret_key' }, function(err, req, res, next) {
  if (err) {
    console.log(err.toJSON());
    /*
      {
        status: 401,
        message: 'JSON Web Token provided has expired',
        code: 'E_TOKEN_EXPIRED'
      }
    */

    console.log(err.toString());
    /*
      [JWTError (E_TOKEN_EXPIRED) JSON Web Token provided has expired]
    */

    console.trace(err);
    /*
      prints Error Stack since err instanceof Error
    */
  }
}));
```

## Test

```
$ npm test
```
{'fraction_non_alphanumeric': 0.17116690352123795, 'fraction_numerical': 0.0041054792357492495, 'mean_word_length': 2.4182406907717215, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 6, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3120317', 'n_tokens_mistral': 1959, 'n_tokens_neox': 1880, 'n_words': 516}