Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PR - [feature]: Add middlware to retrieve settings #540

Merged
merged 7 commits into from
Aug 7, 2020
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
29 changes: 22 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
"description": "A single-/multi-tenant authentication microservice",
"main": "index.js",
"scripts": {
"test": "cross-env NODE_ENV=test jest",
"test:watch": "cross-env NODE_ENV=test jest --watch",
"test:cover": "cross-env NODE_ENV=test jest --coverage",
"test:ci": "cross-env NODE_ENV=test jest --coverage && shx cat ./coverage/lcov.info",
"test": "cross-env NODE_ENV=test jest --verbose",
"test:watch": "cross-env NODE_ENV=test jest --watch --verbose",
"test:ci": "cross-env NODE_ENV=test jest --coverage --verbose && shx cat ./coverage/lcov.info",
"test:cover": "cross-env NODE_ENV=test jest --coverage --verbose",
"lint": "eslint \"src/**/*.js\"",
"lint:fix": "eslint --fix \"src/**/*.js\"",
"build": "babel src --out-dir dist --delete-dir-on-start --ignore '**/*.test.js'",
Expand Down Expand Up @@ -38,6 +38,7 @@
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-jwt": "^6.0.0",
"express-validator": "^6.6.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.9.27",
"swagger-jsdoc": "^4.0.0",
Expand Down
66 changes: 66 additions & 0 deletions src/middleware/__test__/settings.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import express from "express";
import request from "supertest";
import errorHandler from "../../utils/errorhandler";
import jwt from "jsonwebtoken";
import * as mocks from "../../utils/mocks/settings";
import settingsMiddleware from "../settings";

describe("Settings middleware", () => {
let app;
beforeAll(() => {
process.env.API_SECRET = "secret";
app = express();
app.use(settingsMiddleware);
app.get("/", (req, res) => {
res.json({ projectId: req.projectId });
});
app.use((err, req, res, next) => {
errorHandler(err, req, res, next);
});
});

it("should throw an error if no API key is present", async () => {
const res = await request(app).get("/");
expect(res.status).toBe(401);
});
it("should throw an error if invalid API key is present", async () => {
const res = await request(app)
.get("/")
.set("X-MicroAPI-ProjectKey", "crapKey");
expect(res.status).toBe(401);
expect(res.body.error).toBe("Invalid API key found");
});

it("should throw invalid settings error", async () => {
const mockSettings = jest
.spyOn(mocks, "mockSettings")
.mockImplementation(() => {
return mocks.errorMockSettings;
});

const apiKey = jwt.sign(
{ projectId: 123 },
Buffer.from(process.env.API_SECRET, "base64")
);
const res = await request(app)
.get("/")
.set("X-MicroAPI-ProjectKey", apiKey);
expect(mockSettings).toHaveBeenCalled();
expect(res.status).toBe(400);
expect(res.body.error).toBe("Invalid settings found");

mockSettings.mockRestore();
});

it("should return status code 200 and decoded projectId", async () => {
const apiKey = jwt.sign(
{ projectId: 123 },
Buffer.from(process.env.API_SECRET, "base64")
);
const res = await request(app)
.get("/")
.set("X-MicroAPI-ProjectKey", apiKey);
expect(res.status).toBe(200);
expect(res.body.projectId).toBe(123);
});
});
67 changes: 67 additions & 0 deletions src/middleware/settings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
require("dotenv").config();
import jwt from "jsonwebtoken";
import CustomError from "../utils/customError";
import { parseSettings } from "../utils/settingsParser";
import { mockSettings as fetchSettings } from "../utils/mocks/settings";
const log = require("debug")("log");

export const getProjectId = (apiKey) => {
//verify/decode projectID from API key
const decoded = jwt.verify(
apiKey,
Buffer.from(process.env.API_SECRET, "base64")
);
return decoded.projectId;
};

//get settings from external DB or endpoint
//function might be modified to accomodate both sources
export const getSettings = async (apiKey) => {
//fool linter
log(apiKey);

//mock the request for now with mocksettings
//settings need to come from source
//validate the settings by matching against predefined schema
const settings = parseSettings(fetchSettings(), true);
return settings;
};

const settingsMiddleware = async (req, res, next) => {
/* In multi-tenant app, projectID is retreived from API key in a custom HTTP header
** For now we stick with multi-tenant and we will customize this to cater for **
** single tenancy architecture in time where projectIDs are irrelevant **
** In retrospect, expiry of API keys should be from MicroAPI, **
** so making a request for settings with an invalid API key will be rejected **
*/
try {
// we are calling our custom HTTP header X-MicroAPI-ProjectKey
const apiKey = req.headers["x-microapi-projectkey"];
if (!apiKey) throw new CustomError(401, "No API key found");

//validate apiKey
let projectId;
try {
projectId = getProjectId(apiKey);
} catch (error) {
throw new CustomError(401, "Invalid API key found");
}

// get settings from parent DB/source
const settings = await getSettings(apiKey);
if (settings.errors) {
throw new CustomError(400, "Invalid settings found", settings.errors);
}

//attach setting to request body
req.settings = settings;
req.projectId = projectId;

//pass to next middleware
next();
} catch (error) {
next(error);
}
};

export default settingsMiddleware;
114 changes: 114 additions & 0 deletions src/utils/__test__/settingsParser.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { parseSettings } from "../settingsParser";

describe("Settings Parser test", () => {
it("should return two settings", () => {
const dummySetting = [
{
setting_name: "Setting 1",
setting_type: "String",
setting_key: "setting1",
setting_value: null,
setting_required: false,
},
{
setting_name: "Setting 2",
setting_type: "Number",
setting_key: "setting2",
setting_value: null,
setting_required: false,
},
];
const settings = parseSettings(dummySetting);
expect(Object.keys(settings).length).toBe(2);
});

it("should return two settings and one required error", () => {
const dummySetting = [
{
setting_name: "Setting 1",
setting_type: "String",
setting_key: "setting1",
setting_value: null,
setting_required: true,
},
{
setting_name: "Setting 2",
setting_type: "Number",
setting_key: "setting2",
setting_value: 5,
setting_required: true,
},
];
const settings = parseSettings(dummySetting, true);

expect(Object.keys(settings).length).toBe(3);
expect(settings.errors.length).toBe(1);
});

it("should return two settings, one nested setting and one required error", () => {
const dummySetting = [
{
setting_name: "Setting 1",
setting_type: "String",
setting_key: "setting1",
setting_value: null,
setting_required: true,
},
{
setting_name: "Setting 2",
setting_type: "Number",
setting_key: "setting2",
setting_value: 5,
setting_required: true,
},
{
setting_name: "Setting 3",
setting_type: "Array",
setting_key: "setting3",
setting_required: true,
setting_value: [
{
setting_name: "Setting 4",
setting_type: "Number",
setting_key: "setting4",
setting_value: null,
setting_required: true,
},
{
setting_name: "Setting 5",
setting_type: "String",
setting_key: "setting5",
setting_value: 5,
setting_required: true,
},
],
},
];
const settings = parseSettings(dummySetting, true);

expect(Object.keys(settings.setting3).length).toBe(2);
expect(settings.errors.length).toBe(3);
});

it("should return two settings and one type error one required error", () => {
const dummySetting = [
{
setting_name: "Setting 1",
setting_type: "String",
setting_key: "setting1",
setting_value: 5,
setting_required: true,
},
{
setting_name: "Setting 2",
setting_type: "Number",
setting_key: "setting2",
setting_value: null,
setting_required: true,
},
];
const settings = parseSettings(dummySetting, true);
expect(Object.keys(settings).length).toBe(3);
expect(settings.errors.length).toBe(2);
});
});
3 changes: 2 additions & 1 deletion src/utils/customError.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
export default class CustomError extends Error {
constructor(statusCode, message) {
constructor(statusCode, message, errors) {
super();
this.statusCode = statusCode;
this.message = message;
this.errors = errors;
}
}
2 changes: 2 additions & 0 deletions src/utils/errorhandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ const errorHandler = (err, req, res) => {
res.status(err.statusCode).json({
status: "error",
error: err.message,
errors: err.errors,
});
} else if (err.status) {
res.status(err.status).json({
status: "error",
error: err.message,
errors: err.errors,
});
} else {
res.status(500).json({
Expand Down
Loading