Skip to content
This repository was archived by the owner on Jan 20, 2020. It is now read-only.

Commit fa0c409

Browse files
author
Luciano Nooijen
committed
Knex instance is now passed into controller
1 parent 80b1c4d commit fa0c409

File tree

6 files changed

+70
-66
lines changed

6 files changed

+70
-66
lines changed

controllers/auth.js

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
1-
const { authHelper, knex } = require('../helpers');
1+
const { authHelper } = require('../helpers');
22
const { Users } = require('./');
33

44
// eslint-disable-next-line
55
const { checkPasswordHash, generateJWT, decodeJWT, validateJWT } = authHelper;
66

7-
const getUserByUsername = async username => {
7+
const getUserByUsername = async (knex, username) => {
88
const user = await knex
99
.select('*')
1010
.from('users')
1111
.where({ username });
1212
return user[0];
1313
};
1414

15-
const authenticateUser = async (username, password) => {
16-
const user = await getUserByUsername(username);
15+
const authenticateUser = async (knex, username, password) => {
16+
const user = await getUserByUsername(knex, username);
1717
const passwordHash = user.password;
1818
const correctPassword = await checkPasswordHash(password, passwordHash);
1919
if (correctPassword) {
@@ -22,24 +22,24 @@ const authenticateUser = async (username, password) => {
2222
return false;
2323
};
2424

25-
const generateTokenPayload = async username => {
26-
const user = await getUserByUsername(username);
25+
const generateTokenPayload = async (knex, username) => {
26+
const user = await getUserByUsername(knex, username);
2727
const { id, email } = user;
2828
const tokenPayload = { id, username, email };
2929
return tokenPayload;
3030
};
3131

32-
const generateToken = async (username, password) => {
33-
const isAuthenticated = await authenticateUser(username, password);
32+
const generateToken = async (knex, username, password) => {
33+
const isAuthenticated = await authenticateUser(knex, username, password);
3434
if (!isAuthenticated) {
3535
throw new Error('Incorrect credentials');
3636
}
37-
const payloadData = await generateTokenPayload(username);
37+
const payloadData = await generateTokenPayload(knex, username);
3838
const token = generateJWT(payloadData);
3939
return token;
4040
};
4141

42-
const validateToken = async token => {
42+
const validateToken = async (knex, token) => {
4343
let decodedToken = '';
4444

4545
// Check if token can be decoded, is valid format
@@ -59,7 +59,7 @@ const validateToken = async token => {
5959
// Check if user from payload exists
6060
try {
6161
const tokenUserID = decodedToken.data.id;
62-
const tokenUser = await Users.getUser(tokenUserID);
62+
const tokenUser = await Users.getUser(knex, tokenUserID);
6363
if (!tokenUser) {
6464
return false;
6565
}

controllers/authors.js

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,17 @@
1-
const { knex } = require('../helpers');
2-
3-
const listAuthors = async () => {
1+
const listAuthors = async knex => {
42
const authors = await knex.select('*').from('authors');
53
return authors;
64
};
75

8-
const getAuthor = async id => {
6+
const getAuthor = async (knex, id) => {
97
const author = await knex
108
.select('*')
119
.from('authors')
1210
.where({ id });
1311
return author[0];
1412
};
1513

16-
const addAuthor = async author => {
14+
const addAuthor = async (knex, author) => {
1715
const newAuthorData = {
1816
name: author.name,
1917
image_url: author.image_url,
@@ -26,11 +24,11 @@ const addAuthor = async author => {
2624
return newAuthor[0];
2725
};
2826

29-
const modifyAuthor = async (id, author) => {
27+
const modifyAuthor = async (knex, id, author) => {
3028
// eslint-disable-next-line camelcase
3129
const { name, image_url, role } = author;
3230
const newAuthorData = { name, image_url, role };
33-
const oldAuthorData = getAuthor(id);
31+
const oldAuthorData = getAuthor(knex, id);
3432
const newAuthor = Object.assign({}, { ...oldAuthorData, ...newAuthorData });
3533
const returning = ['id', 'name', 'image_url', 'role'];
3634
const modifiedAuthor = await knex('authors')
@@ -40,7 +38,7 @@ const modifyAuthor = async (id, author) => {
4038
return modifiedAuthor[0];
4139
};
4240

43-
const deleteAuthor = async id =>
41+
const deleteAuthor = async (knex, id) =>
4442
new Promise(resolve => {
4543
knex('users')
4644
.where({ author_id: id })

controllers/users.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
1-
const { knex, authHelper } = require('../helpers');
1+
const { authHelper } = require('../helpers');
22

3-
const listUsers = async () => {
3+
const listUsers = async knex => {
44
const Users = await knex.select('*').from('users');
55
return Users;
66
};
77

8-
const getUser = async id => {
8+
const getUser = async (knex, id) => {
99
const user = await knex
1010
.select('*')
1111
.from('users')
1212
.where({ id });
1313
return user[0];
1414
};
1515

16-
const addUser = async user => {
16+
const addUser = async (knex, user) => {
1717
const passwordHash = await authHelper.generatePasswordHash(user.password);
1818
const newUserData = {
1919
username: user.username,
@@ -38,7 +38,7 @@ const addUser = async user => {
3838
return newUser[0];
3939
};
4040

41-
const modifyUser = async (id, user) => {
41+
const modifyUser = async (knex, id, user) => {
4242
const {
4343
/* eslint-disable camelcase */
4444
username,
@@ -65,7 +65,7 @@ const modifyUser = async (id, user) => {
6565
'password',
6666
'author_id',
6767
];
68-
const oldUserData = getUser(id);
68+
const oldUserData = getUser(knex, id);
6969
const newUser = Object.assign({}, { ...oldUserData, ...newUserData });
7070
const modifiedUser = await knex('users')
7171
.returning(returning)
@@ -74,7 +74,7 @@ const modifyUser = async (id, user) => {
7474
return modifiedUser[0];
7575
};
7676

77-
const deleteUser = async id =>
77+
const deleteUser = async (knex, id) =>
7878
new Promise(resolve =>
7979
knex('users')
8080
.returning(['id'])

tests/controllers/auth.test.ts

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { useTestDatabase } from '../config/index';
2+
import blog from '../config/blog';
23

34
const {
45
getUserByUsername,
@@ -32,15 +33,15 @@ const testUser2 = {
3233

3334
useTestDatabase();
3435

35-
beforeEach(async () => await addUser(testUser));
36+
beforeEach(async () => await addUser(blog, testUser));
3637

3738
describe('Auth Controller', () => {
3839
test('getUserByUsername should return user if it exists', async () => {
3940
expect.assertions(4);
40-
const addedUser = await addUser(testUser2);
41+
const addedUser = await addUser(blog, testUser2);
4142
const expectedId = addedUser.id;
4243
const { username, email, password } = testUser2;
43-
const fetchedUser = await getUserByUsername(username);
44+
const fetchedUser = await getUserByUsername(blog, username);
4445
expect(fetchedUser.id).toBe(expectedId);
4546
expect(fetchedUser.username).toBe(username);
4647
expect(fetchedUser.email).toBe(email);
@@ -51,23 +52,24 @@ describe('Auth Controller', () => {
5152
expect.assertions(2);
5253
const { username, password } = testUser;
5354
const incorrectPassword = 'incorrect_password';
54-
expect(await authenticateUser(username, password)).toBe(true);
55-
expect(await authenticateUser(username, incorrectPassword)).toBe(false);
55+
expect(await authenticateUser(blog, username, password)).toBe(true);
56+
expect(await
57+
authenticateUser(blog, username, incorrectPassword)).toBe(false);
5658
});
5759

5860
test('generateToken should throw error on invalid login', async () => {
5961
expect.assertions(1);
6062
const { username } = testUser;
6163
const incorrectPassword = 'incorrect_password';
62-
await expect(generateToken(username, incorrectPassword))
64+
await expect(generateToken(blog, username, incorrectPassword))
6365
.rejects
6466
.toThrowError('Incorrect credentials');
6567
});
6668

6769
test('generateTokenPayload should create a user object', async () => {
6870
expect.assertions(4);
6971
const { username } = testUser;
70-
const tokenPayload = await generateTokenPayload(username);
72+
const tokenPayload = await generateTokenPayload(blog, username);
7173
expect(typeof tokenPayload).toBe('object');
7274
expect(typeof tokenPayload.id).toBe('number');
7375
expect(typeof tokenPayload.username).toBe('string');
@@ -82,43 +84,43 @@ describe('Auth Controller', () => {
8284
8385
};
8486
const invalidToken = authHelper.generateJWT(invalidPayloadData);
85-
const invalidTokenIsValid = await validateToken(invalidToken);
87+
const invalidTokenIsValid = await validateToken(blog, invalidToken);
8688
expect(invalidTokenIsValid).toBe(false);
8789
});
8890

8991
test('validateToken should fail if token is invalid format', async () => {
9092
expect.assertions(1);
9193
const invalidToken = 'thisisaninvalidtoken';
92-
const invalidTokenIsValid = await validateToken(invalidToken);
94+
const invalidTokenIsValid = await validateToken(blog, invalidToken);
9395
expect(invalidTokenIsValid).toBe(false);
9496
});
9597

9698
test('validateToken should fail if token has expired', async () => {
9799
expect.assertions(1);
98-
const addedUser = await addUser(testUser2);
100+
const addedUser = await addUser(blog, testUser2);
99101
const { username } = addedUser;
100-
const tokenPayloadData = generateTokenPayload(username);
102+
const tokenPayloadData = generateTokenPayload(blog, username);
101103
const date = new Date();
102104
const issuedAt = date.setDate(date.getDate() - jwtExpiresInDays - 1);
103105
const expiredJWT = authHelper.generateJWT(tokenPayloadData, issuedAt);
104-
const invalidTokenIsValid = await validateToken(expiredJWT);
106+
const invalidTokenIsValid = await validateToken(blog, expiredJWT);
105107
expect(invalidTokenIsValid).toBe(false);
106108
});
107109

108110
test('validateToken should pass if token is valid', async () => {
109111
expect.assertions(1);
110112
const { username } = testUser;
111-
const tokenPayloadData = await generateTokenPayload(username);
112-
const validToken = authHelper.generateJWT(tokenPayloadData);
113-
const validTokenIsValid = await validateToken(validToken);
113+
const tokenPayloadData = await generateTokenPayload(blog, username);
114+
const validToken = authHelper.generateJWT(blog, tokenPayloadData);
115+
const validTokenIsValid = await validateToken(blog, validToken);
114116
expect(validTokenIsValid).toBe(true);
115117
});
116118

117119
test('generateToken should give valid tokens', async () => {
118120
expect.assertions(1);
119121
const { username, password } = testUser;
120-
const validToken = await generateToken(username, password);
121-
const validTokenIsValid = await validateToken(validToken);
122+
const validToken = await generateToken(blog, username, password);
123+
const validTokenIsValid = await validateToken(blog, validToken);
122124
expect(validTokenIsValid).toBe(true);
123125
});
124126
});

tests/controllers/authors.test.ts

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { useTestDatabase } from '../config/index';
2+
import blog from '../config/blog';
23

34
const {
45
listAuthors,
@@ -19,13 +20,13 @@ const newAuthor = {
1920
describe('Test if Authors CRUD operations are working correctly', () => {
2021
test('Listing all Authors should return rows', async () => {
2122
expect.assertions(1);
22-
const authors = await listAuthors();
23+
const authors = await listAuthors(blog);
2324
expect(authors.length).toBeGreaterThan(0);
2425
});
2526

2627
test('Fetching a single Author should return an Author', async () => {
2728
expect.assertions(4);
28-
const author = await getAuthor(1);
29+
const author = await getAuthor(blog, 1);
2930
expect(author.id).toBe(1);
3031
expect(typeof author.name).toBe('string');
3132
expect(typeof author.image_url).toBe('string');
@@ -34,18 +35,18 @@ describe('Test if Authors CRUD operations are working correctly', () => {
3435

3536
test('Adding a new Author should add a single row', async () => {
3637
expect.assertions(1);
37-
const authorsBefore = await listAuthors();
38+
const authorsBefore = await listAuthors(blog);
3839
const authorLengthBefore = authorsBefore.length;
39-
return addAuthor(newAuthor).then(async () => {
40-
const authorsAfter = await listAuthors();
40+
return addAuthor(blog, newAuthor).then(async () => {
41+
const authorsAfter = await listAuthors(blog);
4142
const authorLengthAfter = authorsAfter.length;
4243
expect(authorLengthAfter).toBe(authorLengthBefore + 1);
4344
});
4445
});
4546

4647
test('Adding a new Author should return the new Author', async () => {
4748
expect.assertions(5);
48-
const addedAuthor = await addAuthor(newAuthor);
49+
const addedAuthor = await addAuthor(blog, newAuthor);
4950
expect(addedAuthor.id).toBeDefined();
5051
expect(typeof addedAuthor.id).toBe('number');
5152
expect(addedAuthor.name).toBe(newAuthor.name);
@@ -55,12 +56,12 @@ describe('Test if Authors CRUD operations are working correctly', () => {
5556

5657
test('Updating an Author should return the modified data', async () => {
5758
expect.assertions(9);
58-
const originalAuthor = await getAuthor(1);
59+
const originalAuthor = await getAuthor(blog, 1);
5960
expect(originalAuthor.id).toBe(1);
6061
expect(originalAuthor.name).not.toBe(newAuthor.name);
6162
expect(originalAuthor.image_url).not.toBe(newAuthor.image_url);
6263
expect(originalAuthor.role).not.toBe(newAuthor.role);
63-
const modifiedAuthor = await modifyAuthor(1, newAuthor);
64+
const modifiedAuthor = await modifyAuthor(blog, 1, newAuthor);
6465
expect(modifiedAuthor.id).toBeDefined();
6566
expect(typeof modifiedAuthor.id).toBe('number');
6667
expect(modifiedAuthor.name).toBe(newAuthor.name);
@@ -70,8 +71,9 @@ describe('Test if Authors CRUD operations are working correctly', () => {
7071

7172
test('Deleting an Author should return the deleted Author ID', async () => {
7273
expect.assertions(2);
73-
return deleteAuthor(1)
74-
.then(data => expect(data.id).toBe(1))
75-
.then(async () => expect(await getAuthor(1)).toBeUndefined());
74+
const deletedResponse = await deleteAuthor(blog, 1);
75+
const deletedAuthor = await getAuthor(blog, 1);
76+
expect(deletedResponse.id).toBe(1);
77+
expect(deletedAuthor).toBeUndefined();
7678
});
7779
});

0 commit comments

Comments
 (0)