Skip to content
This repository has been archived by the owner on May 11, 2020. It is now read-only.

Improve tokens managment #12

Merged
merged 4 commits into from
Nov 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions cli/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import rc from 'rc';
import signale from 'signale';
import boxen from 'boxen';
import fs from 'fs';
import omit from 'lodash.omit';

import { questions } from './questions.js';
import config from '../src/config.js';
import config, { getMissingEnvironmentTokens, getMissingTokensMessage } from '../src/config.js';
import { app } from '../src/app.js';

const clearWn = () => {
Expand Down Expand Up @@ -47,12 +48,7 @@ if (!globalConfiguration.config) {
signale.log(`You already have ${apis.length} api.s configured`);
}
const apiConfiguration = await questions.askApiConfiguration();
apis.push({
name: apiConfiguration.name,
url: apiConfiguration.url,
tokenKey: apiConfiguration.tokenKey || 'authorization',
tokenPrefix: apiConfiguration.tokenPrefix || 'Bearer',
});
apis.push(omit(apiConfiguration, ['continue']));
configureApi = apiConfiguration.continue;
}

Expand Down Expand Up @@ -80,13 +76,21 @@ if (!globalConfiguration.config) {

run();
} else {
app.listen(config.proxyPort, () => {
signale.info(`Web Myna is starded on port ${config.proxyPort} in environment ${config.env}`);
});
const missingTokens = getMissingEnvironmentTokens();

if (missingTokens.length) {
const message = getMissingTokensMessage(config, missingTokens);
signale.log(boxen(message, { padding: 1, margin: 1, borderColor: 'red', align: 'center' }));
process.exit();
} else {
app.listen(config.proxyPort, () => {
signale.info(`Web Myna is starded on port ${config.proxyPort} in environment ${config.env}`);
});
}
}

