aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTom Harley2018-03-07 15:40:49 +0000
committerTom Harley2018-03-07 15:40:49 +0000
commitc8a418113af37cdca5497df788e62493bf947877 (patch)
treeb5531c1715b983d6d7f6a1385e20cca86803317a
parentMerge branch 'trh/pm' into development (diff)
parent... (diff)
downloadmedicine-c8a418113af37cdca5497df788e62493bf947877.tar.gz
medicine-c8a418113af37cdca5497df788e62493bf947877.zip

Merge remote-tracking branch ‘origin/testing-middleware’ into development

-rw-r--r--.gitlab-ci.yml10
-rw-r--r--package.json3
-rwxr-xr-xrunmepostgres.sh6
-rw-r--r--src/app.ts2
-rw-r--r--src/auth.ts9
-rw-r--r--src/db/initPostgresDB.ts2
-rw-r--r--src/logger.ts1
-rw-r--r--test/integration/auth.routes.test.ts126
-rw-r--r--test/integration/index.routes.test.ts7
-rw-r--r--test/integration/protocol.routes.test.ts53
10 files changed, 158 insertions, 61 deletions
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index d4ba66e..cdf3960 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -1,9 +1,17 @@
image: node:9.1.0
services:
- postgres:10.0
+
cache:
untracked: true
+variables:
+ POSTGRES_DB: nice_marmot
+ POSTGRES_USER: admin
+ POSTGRES_PASSWORD: ""
+ POSTGRES_HOST: postgres
+
+
stages:
- build
- test
@@ -17,7 +25,7 @@ install:
mocha:
stage: test
script:
- - yarn test
+ - yarn test:routes:index
lint:
stage: test
diff --git a/package.json b/package.json
index 81c2232..ea63480 100644
--- a/package.json
+++ b/package.json
@@ -9,7 +9,10 @@
"test:unit": "mocha --reporter spec -r ts-node/register './test/**/*.unit.test.ts'",
"test:db": "mocha --reporter spec -r ts-node/register './test/**/*database.unit.test.ts'",
"test:routes:auth": "mocha --reporter spec -r ts-node/register './test/**/*auth.routes.test.ts'",
+ "test:routes:index": "mocha --reporter spec -r ts-node/register './test/**/*index.routes.test.ts'",
+ "test:routes:protocol": "mocha --reporter spec -r ts-node/register './test/**/*protocol.routes.test.ts'",
"docs": "typedoc --out 'docs' --readme 'README.md' --name 'St Andrews Junior Honours 2017/18 - Team BE4' --module commonjs --target ES6 --exclude '*.test.ts' --excludeExternals --includeDeclarations --ignoreCompilerErrors --disableOutputCheck 'src'",
+ "run:postgres": "pg_ctl start",
"start": "ts-node src/index.ts",
"lint": "tslint --fix --force -p './tsconfig.json'",
"lint:tests": "tslint --fix --force ./test/**/*",
diff --git a/runmepostgres.sh b/runmepostgres.sh
index dfa5764..d049a8e 100755
--- a/runmepostgres.sh
+++ b/runmepostgres.sh
@@ -2,9 +2,9 @@
PGDIR=${1-"$HOME/pg"}
-read -p "Press [Enter] key to start Postgres (will already be running if you just got it) use ctl+c to cancel";
+# read -p "Press [Enter] key to start Postgres (will already be running if you just got it) use ctl+c to cancel";
echo "> Starting Server";
"$PGDIR/postgres/bin/pg_ctl" -D "$PGDIR/postgres/data/" -l POSTGRES_logfile start;
-echo "> Conecting as admin user: " + ${USER};
-"$PGDIR/postgres/bin/psql" -U ${USER} postgres;
+# echo "> Conecting as admin user: " + ${USER};
+# "$PGDIR/postgres/bin/psql" -U ${USER} postgres;
diff --git a/src/app.ts b/src/app.ts
index bcb29ca..8c55faa 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -4,7 +4,7 @@ import * as expressJwt from 'express-jwt';
import * as logger from 'morgan';
import * as passport from 'passport';
-import { unauthorisedErr, isAdmin, default as authRouter } from './auth';
+import { default as authRouter, unauthorisedErr } from './auth';
import { RequestError, errorHandler } from './errors/errorware';
import FileRouter from './FileRouter';
diff --git a/src/auth.ts b/src/auth.ts
index 7bc2945..57c375a 100644
--- a/src/auth.ts
+++ b/src/auth.ts
@@ -3,9 +3,9 @@ import { NextFunction, Request, Response, Router } from 'express';
import * as jwt from 'jsonwebtoken';
import * as passport from 'passport';
import { Strategy } from 'passport-local';
+import { default as Project } from './db/model/Project';
import { default as User } from './db/model/User';
import { default as UserGroup } from './db/model/UserGroup';
-import { default as Project } from './db/model/Project';
import { Errorware } from './errors/errorware';
@@ -109,7 +109,6 @@ export class AuthRouter {
next();
}
-
/**
* Used to configure Passport to use the custom authentication strategy.
*/
@@ -157,9 +156,7 @@ export class AuthRouter {
*/
export const unauthorisedErr: Errorware =
(err: Error, req: Request, res: Response, next: NextFunction): void => {
- console.log('fffff');
if (err.name === 'UnauthorizedError') {
- console.log('efewfwf');
return next(new RequestError(
401, 'not_authorised',
'user does not have correct authorisation for task'
@@ -178,7 +175,7 @@ export const unauthorisedErr: Errorware =
*/
export const isAdmin: any =
(req: Request, res: Response, next: NextFunction): void => {
- var isAdmin: boolean = req.user.object.userGroups.some((x: UserGroup): boolean => x.name === 'admin');
+ let isAdmin: boolean = req.user.object.userGroups.some((x: UserGroup): boolean => x.name === 'admin');
if (!isAdmin) {
next(new RequestError(
@@ -188,7 +185,7 @@ export const isAdmin: any =
return;
}
next();
-}
+};
export default new AuthRouter().router;
///////////////////////////////////////////////////
diff --git a/src/db/initPostgresDB.ts b/src/db/initPostgresDB.ts
index eb979f4..b6844d9 100644
--- a/src/db/initPostgresDB.ts
+++ b/src/db/initPostgresDB.ts
@@ -1,6 +1,6 @@
import * as Sequelize from 'sequelize';
const gres: Sequelize.Sequelize = new Sequelize(
- 'postgres://admin:eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af@localhost:5432/be4',
+ 'postgres://admin:eprprJacR0hBpmWvs5IDJZTnjRAY2gM3tSm0b1af@postgres:5432/be4',
{
operatorsAliases : false
}
diff --git a/src/logger.ts b/src/logger.ts
index f598cd5..953a341 100644
--- a/src/logger.ts
+++ b/src/logger.ts
@@ -4,7 +4,6 @@ import * as colors from 'colors/safe';
import * as winston from 'winston';
import { files } from './files';
-import { profiler } from './profiler';
type LogLevel = 'critical' | 'error' | 'warning' | 'security' | 'info';
diff --git a/test/integration/auth.routes.test.ts b/test/integration/auth.routes.test.ts
index f8265a9..888883f 100644
--- a/test/integration/auth.routes.test.ts
+++ b/test/integration/auth.routes.test.ts
@@ -6,7 +6,6 @@
import * as chai from 'chai';
const expect: Chai.ExpectStatic = chai.expect;
import { default as seq } from '../../src/db/orm';
-import request = require('supertest');
import { default as User } from '../../src/db/model/User';
// Chai-http must be imported this way:
@@ -20,6 +19,20 @@ import 'mocha';
import * as App from '../../src/app';
const app = App.TestApp();
+const badRequestErr =
+ { status: 'error',
+ error: 'invalid_request',
+ error_description: 'Missing parameters' };
+const unsupportedGrantTypeErr =
+ { status: 'error',
+ error: 'unsupported_grant_type',
+ error_description: 'invalid grant type' }
+const authorisationErr =
+ { status: 'error',
+ error: 'not_authorised',
+ error_description: 'user does not have correct authorisation for task' }
+
+
const bobbyCredentials = {
username: 'bobby',
password: 'tables',
@@ -28,15 +41,12 @@ const bobbyCredentials = {
let bobbyToken: string;
-async function addUser(credentials: any, done: any) {
- await seq.authenticate();
+async function resetDatabase(done: any){
await seq.sync({
force: true
});
-
- const u: string = credentials.username
- const p: string = credentials.password
- console.log(u + " " + p)
+ const u: string = bobbyCredentials.username
+ const p: string = bobbyCredentials.password
const newUser: User = new User({
username: u,
@@ -47,50 +57,112 @@ async function addUser(credentials: any, done: any) {
done();
}
+async function setupDatabase(done: any) {
+ await seq.authenticate();
+ await seq.sync({
+ force: true
+ });
+ done();
+}
+
// Add user
-before(function(done: any) {
- addUser(bobbyCredentials, done);
+before((done: any) => {
+ setupDatabase(done);
});
describe('authentication', () => {
- context('invalid authentication', () => {
+ context('invalid password authentication', () => {
it('should reject invalid usernames', () => {
- request.agent(app)
+ chai.request(app)
.post('/cs3099group-be-4/login')
.send({...bobbyCredentials, username: 'invalid'})
- .end(function(err, res) {
- expect(err).to.not.be.undefined;
+ .then((res) => {
expect(res).to.have.status(401);
});
});
it('should reject invalid passwords', () => {
- request.agent(app)
+ chai.request(app)
.post('/cs3099group-be-4/login')
- .send({...bobbyCredentials, password: 'invalid'})
- .end(function(err, res) {
- expect(err).to.not.be.undefined;
+ .send({...bobbyCredentials, password: 'asasasas'})
+ .then((res) => {
expect(res).to.have.status(401);
});
});
it('should reject invalid grant_type', () => {
- request.agent(app)
+ chai.request(app)
.post('/cs3099group-be-4/login')
.send({...bobbyCredentials, grant_type: 'invalid'})
- .end(function(err, res) {
- expect(err).to.not.be.undefined;
- expect(res).to.have.status(400);
+ .catch((reason) => {
+ expect(reason.response.body).to.eql(unsupportedGrantTypeErr);
+ });
+ });
+ it('should reject empty usernames', () => {
+ chai.request(app)
+ .post('/cs3099group-be-4/login')
+ .send({...bobbyCredentials, username: ''})
+ .catch((reason) => {
+ expect(reason.response.body).to.eql(badRequestErr);
+ });
+ });
+ it('should reject empty passwords', () => {
+ chai.request(app)
+ .post('/cs3099group-be-4/login')
+ .send({...bobbyCredentials, password: ''})
+ .catch((reason) => {
+ expect(reason.response.body).to.eql(badRequestErr);
});
});
- })
- context('valid authentication', () => {
+ it('should reject empty grant_type', () => {
+ chai.request(app)
+ .post('/cs3099group-be-4/login')
+ .send({...bobbyCredentials, grant_type: ''})
+ .catch((reason) => {
+ expect(reason.response.body).to.eql(badRequestErr);
+ });
+ });
+ });
+ context('valid password authentication', () => {
+ before((done: any) => {
+ resetDatabase(done);
+ });
it('should accept correct credentials', () => {
- request.agent(app)
+ chai.request(app)
.post('/cs3099group-be-4/login')
.send(bobbyCredentials)
- .end(function(err, res) {
- expect(err).to.be.undefined;
+ .then((res) => {
expect(res).to.have.status(200);
});
});
- })
+ });
+ context('token authentication', () => {
+ let bobbyToken: string;
+ before((done: any) => {
+ resetDatabase(() => {
+ chai.request(app)
+ .post('/cs3099group-be-4/login')
+ .send(bobbyCredentials)
+ .end((err, res) => {
+ if (err) { throw err; }
+ bobbyToken = res.body.access_token;
+ done();
+ });
+ });
+ });
+ it('should reject invalid tokens', () => {
+ return chai.request(app).get('/')
+ .set('Authorization', 'Bearer ' + 'invalid')
+ .then((res) => {
+ expect(res).to.have.status(401);
+ }).catch((reason) => {
+ expect(reason.response.body).to.eql(authorisationErr);
+ });
+ });
+ it('should accept valid tokens', () => {
+ return chai.request(app).get('/')
+ .set('Authorization', 'Bearer ' + bobbyToken)
+ .then((res) => {
+ expect(res).to.have.status(200);
+ });
+ });
+ });
});
diff --git a/test/integration/index.routes.test.ts b/test/integration/index.routes.test.ts
index 9ddd1de..70671d8 100644
--- a/test/integration/index.routes.test.ts
+++ b/test/integration/index.routes.test.ts
@@ -8,7 +8,6 @@ const expect: Chai.ExpectStatic = chai.expect;
const should = chai.should();
import * as ex from 'express';
import { default as seq } from '../../src/db/orm';
-import request = require('supertest');
import { default as User } from '../../src/db/model/User';
// Chai-http must be imported this way:
@@ -30,7 +29,7 @@ const userCredentials: Object = {
let token: string;
-async function addUser(done: any) {
+async function startDatabase(done: any) {
await seq.authenticate();
await seq.sync({
force: true
@@ -47,7 +46,7 @@ async function addUser(done: any) {
// Add user
before(function(done: any) {
- addUser(done);
+ startDatabase(done);
});
describe('routes : index', () => {
@@ -61,7 +60,7 @@ describe('routes : index', () => {
context('with authentication', () => {
before(function(done) {
- request.agent(app)
+ chai.request(app)
.post('/cs3099group-be-4/login')
.send(userCredentials)
.end(function(err, res) {
diff --git a/test/integration/protocol.routes.test.ts b/test/integration/protocol.routes.test.ts
index 9b152fc..863bec9 100644
--- a/test/integration/protocol.routes.test.ts
+++ b/test/integration/protocol.routes.test.ts
@@ -5,7 +5,6 @@ const expect: Chai.ExpectStatic = chai.expect;
chai.use(require('chai-http'));
import 'mocha';
import forEach = require('mocha-each');
-import request = require('supertest');
import * as App from '../../src/app';
import * as ex from 'express';
@@ -37,47 +36,67 @@ const errorResponseTemplate: Template = {
type MochaForEachInput = [ string, string, Template, number ];
-const userCredentials: Object = {
+const bobbyCredentials = {
username: 'bobby',
- password: 'pass',
+ password: 'tables',
grant_type: 'password'
};
-const authenticatedUser = request.agent(app);
-let token: string;
+let bobbyToken: string;
-async function addUser(done: any) {
- await seq.authenticate();
+async function resetDatabase(done: any){
await seq.sync({
force: true
});
+ const u: string = bobbyCredentials.username
+ const p: string = bobbyCredentials.password
const newUser: User = new User({
- username: 'bobby',
- password: 'pass',
+ username: u,
+ password: p,
userGroups: []
});
await newUser.save();
done();
}
+async function setupDatabase(done: any) {
+ await seq.authenticate();
+ await seq.sync({
+ force: true
+ });
+ done();
+}
+
// Add user
-before(function(done: any) {
- addUser(done);
+before((done: any) => {
+ setupDatabase(() => {
+ resetDatabase(() => {
+ chai.request(app)
+ .post('/cs3099group-be-4/login')
+ .send(bobbyCredentials)
+ .end((err, res) => {
+ if (err) { throw err; }
+ bobbyToken = res.body.access_token;
+ done();
+ });
+ });
+ });
+
});
describe('routes : errors', () => {
describe('GET invalid routes', function() {
it('should have response code 404', () => {
return chai.request(app).get('/invalid/route')
- .set('Authorization', 'Bearer ' + token)
+ .set('Authorization', 'Bearer ' + bobbyToken)
.catch(function(err: any) {
expect(err.status).to.equal(404);
});
});
it('should conform to the error protocol', function() {
return chai.request(app).get('/invalid/route')
- .set('Authorization', 'Bearer ' + token)
+ .set('Authorization', 'Bearer ' + bobbyToken)
.catch(function(err: any) {
match(errorResponseTemplate)(err.response.body).should.be.true;
});
@@ -218,7 +237,7 @@ describe('routes : protocol', () => {
const request: ChaiHttp.Request = method === 'get'
? chai.request(app).get(base + path)
: chai.request(app).post(base + path);
- request.set('Authorization', 'Bearer ' + token);
+ request.set('Authorization', 'Bearer ' + bobbyToken);
return request.then((res: ChaiHttp.Response) => {
expect(res.type).to.equal('application/json');
}).catch(function(err: any) {
@@ -231,7 +250,7 @@ describe('routes : protocol', () => {
const request: ChaiHttp.Request = method === 'get'
? chai.request(app).get(base + path)
: chai.request(app).post(base + path);
- request.set('Authorization', 'Bearer ' + token);
+ request.set('Authorization', 'Bearer ' + bobbyToken);
return request.then((res: ChaiHttp.Response) => {
expect(res).to.have.status(res_code);
}).catch(function(err: any) {
@@ -244,7 +263,7 @@ describe('routes : protocol', () => {
const request: ChaiHttp.Request = method === 'get'
? chai.request(app).get(base + path)
: chai.request(app).post(base + path);
- request.set('Authorization', 'Bearer ' + token);
+ request.set('Authorization', 'Bearer ' + bobbyToken);
return request.then((res: ChaiHttp.Response) => {
match(responseTemplate, JSON.parse(res.body)).shoul.be.true;
}).catch(function(err: any) {
@@ -255,7 +274,7 @@ describe('routes : protocol', () => {
'the response for %s %s should conform to its specific response protocol',
(method: string, path: string, temp: Template, res_code: number) => {
if (method === 'get' && temp != null) {
- return chai.request(app).get(base + path).set('Authorization', 'Bearer ' + token)
+ return chai.request(app).get(base + path).set('Authorization', 'Bearer ' + bobbyToken)
.then((res: ChaiHttp.Response) => {
match(temp)(JSON.parse(res.body)).should.be.true;
}).catch(function(err: any) {