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

Commit 3866034

Browse files
author
Luciano Nooijen
committed
Added more validation to validateToken
1 parent 5bba64c commit 3866034

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

controllers/auth.js

+12-1
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,23 @@ const generateToken = async (username, password) => {
4747
};
4848

4949
const validateToken = async token => {
50-
const decodedToken = decodeJWT(token);
50+
let decodedToken = '';
51+
52+
// Check if token can be decoded, is valid format
53+
try {
54+
decodedToken = decodeJWT(token);
55+
} catch (err) {
56+
return false;
57+
}
58+
59+
// Check if token has not expired
5160
try {
5261
validateJWT(token);
5362
} catch (err) {
5463
return false;
5564
}
65+
66+
// Check if user from payload exists
5667
const tokenUserID = decodedToken.data.id;
5768
const tokenUser = await Users.getUser(tokenUserID);
5869
if (!tokenUser) {

tests/controllers/auth.test.ts

+7
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,13 @@ describe('Auth Controller', () => {
8686
expect(invalidTokenIsValid).toBe(false);
8787
});
8888

89+
test('validateToken should fail if token is invalid format', async () => {
90+
expect.assertions(1);
91+
const invalidToken = 'thisisaninvalidtoken';
92+
const invalidTokenIsValid = await validateToken(invalidToken);
93+
expect(invalidTokenIsValid).toBe(false);
94+
});
95+
8996
test('validateToken should fail if token has expired', async () => {
9097
expect.assertions(1);
9198
const addedUser = await addUser(testUser2);

0 commit comments

Comments
 (0)