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

NTRNL-450 - Add auth middleware #21

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from 8 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
19 changes: 11 additions & 8 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
PATH_SSL_PRIVATE_KEY=./infrastructure/host/test.key
PATH_SSL_CERTIFICATE=./infrastructure/host/test.cert

PORT=3000
NODE_ENV=development

BASE_URL=http://localhost:3000
CDN_HOST=test
FEATURE_FLAG_ENABLE_AUTH=true
HUMAN=true
LOG_LEVEL=info
NODE_ENV=development
NODE_SSL_ENABLED=false
PATH_SSL_CERTIFICATE=./infrastructure/host/test.cert
PATH_SSL_PRIVATE_KEY=./infrastructure/host/test.key
PORT=3000





LOG_LEVEL=info
HUMAN=true
18 changes: 11 additions & 7 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,16 @@ services:
dockerfile: ./infrastructure/docker/${NODE_ENV}/Dockerfile
ports:
- "${PORT}:3000"
environment:
- NODE_ENV=${NODE_ENV}
- PATH_SSL_PRIVATE_KEY=${PATH_SSL_PRIVATE_KEY}
- PATH_SSL_CERTIFICATE=${PATH_SSL_CERTIFICATE}
- CDN_HOST=${CDN_HOST}
- NODE_SSL_ENABLED=${NODE_SSL_ENABLED}
volumes:
- ./:/app
environment:
- BASE_URL=${BASE_URL}
- CDN_HOST=${CDN_HOST}
- FEATURE_FLAG_ENABLE_AUTH=${FEATURE_FLAG_ENABLE_AUTH}
- HUMAN=${HUMAN}
- LOG_LEVEL=${LOG_LEVEL}
- LOG_LEVEL=${LOG_LEVEL}
- NODE_ENV=${NODE_ENV}
- NODE_SSL_ENABLED=${NODE_SSL_ENABLED}
- PATH_SSL_CERTIFICATE=${PATH_SSL_CERTIFICATE}
- PATH_SSL_PRIVATE_KEY=${PATH_SSL_PRIVATE_KEY}

4 changes: 4 additions & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@ export const SERVICE_NAME = 'Node Prototype';
export const LANDING_PAGE = 'info';
export const NOT_FOUND = 'page-not-found';
export const ERROR_PAGE = 'error';
export const NOT_AVAILABLE = 'not-available';
mel-am marked this conversation as resolved.
Show resolved Hide resolved

// Routing paths
export const LANDING_URL = '/info';

export const INFO_URL = '/info';
export const HEALTHCHECK_URL = '/healthcheck';
export const SERVICE_URL = `${BASE_URL}${LANDING_URL}`;

// Feature Flags
export const FEATURE_FLAG_ENABLE_AUTH = getEnvironmentValue('FEATURE_FLAG_ENABLE_AUTH', 'false');
27 changes: 27 additions & 0 deletions src/middleware/authentication.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { NextFunction, Request, Response } from 'express';
import { log } from '../utils/logger';
import { isFeatureEnabled } from '../utils/isFeatureEnabled';
import * as config from '../config';

export const authentication = (
req: Request,
res: Response,
next: NextFunction
) => {
try {
// if auth is not enabled, render the not available page
if (!isFeatureEnabled(config.FEATURE_FLAG_ENABLE_AUTH)) {
log.infoRequest(req, 'sorry, auth service not available right now');
return res.render(config.NOT_AVAILABLE);
mel-am marked this conversation as resolved.
Show resolved Hide resolved
}

// If auth enabled
log.infoRequest(req, 'some auth here soon!');

next();
} catch (err: any) {
log.errorRequest(req, err);
next(err);
}
};

3 changes: 3 additions & 0 deletions src/utils/isFeatureEnabled.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const isFeatureEnabled = (flag: string) => {
return flag === 'true';
};
8 changes: 8 additions & 0 deletions src/views/not-available.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{% extends "layout.html" %}

{% block content %}
<h1 class="govuk-heading-l">
Sorry, the service is unavailable
</h1>
<p class="govuk-body-m">You will be able to use the service at a later date.</p>
{% endblock %}
92 changes: 92 additions & 0 deletions test/unit/middleware/authentication.middleware.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
jest.mock('../../../src/utils/isFeatureEnabled');
jest.mock('../../../src/utils/logger', () => ({
log: {
infoRequest: jest.fn(),
errorRequest: jest.fn(),
},
}));

import { describe, expect, test, jest, afterEach } from '@jest/globals';
import { Request, Response, NextFunction } from 'express';

import * as config from '../../../src/config';

import { authentication } from '../../../src/middleware/authentication.middleware';
import { log } from '../../../src/utils/logger';
import { isFeatureEnabled } from '../../../src/utils/isFeatureEnabled';

import { GET_REQUEST_MOCK } from '../../mock/data';

const logInfoRequestMock = log.infoRequest as jest.Mock;
const logErrorRequestMock = log.errorRequest as jest.Mock;
const isFeatureEnabledMock = isFeatureEnabled as jest.Mock;

const req = GET_REQUEST_MOCK as Request;
const mockResponse = () => {
const res = {} as Response;
res.render = jest.fn() as any;
return res;
};
const next = jest.fn() as NextFunction;

describe('Authentication Middleware test suites', () => {
let res: any;

beforeEach(() => {
res = mockResponse();
});

afterEach(() => {
jest.resetAllMocks();
});

test('Should call next if auth feature is enabled', () => {
// enable auth flag
isFeatureEnabledMock.mockReturnValue(true);

authentication(req, res, next);

expect(logInfoRequestMock).toHaveBeenCalledTimes(1);
expect(logInfoRequestMock).toHaveBeenCalledWith(
req,
'some auth here soon!'
);
expect(next).toHaveBeenCalledTimes(1);
});

test('should call res.render with not-available view if auth feature is disabled', () => {
// disable auth flag
isFeatureEnabledMock.mockReturnValue(false);

authentication(req, res, next);

expect(logInfoRequestMock).toHaveBeenCalledTimes(1);
expect(logInfoRequestMock).toHaveBeenCalledWith(
req,
'sorry, auth service not available right now'
);
expect(res.render).toHaveBeenCalledTimes(1);
expect(res.render).toHaveBeenCalledWith(config.NOT_AVAILABLE);
});

test('should call next with error object if error is thrown', () => {
// disable auth flag so res.render is called
isFeatureEnabledMock.mockReturnValue(false);

// force an error to be thrown by res.render
const errMsg = 'Error thrown by res.render!';
const resWithError = { ...res };
resWithError.render = jest.fn(() => {
throw new Error(errMsg);
});

authentication(req, resWithError, next);

const errObj = expect.objectContaining({ message: errMsg });

expect(logErrorRequestMock).toHaveBeenCalledTimes(1);
expect(logErrorRequestMock).toHaveBeenCalledWith(req, errObj);
expect(next).toHaveBeenCalledTimes(1);
expect(next).toHaveBeenCalledWith(errObj);
});
});
17 changes: 17 additions & 0 deletions test/unit/utils/isFeatureEnabled.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { describe, test, expect } from '@jest/globals';

import { isFeatureEnabled } from '../../../src/utils/isFeatureEnabled';

describe('isFeaturedEnabled test suites', () => {

test('it should return true boolean if flag passed in is the string "true"', () => {

expect(isFeatureEnabled('true')).toBe(true);
});

test('it should return false if the flag passed in is not the string "true"', () => {

expect(isFeatureEnabled('no')).toBe(false);
});

});
Loading