From 6b0e85996e2e4fbc421af13a608794c3e4086302 Mon Sep 17 00:00:00 2001 From: Francis Li Date: Fri, 29 Mar 2024 15:42:04 -0700 Subject: [PATCH] Add auth tests --- server/routes/api/v1/auth/index.js | 2 +- server/test/fixtures/db/User.yml | 2 +- server/test/routes/api/v1/auth.test.js | 29 +++++++++++++++++++++++++- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/server/routes/api/v1/auth/index.js b/server/routes/api/v1/auth/index.js index e97b148..3089d10 100644 --- a/server/routes/api/v1/auth/index.js +++ b/server/routes/api/v1/auth/index.js @@ -37,7 +37,7 @@ export default async function (fastify, _opts) { if (!user) { return reply.notFound(); } - const result = await bcrypt.compare(password, user.password); + const result = await bcrypt.compare(password, user.hashedPassword); if (!result) { return reply.unauthorized(); } diff --git a/server/test/fixtures/db/User.yml b/server/test/fixtures/db/User.yml index 16c7b17..77d4960 100644 --- a/server/test/fixtures/db/User.yml +++ b/server/test/fixtures/db/User.yml @@ -3,6 +3,6 @@ items: user1: firstName: Admin lastName: User - email: admin.user@gmail.com + email: admin.user@test.com role: ADMIN hashedPassword: $2b$10$ICaCk3VVZUCtO9HySahquuQusQhEnRpXHdzxaceUUJPk0DTwN2e/W # test diff --git a/server/test/routes/api/v1/auth.test.js b/server/test/routes/api/v1/auth.test.js index e46b481..4f94193 100644 --- a/server/test/routes/api/v1/auth.test.js +++ b/server/test/routes/api/v1/auth.test.js @@ -9,10 +9,37 @@ describe('/api/v1/auth', () => { it('should return not found for email that is not registered', async (t) => { const app = await build(t); const response = await app.inject().post('/api/v1/auth/login').payload({ - email: 'not.found@gmail.com', + email: 'not.found@test.com', password: 'test', }); assert.deepStrictEqual(response.statusCode, StatusCodes.NOT_FOUND); }); + + it('should return unauthorized for invalid password', async (t) => { + const app = await build(t); + await t.loadFixtures(); + const response = await app.inject().post('/api/v1/auth/login').payload({ + email: 'admin.user@test.com', + password: 'invalid', + }); + assert.deepStrictEqual(response.statusCode, StatusCodes.UNAUTHORIZED); + }); + + it('should return ok and a secure session cookie for valid credentials', async (t) => { + const app = await build(t); + await t.loadFixtures(); + const response = await app.inject().post('/api/v1/auth/login').payload({ + email: 'admin.user@test.com', + password: 'test', + }); + assert.deepStrictEqual(response.statusCode, StatusCodes.OK); + const cookie = response.headers['set-cookie'] + ?.split(';') + .map((t) => t.trim()); + assert.ok(cookie[0].startsWith('session=')); + assert.ok(cookie.includes('HttpOnly')); + assert.ok(cookie.includes('Secure')); + assert.ok(cookie.includes('SameSite=Strict')); + }); }); });