process.on('SIGINT', function() {
clear();
signale.log(chalk.yellow(figlet.textSync('Bye', { horizontalLayout: 'full' })));
process.exit(1);
process.exit();
});
6 changes: 3 additions & 3 deletions cli/questions.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,22 +65,22 @@ export const questions = {
},
{
type: 'confirm',
name: 'needToken',
name: 'requiresAuthentication',
message: 'Does the API need an authentication token?',
},
{
type: 'input',
name: 'tokenKey',
message: 'What is the name of the http header with the authentication token?',
default: 'authorization',
when: value => value.needToken,
when: value => value.requiresAuthentication,
},
{
type: 'input',
name: 'tokenPrefix',
message: 'Should the token be prefixed in the header?',
default: 'Bearer',
when: value => value.needToken,
when: value => value.requiresAuthentication,
},
{
type: 'confirm',
Expand Down
35 changes: 35 additions & 0 deletions docs/references.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
## Functions

<dl>
<dt><a href="#getApiTokenName">getApiTokenName(api)</a> ⇒ <code>string</code></dt>
<dd><p>return the token name as environment variable from api name</p>
</dd>
<dt><a href="#getMissingEnvironmentTokens">getMissingEnvironmentTokens(apis, environment)</a> ⇒ <code>Array.&lt;string&gt;</code></dt>
<dd><p>Returns an array of missing token names from the environment variables</p>
</dd>
<dt><a href="#transformBinaryToUtf8">transformBinaryToUtf8(value)</a> ⇒ <code>string</code></dt>
<dd><p>Transform a Binay (Buffer) into string</p>
</dd>
Expand All @@ -15,6 +21,35 @@
</dd>
</dl>

<a name="getApiTokenName"></a>

## getApiTokenName(api) ⇒ <code>string</code>
return the token name as environment variable from api name

**Kind**: global function
**Returns**: <code>string</code> - The token name

| Param | Type | Description |
| --- | --- | --- |
| api | <code>object</code> | the api object configuration |

**Example**
```js
api name: rick-and-morty => token name RICK_AND_MORTY_TOKEN
```
<a name="getMissingEnvironmentTokens"></a>

## getMissingEnvironmentTokens(apis, environment) ⇒ <code>Array.&lt;string&gt;</code>
Returns an array of missing token names from the environment variables

**Kind**: global function
**Returns**: <code>Array.&lt;string&gt;</code> - an array of missing token name from environment variables

| Param | Type | Description |
| --- | --- | --- |
| apis | <code>Array.&lt;object&gt;</code> | an array of configured apis |
| environment | <code>object</code> | the environment from process.env |

<a name="transformBinaryToUtf8"></a>

## transformBinaryToUtf8(value) ⇒ <code>string</code>
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"figlet": "1.2.4",
"http-proxy-middleware": "0.20.0",
"inquirer": "7.0.0",
"lodash.omit": "4.5.0",
"md5": "2.2.1",
"minimist": "1.2.0",
"nodemon": "1.19.4",
Expand Down
35 changes: 23 additions & 12 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,33 @@ import express from 'express';
import proxy from 'http-proxy-middleware';

import config from './config.js';
import { MODE_RECORDER } from './modes.js';
import { myna } from './myna.js';

export const app = express();

app.get('/', (req, res) => res.json({ message: 'Hello Web Myna' }));
app.get('/', (__, res) => res.json({ message: 'Hello Web Myna' }));

for (const api of config.apis) {
const proxyOptions = {
changeOrigin: true,
proxyTimeout: 5000,
timeout: 5000,
target: api.url,
ignorePath: false,
pathRewrite: path => path.replace(`/${api.name}`, ''),
onProxyReq: proxyReq =>
proxyReq.setHeader(`${api.tokenKey || 'authorization'}`, `${api.tokenPrefix || 'Bearer'} ${api.token}`),
};
app.use(`/${api.name}`, myna(api), proxy(proxyOptions));
if (config.mode === MODE_RECORDER) {
const proxyOptions = {
changeOrigin: true,
proxyTimeout: 5000,
timeout: 5000,
target: api.url,
ignorePath: false,
pathRewrite: path => path.replace(`/${api.name}`, ''),
onProxyReq: proxyReq => {
if (api.requiresAuthentication) {
proxyReq.setHeader(
`${api.tokenKey || 'authorization'}`,
`${api.tokenPrefix || 'Bearer'} ${api.token}`,
);
}
},
};
app.use(`/${api.name}`, myna(api), proxy(proxyOptions));
} else {
app.use(`/${api.name}`, myna(api));
}
}
80 changes: 73 additions & 7 deletions src/config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import signale from 'signale';
import convict from 'convict';
import rc from 'rc';

Expand All @@ -9,19 +8,81 @@ const isPlayerMode = processEnv['WEB_MYNA_MODE'] === MODE_PLAYER || !processEnv[

const globalConfiguration = rc('webmyna', { apis: [], recordingsPath: null });

/**
* return the token name as environment variable from api name
*
* @example api name: rick-and-morty => token name RICK_AND_MORTY_TOKEN
* @function
* @param {object} api the api object configuration
* @returns {string} The token name
*/
export const getApiTokenName = api => {
return typeof api.name === 'string' && !!api.name
? `${api.name.toUpperCase().replace(/-/g, '_')}_TOKEN`
: 'fakeWebMynaTokenName';
};

/**
* Returns an array of missing token names from the environment variables
*
* @function
* @param {object[]} apis an array of configured apis
* @param {object} environment the environment from process.env
* @returns {string[]} an array of missing token name from environment variables
*/
export const getMissingEnvironmentTokens = (apis = globalConfiguration.apis, environment = processEnv) => {
let missingTokens = [];
apis.filter(api => api.requiresAuthentication)
.map(api => getApiTokenName(api))
.map(tokenName => {
if (!environment[tokenName]) {
missingTokens.push(tokenName);
}
});

return missingTokens;
};

/**
* Return readable message about missing tokens in process.env
*
* @function
* @param {object} config with apis
* @param {string[]} missingTokens an array of missing token names
* @returns {string} the message
*/
export const getMissingTokensMessage = (config, missingTokens) => {
const missingApisWithAuthentication = config.apis
.filter(api => missingTokens.includes(getApiTokenName(api)))
.map(api => api.name);
const isPlural = missingApisWithAuthentication.length > 1;
return `
You have declared ${missingApisWithAuthentication.length} api${
isPlural ? 's' : ''
} as requiring an authentication token: ${missingApisWithAuthentication.join(', ')}.

You must therefore declare the following token${isPlural ? 's' : ''} as an environment variable: ${missingTokens
.map(
token => `
=> ${token}`,
)
.join('')}`;
};

convict.addFormat({
name: 'apis',
validate: (apis, schema) => {
if (!Array.isArray(apis)) {
throw new Error('must be of type Array');
}

// if webmyna mode is recorder and api requires an authentication and token is present in environment variables
// we add token from environment variable in config
apis.map((api, index) => {
const tokenName = api.name ? `${api.name.toUpperCase().replace(/-/g, '_')}_TOKEN` : null;
signale.debug(tokenName);
if (tokenName || isPlayerMode) {
const apiToken = processEnv[tokenName];
apis[index].token = isPlayerMode ? 'webMynaPlayerToken' : apiToken;
const tokenName = getApiTokenName(api);
const apiToken = processEnv[tokenName] || null;
if (apiToken && api.requiresAuthentication && !isPlayerMode) {
apis[index].token = apiToken;
}
});

Expand Down Expand Up @@ -49,10 +110,15 @@ const config = convict({
format: 'url',
default: null,
},
requiresAuthentication: {
doc: 'Does the API require authentication or not',
format: Boolean,
default: false,
},
token: {
doc: 'Value of the authorization token to add in http headers',
format: String,
default: null,
default: 'webMynaDefaultToken',
},
tokenKey: {
doc: 'Name of the http header for authentification',
Expand Down
32 changes: 32 additions & 0 deletions src/config.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { getApiTokenName, getMissingEnvironmentTokens } from './config.js';

describe('config', () => {
describe('getApiTokenName', () => {
it('should return "fakeWebMynaTokenName" if api.name is not a string', () => {
const testGetApiTokenName = api => expect(getApiTokenName(api)).toEqual('fakeWebMynaTokenName');
testGetApiTokenName({ name: null });
testGetApiTokenName({ name: undefined });
testGetApiTokenName({ name: 345 });
testGetApiTokenName({ name: { foo: 'bar' } });
testGetApiTokenName({ name: '' });
testGetApiTokenName({});
});

it('should return a well formated token name', () => {
expect(getApiTokenName({ name: 'rick-and-morty' })).toEqual('RICK_AND_MORTY_TOKEN');
});
});

describe('getMissingEnvironmentTokens', () => {
it('should return an array of missing token in precess.env', () => {
const apis = [
{ name: 'api-1', requiresAuthentication: false },
{ name: 'api-2', requiresAuthentication: true },
{ name: 'api-3', requiresAuthentication: true },
];
const processEnv = {};
processEnv['API_2_TOKEN'] = 'foo';
expect(getMissingEnvironmentTokens(apis, processEnv)).toEqual(['API_3_TOKEN']);
});
});
});
18 changes: 13 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import signale from 'signale';
import boxen from 'boxen';

import { app } from './app.js';
import config from './config.js';
import * as appJs from './app.js';
import config, { getMissingEnvironmentTokens, getMissingTokensMessage } from './config.js';

app.listen(config.proxyPort, () => {
signale.info(`Web Myna is starded on port ${config.proxyPort} in environment ${config.env}`);
});
const missingTokens = getMissingEnvironmentTokens();

if (missingTokens.length) {
const message = getMissingTokensMessage(config, missingTokens);
signale.log(boxen(message, { padding: 1, margin: 1, borderColor: 'red', align: 'center' }));
} else {
appJs.app.listen(config.proxyPort, () => {
signale.info(`Web Myna is starded on port ${config.proxyPort} in environment ${config.env}`);
});
}
2 changes: 1 addition & 1 deletion website/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"tagline": "Record then emulate your api.s for testing and development",
"docs": {
"references": {
"title": "References"
"title": "references"
}
},
"links": {
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5751,7 +5751,7 @@ lodash.memoize@^4.1.2:
resolved "https://registry.yarnpkg.com/lodash.memoize/-/lodash.memoize-4.1.2.tgz#bcc6c49a42a2840ed997f323eada5ecd182e0bfe"
integrity sha1-vMbEmkKihA7Zl/Mj6tpezRguC/4=

lodash.omit@^4.5.0:
lodash.omit@4.5.0, lodash.omit@^4.5.0:
version "4.5.0"
resolved "https://registry.yarnpkg.com/lodash.omit/-/lodash.omit-4.5.0.tgz#6eb19ae5a1ee1dd9df0b969e66ce0b7fa30b5e60"
integrity sha1-brGa5aHuHdnfC5aeZs4Lf6MLXmA=
Expand Down