From 8cab05d40fbb5327072019d91f32cc122b468baa Mon Sep 17 00:00:00 2001 From: Danya Date: Sun, 29 Oct 2023 22:42:02 +0300 Subject: [PATCH 01/34] create sample of test, without test data --- openapi.yaml | 44 +++++++++++++ src/presentation/http/router/auth.test.ts | 40 ++++++++++++ test | 75 +++++++++++++++++++++++ 3 files changed, 159 insertions(+) create mode 100644 openapi.yaml create mode 100644 src/presentation/http/router/auth.test.ts create mode 100644 test diff --git a/openapi.yaml b/openapi.yaml new file mode 100644 index 00000000..62225e87 --- /dev/null +++ b/openapi.yaml @@ -0,0 +1,44 @@ +source : https://github.com/codex-team/notes.api/blob/main/src/presentation/http/router/auth.ts#L42 + +path: /auth + method: post + tag: + -fastify + summary: check, access, remove, refresh token + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/session' + + responses: + 401: + type: "application/json" + reply: ErrorResponse + body: + # creatorId: "@presentation/http/types/HttpResponse.js" + # StatusCodes: UNAUTHORIZED + message: 'Session is not valid' + + + 200: + type: "application/json" + reply: AuthSession + body: + accessToken: '' + refreshToken: '' + # creatorId: '@domain/service/auth.js' + # signAccessToken : userSession.userId + # removeSessionByRefreshToken: token + # signRefreshToken : userSession.userId + + + +components: + schemas: + session: + token: + type: string + example: "123 + diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts new file mode 100644 index 00000000..059eeb05 --- /dev/null +++ b/src/presentation/http/router/auth.test.ts @@ -0,0 +1,40 @@ +import { describe, test, expect } from 'vitest' +describe('Note API', () => { + describe('POST /auth/:', () => { + test('Returns 401 when session is not valid', async () => { + const expectedStatus = 401 + + const response = await global.api?.fakeRequest({ + method: 'POST', + url: '/auth/' // write not authorised data + }) + + expect(response?.statusCode).toBe(expectedStatus) + + const body = response?.body !== undefined ? JSON.parse(response?.body) : {} + + expect(body).toStrictEqual({ message: "Session is not valid" }) + }) + test('Returns 200 when session was authed', async () => { + + const expectedStatus = 200 + + const expectedAuthReply = { + accessToken: '', + refreshToken: '' + }; + + const response = await global.api?.fakeRequest({ + method: 'POST', + url: ""//write authorised data + }) + + expect(response?.statusCode).toBe(expectedStatus) + + const body = response?.body !== undefined ? JSON.parse(response?.body) : {} + + expect(body).toStrictEqual(expectedAuthReply) + + }) + }) +}) \ No newline at end of file diff --git a/test b/test new file mode 100644 index 00000000..9b35082f --- /dev/null +++ b/test @@ -0,0 +1,75 @@ +describe('Note API', () => { + describe('GET note/:notePublicId ', () => { + test('Returns note by public id', async () => { + const expectedStatus = 200; + + const expectedNote = { + 'id': 2, + 'publicId': 'testnote11', + 'creatorId': 1, + 'content': null, + 'createdAt': '2023-10-16T13:49:19.000Z', + 'updatedAt': '2023-10-16T13:49:19.000Z', + }; + + const response = await global.api?.fakeRequest({ + method: 'GET', + url: '/note/testnote11', + }); + + expect(response?.statusCode).toBe(expectedStatus); + + const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; + + expect(body).toStrictEqual(expectedNote); + }); + + // TODO find correct url and review expected note + // test('Returns 404 when note not found', async () => { + // const expectedStatus = 404; + + // const response = await global.api?.fakeRequest({ + // method: 'GET', + // url: '/note/notex12345', + // }); + + // expect(response?.statusCode).toBe(expectedStatus); + + // const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; + + // expect(body).toStrictEqual({ message: 'Note not found' }); + // }); + + test('Returns 403 when permission denied', async () => { + const expectedStatus = 403; + + const response = await global.api?.fakeRequest({ + method: 'GET', + url: '/note/testnote22', + }); + + expect(response?.statusCode).toBe(expectedStatus); + + const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; + + expect(body).toStrictEqual({ message: 'Permission denied' }); + }); + + // TODO fix problems with 406 response ("Note not found" should be 404 response) + test('Returns 406 when public id incorrect', async () => { + const expectedStatus = 406; + + const response = await global.api?.fakeRequest({ + method: 'GET', + url: '/note/wrong_1_id', + }); + + expect(response?.statusCode).toBe(expectedStatus); + + const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; + + expect(body).toStrictEqual({ message: 'Note not found' }); + }); + + }); +}); From 84cb253087356e34b2efa114eedcefa7e033a0b1 Mon Sep 17 00:00:00 2001 From: Danspb77 <113914200+Danspb77@users.noreply.github.com> Date: Mon, 30 Oct 2023 20:38:40 +0300 Subject: [PATCH 02/34] Update src/presentation/http/router/auth.test.ts Co-authored-by: Vyacheslav Chernyshev <81693471+slaveeks@users.noreply.github.com> --- src/presentation/http/router/auth.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 059eeb05..71c106f7 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -15,7 +15,7 @@ describe('Note API', () => { expect(body).toStrictEqual({ message: "Session is not valid" }) }) - test('Returns 200 when session was authed', async () => { + test('Returns 200 when session was authorized', async () => { const expectedStatus = 200 From 5574e34ecdc7aa463c7ff23e69ec9620c498949e Mon Sep 17 00:00:00 2001 From: Danya Date: Mon, 30 Oct 2023 21:27:37 +0300 Subject: [PATCH 03/34] insert not real test-data into database --- .gitignore | 4 ++ notes.api.code-workspace | 8 +++ openapi.yaml | 2 +- src/presentation/http/router/auth.test.ts | 8 +-- src/tests/test-data/notes.json | 2 +- src/tests/test-data/tokens.json | 6 ++ src/tests/utils/insert-data.ts | 13 ++++ test | 75 ----------------------- 8 files changed, 37 insertions(+), 81 deletions(-) create mode 100644 notes.api.code-workspace create mode 100644 src/tests/test-data/tokens.json delete mode 100644 test diff --git a/.gitignore b/.gitignore index f563cbda..09ff2805 100644 --- a/.gitignore +++ b/.gitignore @@ -139,3 +139,7 @@ dist .yarn/build-state.yml .yarn/install-state.gz .pnp.* + + +# API test sample +.test diff --git a/notes.api.code-workspace b/notes.api.code-workspace new file mode 100644 index 00000000..876a1499 --- /dev/null +++ b/notes.api.code-workspace @@ -0,0 +1,8 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": {} +} \ No newline at end of file diff --git a/openapi.yaml b/openapi.yaml index 62225e87..aaa11893 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -40,5 +40,5 @@ components: session: token: type: string - example: "123 + example: 123 diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 059eeb05..a4570fd1 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect } from 'vitest' describe('Note API', () => { - describe('POST /auth/:', () => { + describe('POST /auth:', () => { test('Returns 401 when session is not valid', async () => { const expectedStatus = 401 @@ -15,13 +15,13 @@ describe('Note API', () => { expect(body).toStrictEqual({ message: "Session is not valid" }) }) - test('Returns 200 when session was authed', async () => { + test('Returns 200 when session was authorized', async () => { const expectedStatus = 200 const expectedAuthReply = { - accessToken: '', - refreshToken: '' + accessToken: '123', + refreshToken: '4567' }; const response = await global.api?.fakeRequest({ diff --git a/src/tests/test-data/notes.json b/src/tests/test-data/notes.json index 4fc09cbf..b5747fed 100644 --- a/src/tests/test-data/notes.json +++ b/src/tests/test-data/notes.json @@ -1,4 +1,4 @@ -[ + [ { "id": 1, "public_id": "note_1", diff --git a/src/tests/test-data/tokens.json b/src/tests/test-data/tokens.json new file mode 100644 index 00000000..3bd24f15 --- /dev/null +++ b/src/tests/test-data/tokens.json @@ -0,0 +1,6 @@ +[ + { + "refreshToken": "", + "accessToken": "" + } +] \ No newline at end of file diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index cbb3c590..54641db7 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -2,6 +2,7 @@ import type SequelizeOrm from '@repository/storage/postgres/orm/index.js'; import users from '../test-data/users.json'; import notes from '../test-data/notes.json'; import noteSettings from '../test-data/notes-settings.json'; +import tokens from '../test-data/tokens.json' /** * Fills in the database with users data @@ -36,6 +37,17 @@ async function insertNoteSettings(db: SequelizeOrm): Promise { } } +/** + * Fills in the database with tokens + * + * @param db - SequelizeOrm instance + */ +async function insertTokens(db:SequelizeOrm): Promise { + for(const token of tokens){ + await db.connection.query(`INSERT INTO public.tokens("accessToken","refreshToken") VALUES (${token.accessToken}, ${token.refreshToken}) `); + } + +} /** * Fills in the database with test data @@ -46,5 +58,6 @@ export async function insertData(db: SequelizeOrm): Promise { await insertUsers(db); await insertNotes(db); await insertNoteSettings(db); + await insertTokens(db); } diff --git a/test b/test deleted file mode 100644 index 9b35082f..00000000 --- a/test +++ /dev/null @@ -1,75 +0,0 @@ -describe('Note API', () => { - describe('GET note/:notePublicId ', () => { - test('Returns note by public id', async () => { - const expectedStatus = 200; - - const expectedNote = { - 'id': 2, - 'publicId': 'testnote11', - 'creatorId': 1, - 'content': null, - 'createdAt': '2023-10-16T13:49:19.000Z', - 'updatedAt': '2023-10-16T13:49:19.000Z', - }; - - const response = await global.api?.fakeRequest({ - method: 'GET', - url: '/note/testnote11', - }); - - expect(response?.statusCode).toBe(expectedStatus); - - const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; - - expect(body).toStrictEqual(expectedNote); - }); - - // TODO find correct url and review expected note - // test('Returns 404 when note not found', async () => { - // const expectedStatus = 404; - - // const response = await global.api?.fakeRequest({ - // method: 'GET', - // url: '/note/notex12345', - // }); - - // expect(response?.statusCode).toBe(expectedStatus); - - // const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; - - // expect(body).toStrictEqual({ message: 'Note not found' }); - // }); - - test('Returns 403 when permission denied', async () => { - const expectedStatus = 403; - - const response = await global.api?.fakeRequest({ - method: 'GET', - url: '/note/testnote22', - }); - - expect(response?.statusCode).toBe(expectedStatus); - - const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; - - expect(body).toStrictEqual({ message: 'Permission denied' }); - }); - - // TODO fix problems with 406 response ("Note not found" should be 404 response) - test('Returns 406 when public id incorrect', async () => { - const expectedStatus = 406; - - const response = await global.api?.fakeRequest({ - method: 'GET', - url: '/note/wrong_1_id', - }); - - expect(response?.statusCode).toBe(expectedStatus); - - const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; - - expect(body).toStrictEqual({ message: 'Note not found' }); - }); - - }); -}); From 10a3ff6aeb87e2fcd278b8c7c1435d99a17421de Mon Sep 17 00:00:00 2001 From: Danya Date: Tue, 31 Oct 2023 20:55:22 +0300 Subject: [PATCH 04/34] add real test-data, but with wrong urls in auth.test.ts --- openapi.yaml | 7 +------ src/presentation/http/router/auth.test.ts | 2 +- src/tests/test-data/tokens.json | 11 +++++++++-- src/tests/utils/insert-data.ts | 2 +- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/openapi.yaml b/openapi.yaml index aaa11893..5f2cd58c 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -17,8 +17,6 @@ path: /auth type: "application/json" reply: ErrorResponse body: - # creatorId: "@presentation/http/types/HttpResponse.js" - # StatusCodes: UNAUTHORIZED message: 'Session is not valid' @@ -28,10 +26,7 @@ path: /auth body: accessToken: '' refreshToken: '' - # creatorId: '@domain/service/auth.js' - # signAccessToken : userSession.userId - # removeSessionByRefreshToken: token - # signRefreshToken : userSession.userId + diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index a4570fd1..65c0cf4b 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect } from 'vitest' describe('Note API', () => { - describe('POST /auth:', () => { + describe('POST /auth', () => { test('Returns 401 when session is not valid', async () => { const expectedStatus = 401 diff --git a/src/tests/test-data/tokens.json b/src/tests/test-data/tokens.json index 3bd24f15..2b008c81 100644 --- a/src/tests/test-data/tokens.json +++ b/src/tests/test-data/tokens.json @@ -1,6 +1,13 @@ [ { - "refreshToken": "", - "accessToken": "" + "refreshToken": "pv-jIqfPj1", + "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTksImlhdCI6MTY5ODc1NzQyMSwiZXhwIjoxNjk5NjU3NDIxfQ.g0PzlWpGkw4VQrMRulNrnnAFa3KxtF4buCjqxKV-wq4", + + "refresh_token_expires_at": "2023-10-31 10:23:54+02", + "user_Id": "134", + "Id":"1" + + + } ] \ No newline at end of file diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 54641db7..ac191482 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -44,7 +44,7 @@ async function insertNoteSettings(db: SequelizeOrm): Promise { */ async function insertTokens(db:SequelizeOrm): Promise { for(const token of tokens){ - await db.connection.query(`INSERT INTO public.tokens("accessToken","refreshToken") VALUES (${token.accessToken}, ${token.refreshToken}) `); + await db.connection.query(`INSERT INTO public.user_sessions("Id","user_Id,"refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id},${token.refreshToken},${token.refresh_token_expires_at}) `) } } From 8814436d8e2eee57b0ec39b9accc7e071c092398 Mon Sep 17 00:00:00 2001 From: Danya Date: Wed, 1 Nov 2023 12:42:52 +0300 Subject: [PATCH 05/34] add real data in expectedAuthReply --- openapi.yaml | 2 +- src/presentation/http/router/auth.test.ts | 9 +++++---- src/tests/test-data/tokens.json | 1 - 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/openapi.yaml b/openapi.yaml index 5f2cd58c..7ad6b4ac 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -7,7 +7,7 @@ path: /auth summary: check, access, remove, refresh token requestBody: required: true - content: + content application/json: schema: $ref: '#/components/schemas/session' diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 65c0cf4b..58512b8c 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -6,7 +6,7 @@ describe('Note API', () => { const response = await global.api?.fakeRequest({ method: 'POST', - url: '/auth/' // write not authorised data + url: '/auth' // write not authorised data }) expect(response?.statusCode).toBe(expectedStatus) @@ -20,13 +20,14 @@ describe('Note API', () => { const expectedStatus = 200 const expectedAuthReply = { - accessToken: '123', - refreshToken: '4567' + refreshToken: "pv-jIqfPj1", + accessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTksImlhdCI6MTY5ODc1NzQyMSwiZXhwIjoxNjk5NjU3NDIxfQ.g0PzlWpGkw4VQrMRulNrnnAFa3KxtF4buCjqxKV-wq4" + }; const response = await global.api?.fakeRequest({ method: 'POST', - url: ""//write authorised data + url: "/auth"//write authorised data }) expect(response?.statusCode).toBe(expectedStatus) diff --git a/src/tests/test-data/tokens.json b/src/tests/test-data/tokens.json index 2b008c81..f0e735d4 100644 --- a/src/tests/test-data/tokens.json +++ b/src/tests/test-data/tokens.json @@ -2,7 +2,6 @@ { "refreshToken": "pv-jIqfPj1", "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTksImlhdCI6MTY5ODc1NzQyMSwiZXhwIjoxNjk5NjU3NDIxfQ.g0PzlWpGkw4VQrMRulNrnnAFa3KxtF4buCjqxKV-wq4", - "refresh_token_expires_at": "2023-10-31 10:23:54+02", "user_Id": "134", "Id":"1" From 462886fba7b96e9a4204959997e2699fb9d96c82 Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 2 Nov 2023 13:50:48 +0300 Subject: [PATCH 06/34] add body to POST method --- .gitignore | 3 +- notes.api.code-workspace | 8 --- src/presentation/http/router/auth.test.ts | 18 +++--- src/tests/test-data/tokens.json | 3 - test | 75 +++++++++++++++++++++++ 5 files changed, 88 insertions(+), 19 deletions(-) delete mode 100644 notes.api.code-workspace create mode 100644 test diff --git a/.gitignore b/.gitignore index 09ff2805..199aa0c4 100644 --- a/.gitignore +++ b/.gitignore @@ -142,4 +142,5 @@ dist # API test sample -.test + +./notes.api.code-workspace \ No newline at end of file diff --git a/notes.api.code-workspace b/notes.api.code-workspace deleted file mode 100644 index 876a1499..00000000 --- a/notes.api.code-workspace +++ /dev/null @@ -1,8 +0,0 @@ -{ - "folders": [ - { - "path": "." - } - ], - "settings": {} -} \ No newline at end of file diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 58512b8c..4f503740 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -1,12 +1,13 @@ import { describe, test, expect } from 'vitest' -describe('Note API', () => { + +describe('Auth API', () => { describe('POST /auth', () => { test('Returns 401 when session is not valid', async () => { const expectedStatus = 401 const response = await global.api?.fakeRequest({ method: 'POST', - url: '/auth' // write not authorised data + url: '/auth', // write not authorized data }) expect(response?.statusCode).toBe(expectedStatus) @@ -15,19 +16,23 @@ describe('Note API', () => { expect(body).toStrictEqual({ message: "Session is not valid" }) }) - test('Returns 200 when session was authorized', async () => { + test('Returns 200 when session was authorized', async () => { const expectedStatus = 200 + // Define the token to include in the request body + const refreshToken = "pv-jIqfPj1"; + const expectedAuthReply = { refreshToken: "pv-jIqfPj1", accessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTksImlhdCI6MTY5ODc1NzQyMSwiZXhwIjoxNjk5NjU3NDIxfQ.g0PzlWpGkw4VQrMRulNrnnAFa3KxtF4buCjqxKV-wq4" - }; + // Include the token in the request body const response = await global.api?.fakeRequest({ method: 'POST', - url: "/auth"//write authorised data + url: "/auth", // write authorized data + body: { token: refreshToken } // Include the token in the request body }) expect(response?.statusCode).toBe(expectedStatus) @@ -35,7 +40,6 @@ describe('Note API', () => { const body = response?.body !== undefined ? JSON.parse(response?.body) : {} expect(body).toStrictEqual(expectedAuthReply) - }) }) -}) \ No newline at end of file +}) diff --git a/src/tests/test-data/tokens.json b/src/tests/test-data/tokens.json index f0e735d4..fa5e936f 100644 --- a/src/tests/test-data/tokens.json +++ b/src/tests/test-data/tokens.json @@ -5,8 +5,5 @@ "refresh_token_expires_at": "2023-10-31 10:23:54+02", "user_Id": "134", "Id":"1" - - - } ] \ No newline at end of file diff --git a/test b/test new file mode 100644 index 00000000..9b35082f --- /dev/null +++ b/test @@ -0,0 +1,75 @@ +describe('Note API', () => { + describe('GET note/:notePublicId ', () => { + test('Returns note by public id', async () => { + const expectedStatus = 200; + + const expectedNote = { + 'id': 2, + 'publicId': 'testnote11', + 'creatorId': 1, + 'content': null, + 'createdAt': '2023-10-16T13:49:19.000Z', + 'updatedAt': '2023-10-16T13:49:19.000Z', + }; + + const response = await global.api?.fakeRequest({ + method: 'GET', + url: '/note/testnote11', + }); + + expect(response?.statusCode).toBe(expectedStatus); + + const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; + + expect(body).toStrictEqual(expectedNote); + }); + + // TODO find correct url and review expected note + // test('Returns 404 when note not found', async () => { + // const expectedStatus = 404; + + // const response = await global.api?.fakeRequest({ + // method: 'GET', + // url: '/note/notex12345', + // }); + + // expect(response?.statusCode).toBe(expectedStatus); + + // const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; + + // expect(body).toStrictEqual({ message: 'Note not found' }); + // }); + + test('Returns 403 when permission denied', async () => { + const expectedStatus = 403; + + const response = await global.api?.fakeRequest({ + method: 'GET', + url: '/note/testnote22', + }); + + expect(response?.statusCode).toBe(expectedStatus); + + const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; + + expect(body).toStrictEqual({ message: 'Permission denied' }); + }); + + // TODO fix problems with 406 response ("Note not found" should be 404 response) + test('Returns 406 when public id incorrect', async () => { + const expectedStatus = 406; + + const response = await global.api?.fakeRequest({ + method: 'GET', + url: '/note/wrong_1_id', + }); + + expect(response?.statusCode).toBe(expectedStatus); + + const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; + + expect(body).toStrictEqual({ message: 'Note not found' }); + }); + + }); +}); From e5e4f2264577d9fd3349810631c6d8211ec65e93 Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 2 Nov 2023 23:02:41 +0300 Subject: [PATCH 07/34] fix insert data for auth tests --- src/tests/utils/insert-data.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index ac191482..684f32a7 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -44,7 +44,7 @@ async function insertNoteSettings(db: SequelizeOrm): Promise { */ async function insertTokens(db:SequelizeOrm): Promise { for(const token of tokens){ - await db.connection.query(`INSERT INTO public.user_sessions("Id","user_Id,"refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id},${token.refreshToken},${token.refresh_token_expires_at}) `) + await db.connection.query(`INSERT INTO public.user_sessions("id","user_id","refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id}, '${token.refreshToken}', '${token.refresh_token_expires_at}')`) } } From e389e694244d19738bbb60ed62decbf5f4d51d0d Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 2 Nov 2023 23:12:11 +0300 Subject: [PATCH 08/34] fix data for auth tests --- src/tests/test-data/tokens.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/test-data/tokens.json b/src/tests/test-data/tokens.json index fa5e936f..0c59a4c8 100644 --- a/src/tests/test-data/tokens.json +++ b/src/tests/test-data/tokens.json @@ -3,7 +3,7 @@ "refreshToken": "pv-jIqfPj1", "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTksImlhdCI6MTY5ODc1NzQyMSwiZXhwIjoxNjk5NjU3NDIxfQ.g0PzlWpGkw4VQrMRulNrnnAFa3KxtF4buCjqxKV-wq4", "refresh_token_expires_at": "2023-10-31 10:23:54+02", - "user_Id": "134", + "user_Id": "1", "Id":"1" } ] \ No newline at end of file From b31848abcb4bca25b446c485a1991f23ce8f1e13 Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 2 Nov 2023 23:29:24 +0300 Subject: [PATCH 09/34] fix data for auth tests in the second time --- src/tests/test-data/tokens.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tests/test-data/tokens.json b/src/tests/test-data/tokens.json index 0c59a4c8..210cd8b0 100644 --- a/src/tests/test-data/tokens.json +++ b/src/tests/test-data/tokens.json @@ -3,7 +3,7 @@ "refreshToken": "pv-jIqfPj1", "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTksImlhdCI6MTY5ODc1NzQyMSwiZXhwIjoxNjk5NjU3NDIxfQ.g0PzlWpGkw4VQrMRulNrnnAFa3KxtF4buCjqxKV-wq4", "refresh_token_expires_at": "2023-10-31 10:23:54+02", - "user_Id": "1", - "Id":"1" + "user_Id": 1, + "Id":1 } ] \ No newline at end of file From 624748fa1a6648409da3b94621e3c07c482001f8 Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 2 Nov 2023 23:45:50 +0300 Subject: [PATCH 10/34] fix test with not valid token --- src/presentation/http/router/auth.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 4f503740..ed882a77 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -4,10 +4,11 @@ describe('Auth API', () => { describe('POST /auth', () => { test('Returns 401 when session is not valid', async () => { const expectedStatus = 401 - + const refreshToken = "not-validToken"; const response = await global.api?.fakeRequest({ method: 'POST', url: '/auth', // write not authorized data + body: { token: refreshToken } }) expect(response?.statusCode).toBe(expectedStatus) From c04144eacdab68b120aab70ad0c6b702cb952d92 Mon Sep 17 00:00:00 2001 From: Danya Date: Fri, 3 Nov 2023 21:51:23 +0300 Subject: [PATCH 11/34] change format of checking in test with status 200 --- .gitignore | 3 +- src/presentation/http/router/auth.test.ts | 68 +++++++++++------------ src/tests/test-data/tokens.json | 2 +- 3 files changed, 36 insertions(+), 37 deletions(-) diff --git a/.gitignore b/.gitignore index 199aa0c4..549b9be5 100644 --- a/.gitignore +++ b/.gitignore @@ -141,6 +141,5 @@ dist .pnp.* -# API test sample -./notes.api.code-workspace \ No newline at end of file +notes.api.code-workspace \ No newline at end of file diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index ed882a77..fe49df90 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -1,46 +1,46 @@ -import { describe, test, expect } from 'vitest' +import { describe, test, expect } from 'vitest'; describe('Auth API', () => { - describe('POST /auth', () => { - test('Returns 401 when session is not valid', async () => { - const expectedStatus = 401 - const refreshToken = "not-validToken"; - const response = await global.api?.fakeRequest({ - method: 'POST', - url: '/auth', // write not authorized data - body: { token: refreshToken } - }) + describe('POST /auth', () => { + test('Returns 401 when session is not valid', async () => { + const expectedStatus = 401; + const refreshToken = 'not-validToken'; + const response = await global.api?.fakeRequest({ + method: 'POST', + url: '/auth', // write not authorized data + body: { token: refreshToken }, + }); - expect(response?.statusCode).toBe(expectedStatus) + expect(response?.statusCode).toBe(expectedStatus); - const body = response?.body !== undefined ? JSON.parse(response?.body) : {} + const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; - expect(body).toStrictEqual({ message: "Session is not valid" }) - }) + expect(body).toStrictEqual({ message: 'Session is not valid' }); + }); - test('Returns 200 when session was authorized', async () => { - const expectedStatus = 200 + test('Returns 200 when session was authorized', async () => { + const expectedStatus = 200; - // Define the token to include in the request body - const refreshToken = "pv-jIqfPj1"; + // Define the token to include in the request body + const refreshToken = 'pv-jIqfPj1'; - const expectedAuthReply = { - refreshToken: "pv-jIqfPj1", - accessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTksImlhdCI6MTY5ODc1NzQyMSwiZXhwIjoxNjk5NjU3NDIxfQ.g0PzlWpGkw4VQrMRulNrnnAFa3KxtF4buCjqxKV-wq4" - }; + const expectedAuthReply = { + refreshToken: expect.any(String), + accessToken: expect.any(String), + }; - // Include the token in the request body - const response = await global.api?.fakeRequest({ - method: 'POST', - url: "/auth", // write authorized data - body: { token: refreshToken } // Include the token in the request body - }) + // Include the token in the request body + const response = await global.api?.fakeRequest({ + method: 'POST', + url: '/auth', // write authorized data + body: { token: refreshToken }, // Include the token in the request body + }); - expect(response?.statusCode).toBe(expectedStatus) + expect(response?.statusCode).toBe(expectedStatus); - const body = response?.body !== undefined ? JSON.parse(response?.body) : {} + const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; - expect(body).toStrictEqual(expectedAuthReply) - }) - }) -}) + expect(body).toMatchObject(expectedAuthReply); + }); + }); +}); diff --git a/src/tests/test-data/tokens.json b/src/tests/test-data/tokens.json index 210cd8b0..0f4b636e 100644 --- a/src/tests/test-data/tokens.json +++ b/src/tests/test-data/tokens.json @@ -2,7 +2,7 @@ { "refreshToken": "pv-jIqfPj1", "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTksImlhdCI6MTY5ODc1NzQyMSwiZXhwIjoxNjk5NjU3NDIxfQ.g0PzlWpGkw4VQrMRulNrnnAFa3KxtF4buCjqxKV-wq4", - "refresh_token_expires_at": "2023-10-31 10:23:54+02", + "refresh_token_expires_at": "2023-11-04 10:23:54+02", "user_Id": 1, "Id":1 } From 148f0a77bd384c348c7822a60be49183ad09cb46 Mon Sep 17 00:00:00 2001 From: Danya Date: Fri, 3 Nov 2023 22:16:31 +0300 Subject: [PATCH 12/34] change script for insert data for auth test in ESLint format --- src/tests/utils/insert-data.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 684f32a7..5aec8bcb 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -2,7 +2,7 @@ import type SequelizeOrm from '@repository/storage/postgres/orm/index.js'; import users from '../test-data/users.json'; import notes from '../test-data/notes.json'; import noteSettings from '../test-data/notes-settings.json'; -import tokens from '../test-data/tokens.json' +import tokens from '../test-data/tokens.json'; /** * Fills in the database with users data @@ -43,10 +43,9 @@ async function insertNoteSettings(db: SequelizeOrm): Promise { * @param db - SequelizeOrm instance */ async function insertTokens(db:SequelizeOrm): Promise { - for(const token of tokens){ - await db.connection.query(`INSERT INTO public.user_sessions("id","user_id","refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id}, '${token.refreshToken}', '${token.refresh_token_expires_at}')`) + for (const token of tokens) { + await db.connection.query(`INSERT INTO public.user_sessions("id","user_id","refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id}, '${token.refreshToken}', '${token.refresh_token_expires_at}')`); } - } /** From d41f8dd9e45c912635956fe7c96ab586b318cafc Mon Sep 17 00:00:00 2001 From: Danya Date: Mon, 6 Nov 2023 16:43:11 +0300 Subject: [PATCH 13/34] add test-case for situation when expiration day has passed --- .gitignore | 2 +- src/presentation/http/router/auth.test.ts | 36 ++++++++--- src/tests/test-data/tokens.json | 9 --- src/tests/test-data/users_sessions.json | 8 +++ src/tests/utils/insert-data.ts | 12 ++-- test | 75 ----------------------- 6 files changed, 44 insertions(+), 98 deletions(-) delete mode 100644 src/tests/test-data/tokens.json create mode 100644 src/tests/test-data/users_sessions.json delete mode 100644 test diff --git a/.gitignore b/.gitignore index 549b9be5..6d038855 100644 --- a/.gitignore +++ b/.gitignore @@ -142,4 +142,4 @@ dist -notes.api.code-workspace \ No newline at end of file +*.code-workspace \ No newline at end of file diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index fe49df90..58eb3829 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -7,7 +7,7 @@ describe('Auth API', () => { const refreshToken = 'not-validToken'; const response = await global.api?.fakeRequest({ method: 'POST', - url: '/auth', // write not authorized data + url: '/auth', body: { token: refreshToken }, }); @@ -21,19 +21,21 @@ describe('Auth API', () => { test('Returns 200 when session was authorized', async () => { const expectedStatus = 200; - // Define the token to include in the request body + /** Define the token to include in the request body */ const refreshToken = 'pv-jIqfPj1'; + const notEmptyString = expect.stringMatching('/^.$/'); + const expectedAuthReply = { - refreshToken: expect.any(String), - accessToken: expect.any(String), + refreshToken: notEmptyString, + accessToken: notEmptyString, }; - // Include the token in the request body + const response = await global.api?.fakeRequest({ method: 'POST', - url: '/auth', // write authorized data - body: { token: refreshToken }, // Include the token in the request body + url: '/auth', + body: { token: refreshToken }, /** Include the token in the request body*/ }); expect(response?.statusCode).toBe(expectedStatus); @@ -42,5 +44,25 @@ describe('Auth API', () => { expect(body).toMatchObject(expectedAuthReply); }); + + test('Returns 401 when expiration day has passed', async () => { + const expectedStatus=401; + const refreshToken = 'pv-jIqfPj1'; + /** Set the expiration day to a date in the past */ + const pastExpirationDay = new Date('Sat, 03 Nov 2022 16:53:36 GMT').toUTCString(); + + const response=await global.api?.fakeRequest({ + method: 'POST', + url: '/auth', + headers:{ date:pastExpirationDay }, + body:{ token: refreshToken }, + }); + + expect (response?.statusCode).toBe(expectedStatus); + const body = response?.body !== undefined ? JSON.parse(response?.body):{}; + + expect(body).toStrictEqual({ message:'Session is not valid' }); + }); }); }); +/** to do give 401 if experation date > now, check, to srtings will not be empty */ \ No newline at end of file diff --git a/src/tests/test-data/tokens.json b/src/tests/test-data/tokens.json deleted file mode 100644 index 0f4b636e..00000000 --- a/src/tests/test-data/tokens.json +++ /dev/null @@ -1,9 +0,0 @@ -[ - { - "refreshToken": "pv-jIqfPj1", - "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTksImlhdCI6MTY5ODc1NzQyMSwiZXhwIjoxNjk5NjU3NDIxfQ.g0PzlWpGkw4VQrMRulNrnnAFa3KxtF4buCjqxKV-wq4", - "refresh_token_expires_at": "2023-11-04 10:23:54+02", - "user_Id": 1, - "Id":1 - } -] \ No newline at end of file diff --git a/src/tests/test-data/users_sessions.json b/src/tests/test-data/users_sessions.json new file mode 100644 index 00000000..c53dcf16 --- /dev/null +++ b/src/tests/test-data/users_sessions.json @@ -0,0 +1,8 @@ +[ + { + "refreshToken": "pv-jIqfPj1", + "refresh_token_expires_at": "2023-11-06 10:23:54+02", + "user_Id": 1, + "Id":1 + } +] \ No newline at end of file diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 5aec8bcb..1446546a 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -42,11 +42,11 @@ async function insertNoteSettings(db: SequelizeOrm): Promise { * * @param db - SequelizeOrm instance */ -async function insertTokens(db:SequelizeOrm): Promise { - for (const token of tokens) { - await db.connection.query(`INSERT INTO public.user_sessions("id","user_id","refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id}, '${token.refreshToken}', '${token.refresh_token_expires_at}')`); - } -} +// async function insertTokens(db:SequelizeOrm): Promise { +// for (const token of tokens) { +// await db.connection.query(`INSERT INTO public.user_sessions("id","user_id","refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id}, '${token.refreshToken}', '${token.refresh_token_expires_at}')`); +// } +// } /** * Fills in the database with test data @@ -57,6 +57,6 @@ export async function insertData(db: SequelizeOrm): Promise { await insertUsers(db); await insertNotes(db); await insertNoteSettings(db); - await insertTokens(db); + // await insertTokens(db); } diff --git a/test b/test deleted file mode 100644 index 9b35082f..00000000 --- a/test +++ /dev/null @@ -1,75 +0,0 @@ -describe('Note API', () => { - describe('GET note/:notePublicId ', () => { - test('Returns note by public id', async () => { - const expectedStatus = 200; - - const expectedNote = { - 'id': 2, - 'publicId': 'testnote11', - 'creatorId': 1, - 'content': null, - 'createdAt': '2023-10-16T13:49:19.000Z', - 'updatedAt': '2023-10-16T13:49:19.000Z', - }; - - const response = await global.api?.fakeRequest({ - method: 'GET', - url: '/note/testnote11', - }); - - expect(response?.statusCode).toBe(expectedStatus); - - const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; - - expect(body).toStrictEqual(expectedNote); - }); - - // TODO find correct url and review expected note - // test('Returns 404 when note not found', async () => { - // const expectedStatus = 404; - - // const response = await global.api?.fakeRequest({ - // method: 'GET', - // url: '/note/notex12345', - // }); - - // expect(response?.statusCode).toBe(expectedStatus); - - // const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; - - // expect(body).toStrictEqual({ message: 'Note not found' }); - // }); - - test('Returns 403 when permission denied', async () => { - const expectedStatus = 403; - - const response = await global.api?.fakeRequest({ - method: 'GET', - url: '/note/testnote22', - }); - - expect(response?.statusCode).toBe(expectedStatus); - - const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; - - expect(body).toStrictEqual({ message: 'Permission denied' }); - }); - - // TODO fix problems with 406 response ("Note not found" should be 404 response) - test('Returns 406 when public id incorrect', async () => { - const expectedStatus = 406; - - const response = await global.api?.fakeRequest({ - method: 'GET', - url: '/note/wrong_1_id', - }); - - expect(response?.statusCode).toBe(expectedStatus); - - const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; - - expect(body).toStrictEqual({ message: 'Note not found' }); - }); - - }); -}); From 89c326b157b759f42e00f59df707c63b6b3cc97b Mon Sep 17 00:00:00 2001 From: Danya Date: Mon, 6 Nov 2023 16:47:40 +0300 Subject: [PATCH 14/34] add test-case for situation when expiration day has passed v 2.0 --- src/tests/utils/insert-data.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 1446546a..7590bb6b 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -2,7 +2,7 @@ import type SequelizeOrm from '@repository/storage/postgres/orm/index.js'; import users from '../test-data/users.json'; import notes from '../test-data/notes.json'; import noteSettings from '../test-data/notes-settings.json'; -import tokens from '../test-data/tokens.json'; +import tokens from '../test-data/users_sessions.json'; /** * Fills in the database with users data @@ -42,11 +42,11 @@ async function insertNoteSettings(db: SequelizeOrm): Promise { * * @param db - SequelizeOrm instance */ -// async function insertTokens(db:SequelizeOrm): Promise { -// for (const token of tokens) { -// await db.connection.query(`INSERT INTO public.user_sessions("id","user_id","refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id}, '${token.refreshToken}', '${token.refresh_token_expires_at}')`); -// } -// } +async function insertTokens(db:SequelizeOrm): Promise { + for (const token of tokens) { + await db.connection.query(`INSERT INTO public.user_sessions("id","user_id","refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id}, '${token.refreshToken}', '${token.refresh_token_expires_at}')`); + } +} /** * Fills in the database with test data @@ -57,6 +57,6 @@ export async function insertData(db: SequelizeOrm): Promise { await insertUsers(db); await insertNotes(db); await insertNoteSettings(db); - // await insertTokens(db); + await insertTokens(db); } From 9d3ec54c9f743b92490c401103368c321576fb30 Mon Sep 17 00:00:00 2001 From: Danya Date: Mon, 6 Nov 2023 17:25:33 +0300 Subject: [PATCH 15/34] draft commit --- openapi.yaml | 39 ----------------------- src/presentation/http/router/auth.test.ts | 1 - 2 files changed, 40 deletions(-) delete mode 100644 openapi.yaml diff --git a/openapi.yaml b/openapi.yaml deleted file mode 100644 index 7ad6b4ac..00000000 --- a/openapi.yaml +++ /dev/null @@ -1,39 +0,0 @@ -source : https://github.com/codex-team/notes.api/blob/main/src/presentation/http/router/auth.ts#L42 - -path: /auth - method: post - tag: - -fastify - summary: check, access, remove, refresh token - requestBody: - required: true - content - application/json: - schema: - $ref: '#/components/schemas/session' - - responses: - 401: - type: "application/json" - reply: ErrorResponse - body: - message: 'Session is not valid' - - - 200: - type: "application/json" - reply: AuthSession - body: - accessToken: '' - refreshToken: '' - - - - -components: - schemas: - session: - token: - type: string - example: 123 - diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 58eb3829..88b458e9 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -65,4 +65,3 @@ describe('Auth API', () => { }); }); }); -/** to do give 401 if experation date > now, check, to srtings will not be empty */ \ No newline at end of file From 71b01dbcab46a2a9e6ba91d4cdb13da90844257f Mon Sep 17 00:00:00 2001 From: Danya Date: Tue, 7 Nov 2023 23:12:28 +0300 Subject: [PATCH 16/34] 200 test doesn't work , but others work --- .gitignore | 2 -- src/tests/test-data/users_sessions.json | 8 +++++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 6d038855..dcd4666b 100644 --- a/.gitignore +++ b/.gitignore @@ -140,6 +140,4 @@ dist .yarn/install-state.gz .pnp.* - - *.code-workspace \ No newline at end of file diff --git a/src/tests/test-data/users_sessions.json b/src/tests/test-data/users_sessions.json index c53dcf16..edee17fa 100644 --- a/src/tests/test-data/users_sessions.json +++ b/src/tests/test-data/users_sessions.json @@ -1,8 +1,14 @@ [ { "refreshToken": "pv-jIqfPj1", - "refresh_token_expires_at": "2023-11-06 10:23:54+02", + "refresh_token_expires_at": "2023-11-04 10:23:54+02", "user_Id": 1, "Id":1 + }, + { + "refreshToken": "F5tTF24K9Q", + "refresh_token_expires_at": "2023-11-08 11:23:54+02", + "user_Id": 1, + "Id":2 } ] \ No newline at end of file From dacac93dd0c7ed7d10e23c20365e1c534eae6d56 Mon Sep 17 00:00:00 2001 From: Danya Date: Wed, 8 Nov 2023 09:37:19 +0300 Subject: [PATCH 17/34] fix test case for situation when expiration dau has passed --- package.json | 1 + src/presentation/http/router/auth.test.ts | 4 +- ...{users_sessions.json => userSessions.json} | 4 +- src/tests/utils/insert-data.ts | 6 +- yarn.lock | 79 +++++++++++++++++++ 5 files changed, 87 insertions(+), 7 deletions(-) rename src/tests/test-data/{users_sessions.json => userSessions.json} (58%) diff --git a/package.json b/package.json index 80240b7a..338fb77f 100644 --- a/package.json +++ b/package.json @@ -42,6 +42,7 @@ "@fastify/swagger-ui": "^1.9.3", "@testcontainers/postgresql": "^10.2.1", "arg": "^5.0.2", + "axios": "^1.6.0", "fastify": "^4.17.0", "http-status-codes": "^2.2.0", "jsonwebtoken": "^9.0.0", diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 88b458e9..eee080e6 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -23,8 +23,8 @@ describe('Auth API', () => { /** Define the token to include in the request body */ const refreshToken = 'pv-jIqfPj1'; - - const notEmptyString = expect.stringMatching('/^.$/'); + /** Define regular expression to be sure that string is not empty */ + const notEmptyString = /^.$/; const expectedAuthReply = { refreshToken: notEmptyString, diff --git a/src/tests/test-data/users_sessions.json b/src/tests/test-data/userSessions.json similarity index 58% rename from src/tests/test-data/users_sessions.json rename to src/tests/test-data/userSessions.json index edee17fa..21c4ad52 100644 --- a/src/tests/test-data/users_sessions.json +++ b/src/tests/test-data/userSessions.json @@ -1,13 +1,13 @@ [ { "refreshToken": "pv-jIqfPj1", - "refresh_token_expires_at": "2023-11-04 10:23:54+02", + "refresh_token_expires_at": "2024-11-04 10:23:54+02", "user_Id": 1, "Id":1 }, { "refreshToken": "F5tTF24K9Q", - "refresh_token_expires_at": "2023-11-08 11:23:54+02", + "refresh_token_expires_at": "2023-11-09 11:23:54+02", "user_Id": 1, "Id":2 } diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 7590bb6b..21c26503 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -2,7 +2,7 @@ import type SequelizeOrm from '@repository/storage/postgres/orm/index.js'; import users from '../test-data/users.json'; import notes from '../test-data/notes.json'; import noteSettings from '../test-data/notes-settings.json'; -import tokens from '../test-data/users_sessions.json'; +import tokens from '../test-data/userSessions.json'; /** * Fills in the database with users data @@ -42,7 +42,7 @@ async function insertNoteSettings(db: SequelizeOrm): Promise { * * @param db - SequelizeOrm instance */ -async function insertTokens(db:SequelizeOrm): Promise { +async function insertUserSessions(db:SequelizeOrm): Promise { for (const token of tokens) { await db.connection.query(`INSERT INTO public.user_sessions("id","user_id","refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id}, '${token.refreshToken}', '${token.refresh_token_expires_at}')`); } @@ -57,6 +57,6 @@ export async function insertData(db: SequelizeOrm): Promise { await insertUsers(db); await insertNotes(db); await insertNoteSettings(db); - await insertTokens(db); + await insertUserSessions(db); } diff --git a/yarn.lock b/yarn.lock index 5d3f8483..88511424 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1377,6 +1377,13 @@ __metadata: languageName: node linkType: hard +"asynckit@npm:^0.4.0": + version: 0.4.0 + resolution: "asynckit@npm:0.4.0" + checksum: 7b78c451df768adba04e2d02e63e2d0bf3b07adcd6e42b4cf665cb7ce899bedd344c69a1dcbce355b5f972d597b25aaa1c1742b52cffd9caccb22f348114f6be + languageName: node + linkType: hard + "atomic-sleep@npm:^1.0.0": version: 1.0.0 resolution: "atomic-sleep@npm:1.0.0" @@ -1402,6 +1409,17 @@ __metadata: languageName: node linkType: hard +"axios@npm:^1.6.0": + version: 1.6.0 + resolution: "axios@npm:1.6.0" + dependencies: + follow-redirects: ^1.15.0 + form-data: ^4.0.0 + proxy-from-env: ^1.1.0 + checksum: c7c9f2ae9e0b9bad7d6f9a4dff030930b12ee667dedf54c3c776714f91681feb743c509ac0796ae5c01e12c4ab4a2bee74905068dd200fbc1ab86f9814578fb0 + languageName: node + linkType: hard + "b4a@npm:^1.6.4": version: 1.6.4 resolution: "b4a@npm:1.6.4" @@ -1707,6 +1725,15 @@ __metadata: languageName: node linkType: hard +"combined-stream@npm:^1.0.8": + version: 1.0.8 + resolution: "combined-stream@npm:1.0.8" + dependencies: + delayed-stream: ~1.0.0 + checksum: 49fa4aeb4916567e33ea81d088f6584749fc90c7abec76fd516bf1c5aa5c79f3584b5ba3de6b86d26ddd64bae5329c4c7479343250cfe71c75bb366eae53bb7c + languageName: node + linkType: hard + "commander@npm:^9.0.0": version: 9.5.0 resolution: "commander@npm:9.5.0" @@ -1884,6 +1911,13 @@ __metadata: languageName: node linkType: hard +"delayed-stream@npm:~1.0.0": + version: 1.0.0 + resolution: "delayed-stream@npm:1.0.0" + checksum: 46fe6e83e2cb1d85ba50bd52803c68be9bd953282fa7096f51fc29edd5d67ff84ff753c51966061e5ba7cb5e47ef6d36a91924eddb7f3f3483b1c560f77a0020 + languageName: node + linkType: hard + "delegates@npm:^1.0.0": version: 1.0.0 resolution: "delegates@npm:1.0.0" @@ -2693,6 +2727,16 @@ __metadata: languageName: node linkType: hard +"follow-redirects@npm:^1.15.0": + version: 1.15.3 + resolution: "follow-redirects@npm:1.15.3" + peerDependenciesMeta: + debug: + optional: true + checksum: 584da22ec5420c837bd096559ebfb8fe69d82512d5585004e36a3b4a6ef6d5905780e0c74508c7b72f907d1fa2b7bd339e613859e9c304d0dc96af2027fd0231 + languageName: node + linkType: hard + "for-each@npm:^0.3.3": version: 0.3.3 resolution: "for-each@npm:0.3.3" @@ -2712,6 +2756,17 @@ __metadata: languageName: node linkType: hard +"form-data@npm:^4.0.0": + version: 4.0.0 + resolution: "form-data@npm:4.0.0" + dependencies: + asynckit: ^0.4.0 + combined-stream: ^1.0.8 + mime-types: ^2.1.12 + checksum: 01135bf8675f9d5c61ff18e2e2932f719ca4de964e3be90ef4c36aacfc7b9cb2fceb5eca0b7e0190e3383fe51c5b37f4cb80b62ca06a99aaabfcfd6ac7c9328c + languageName: node + linkType: hard + "forwarded@npm:0.2.0": version: 0.2.0 resolution: "forwarded@npm:0.2.0" @@ -3806,6 +3861,22 @@ __metadata: languageName: node linkType: hard +"mime-db@npm:1.52.0": + version: 1.52.0 + resolution: "mime-db@npm:1.52.0" + checksum: 0d99a03585f8b39d68182803b12ac601d9c01abfa28ec56204fa330bc9f3d1c5e14beb049bafadb3dbdf646dfb94b87e24d4ec7b31b7279ef906a8ea9b6a513f + languageName: node + linkType: hard + +"mime-types@npm:^2.1.12": + version: 2.1.35 + resolution: "mime-types@npm:2.1.35" + dependencies: + mime-db: 1.52.0 + checksum: 89a5b7f1def9f3af5dad6496c5ed50191ae4331cc5389d7c521c8ad28d5fdad2d06fd81baf38fed813dc4e46bb55c8145bb0ff406330818c9cf712fb2e9b3836 + languageName: node + linkType: hard + "mime@npm:^3.0.0": version: 3.0.0 resolution: "mime@npm:3.0.0" @@ -4147,6 +4218,7 @@ __metadata: "@types/node": ^20.2.3 "@types/pg": ^8.10.2 arg: ^5.0.2 + axios: ^1.6.0 eslint: ^8.41.0 eslint-config-codex: ^1.8.3 eslint-plugin-vitest: ^0.3.1 @@ -4793,6 +4865,13 @@ __metadata: languageName: node linkType: hard +"proxy-from-env@npm:^1.1.0": + version: 1.1.0 + resolution: "proxy-from-env@npm:1.1.0" + checksum: ed7fcc2ba0a33404958e34d95d18638249a68c430e30fcb6c478497d72739ba64ce9810a24f53a7d921d0c065e5b78e3822759800698167256b04659366ca4d4 + languageName: node + linkType: hard + "pstree.remy@npm:^1.1.8": version: 1.1.8 resolution: "pstree.remy@npm:1.1.8" From e5427056b206382d1c49a43b4d864dd8164bcaae Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 9 Nov 2023 20:32:16 +0300 Subject: [PATCH 18/34] fix almost all comments --- package.json | 2 +- src/presentation/http/router/auth.test.ts | 27 +++++++++++++++-------- src/tests/test-data/notes.json | 2 +- src/tests/utils/insert-data.ts | 4 ++-- 4 files changed, 22 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index 338fb77f..0c15b22d 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,7 @@ "@fastify/swagger-ui": "^1.9.3", "@testcontainers/postgresql": "^10.2.1", "arg": "^5.0.2", - "axios": "^1.6.0", + "fastify": "^4.17.0", "http-status-codes": "^2.2.0", "jsonwebtoken": "^9.0.0", diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index eee080e6..6c359b38 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -13,18 +13,19 @@ describe('Auth API', () => { expect(response?.statusCode).toBe(expectedStatus); - const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; + const body = await response?.json(); expect(body).toStrictEqual({ message: 'Session is not valid' }); }); - test('Returns 200 when session was authorized', async () => { + test('Returns 200 when refreshToken is in database', async () => { const expectedStatus = 200; /** Define the token to include in the request body */ const refreshToken = 'pv-jIqfPj1'; /** Define regular expression to be sure that string is not empty */ - const notEmptyString = /^.$/; + const notEmptyString = /^.+$/; + const expectedAuthReply = { refreshToken: notEmptyString, @@ -40,26 +41,34 @@ describe('Auth API', () => { expect(response?.statusCode).toBe(expectedStatus); - const body = response?.body !== undefined ? JSON.parse(response?.body) : {}; + const body = await response?.json(); + + expect(body.refreshToken).toBeDefined(); + expect(body.refreshToken).not.toBeNull(); + expect(body.refreshToken).not.toBe(''); + + expect(body.accessToken).toBeDefined(); + expect(body.accessToken).not.toBeNull(); + expect(body.accessToken).not.toBe(''); + expect(body).toMatchObject(expectedAuthReply); }); test('Returns 401 when expiration day has passed', async () => { const expectedStatus=401; - const refreshToken = 'pv-jIqfPj1'; - /** Set the expiration day to a date in the past */ - const pastExpirationDay = new Date('Sat, 03 Nov 2022 16:53:36 GMT').toUTCString(); + const refreshToken = 'F5tTF24K9Q'; + const response=await global.api?.fakeRequest({ method: 'POST', url: '/auth', - headers:{ date:pastExpirationDay }, + body:{ token: refreshToken }, }); expect (response?.statusCode).toBe(expectedStatus); - const body = response?.body !== undefined ? JSON.parse(response?.body):{}; + const body = await response?.json(); expect(body).toStrictEqual({ message:'Session is not valid' }); }); diff --git a/src/tests/test-data/notes.json b/src/tests/test-data/notes.json index b5747fed..4fc09cbf 100644 --- a/src/tests/test-data/notes.json +++ b/src/tests/test-data/notes.json @@ -1,4 +1,4 @@ - [ +[ { "id": 1, "public_id": "note_1", diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 21c26503..58bfda22 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -2,7 +2,7 @@ import type SequelizeOrm from '@repository/storage/postgres/orm/index.js'; import users from '../test-data/users.json'; import notes from '../test-data/notes.json'; import noteSettings from '../test-data/notes-settings.json'; -import tokens from '../test-data/userSessions.json'; +import userSessions from '../test-data/userSessions.json'; /** * Fills in the database with users data @@ -43,7 +43,7 @@ async function insertNoteSettings(db: SequelizeOrm): Promise { * @param db - SequelizeOrm instance */ async function insertUserSessions(db:SequelizeOrm): Promise { - for (const token of tokens) { + for (const token of userSessions) { await db.connection.query(`INSERT INTO public.user_sessions("id","user_id","refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id}, '${token.refreshToken}', '${token.refresh_token_expires_at}')`); } } From 10513f80052940a6489fb12d2e584eff1689e5e9 Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 9 Nov 2023 20:39:12 +0300 Subject: [PATCH 19/34] fix almost all comments v2.0 --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index 0c15b22d..80240b7a 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,6 @@ "@fastify/swagger-ui": "^1.9.3", "@testcontainers/postgresql": "^10.2.1", "arg": "^5.0.2", - "fastify": "^4.17.0", "http-status-codes": "^2.2.0", "jsonwebtoken": "^9.0.0", From 8c2fd5729cdaa97e7fcd8c8cb9eb35455d95ef87 Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 9 Nov 2023 21:03:16 +0300 Subject: [PATCH 20/34] fix almost all comments v2.1 --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 80240b7a..0c15b22d 100644 --- a/package.json +++ b/package.json @@ -42,6 +42,7 @@ "@fastify/swagger-ui": "^1.9.3", "@testcontainers/postgresql": "^10.2.1", "arg": "^5.0.2", + "fastify": "^4.17.0", "http-status-codes": "^2.2.0", "jsonwebtoken": "^9.0.0", From a65eeeb367651a14766bbc87b23b0c0cd7b73f90 Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 9 Nov 2023 21:43:59 +0300 Subject: [PATCH 21/34] fix almost all comments v2.2 --- package.json | 3 +- yarn.lock | 81 +--------------------------------------------------- 2 files changed, 2 insertions(+), 82 deletions(-) diff --git a/package.json b/package.json index 0c15b22d..10abf1e4 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,6 @@ "@fastify/swagger-ui": "^1.9.3", "@testcontainers/postgresql": "^10.2.1", "arg": "^5.0.2", - "fastify": "^4.17.0", "http-status-codes": "^2.2.0", "jsonwebtoken": "^9.0.0", @@ -56,4 +55,4 @@ "zod": "^3.21.4" }, "packageManager": "yarn@3.6.4" -} +} \ No newline at end of file diff --git a/yarn.lock b/yarn.lock index 88511424..89bf505f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1377,13 +1377,6 @@ __metadata: languageName: node linkType: hard -"asynckit@npm:^0.4.0": - version: 0.4.0 - resolution: "asynckit@npm:0.4.0" - checksum: 7b78c451df768adba04e2d02e63e2d0bf3b07adcd6e42b4cf665cb7ce899bedd344c69a1dcbce355b5f972d597b25aaa1c1742b52cffd9caccb22f348114f6be - languageName: node - linkType: hard - "atomic-sleep@npm:^1.0.0": version: 1.0.0 resolution: "atomic-sleep@npm:1.0.0" @@ -1409,17 +1402,6 @@ __metadata: languageName: node linkType: hard -"axios@npm:^1.6.0": - version: 1.6.0 - resolution: "axios@npm:1.6.0" - dependencies: - follow-redirects: ^1.15.0 - form-data: ^4.0.0 - proxy-from-env: ^1.1.0 - checksum: c7c9f2ae9e0b9bad7d6f9a4dff030930b12ee667dedf54c3c776714f91681feb743c509ac0796ae5c01e12c4ab4a2bee74905068dd200fbc1ab86f9814578fb0 - languageName: node - linkType: hard - "b4a@npm:^1.6.4": version: 1.6.4 resolution: "b4a@npm:1.6.4" @@ -1725,15 +1707,6 @@ __metadata: languageName: node linkType: hard -"combined-stream@npm:^1.0.8": - version: 1.0.8 - resolution: "combined-stream@npm:1.0.8" - dependencies: - delayed-stream: ~1.0.0 - checksum: 49fa4aeb4916567e33ea81d088f6584749fc90c7abec76fd516bf1c5aa5c79f3584b5ba3de6b86d26ddd64bae5329c4c7479343250cfe71c75bb366eae53bb7c - languageName: node - linkType: hard - "commander@npm:^9.0.0": version: 9.5.0 resolution: "commander@npm:9.5.0" @@ -1911,13 +1884,6 @@ __metadata: languageName: node linkType: hard -"delayed-stream@npm:~1.0.0": - version: 1.0.0 - resolution: "delayed-stream@npm:1.0.0" - checksum: 46fe6e83e2cb1d85ba50bd52803c68be9bd953282fa7096f51fc29edd5d67ff84ff753c51966061e5ba7cb5e47ef6d36a91924eddb7f3f3483b1c560f77a0020 - languageName: node - linkType: hard - "delegates@npm:^1.0.0": version: 1.0.0 resolution: "delegates@npm:1.0.0" @@ -2727,16 +2693,6 @@ __metadata: languageName: node linkType: hard -"follow-redirects@npm:^1.15.0": - version: 1.15.3 - resolution: "follow-redirects@npm:1.15.3" - peerDependenciesMeta: - debug: - optional: true - checksum: 584da22ec5420c837bd096559ebfb8fe69d82512d5585004e36a3b4a6ef6d5905780e0c74508c7b72f907d1fa2b7bd339e613859e9c304d0dc96af2027fd0231 - languageName: node - linkType: hard - "for-each@npm:^0.3.3": version: 0.3.3 resolution: "for-each@npm:0.3.3" @@ -2756,17 +2712,6 @@ __metadata: languageName: node linkType: hard -"form-data@npm:^4.0.0": - version: 4.0.0 - resolution: "form-data@npm:4.0.0" - dependencies: - asynckit: ^0.4.0 - combined-stream: ^1.0.8 - mime-types: ^2.1.12 - checksum: 01135bf8675f9d5c61ff18e2e2932f719ca4de964e3be90ef4c36aacfc7b9cb2fceb5eca0b7e0190e3383fe51c5b37f4cb80b62ca06a99aaabfcfd6ac7c9328c - languageName: node - linkType: hard - "forwarded@npm:0.2.0": version: 0.2.0 resolution: "forwarded@npm:0.2.0" @@ -3861,22 +3806,6 @@ __metadata: languageName: node linkType: hard -"mime-db@npm:1.52.0": - version: 1.52.0 - resolution: "mime-db@npm:1.52.0" - checksum: 0d99a03585f8b39d68182803b12ac601d9c01abfa28ec56204fa330bc9f3d1c5e14beb049bafadb3dbdf646dfb94b87e24d4ec7b31b7279ef906a8ea9b6a513f - languageName: node - linkType: hard - -"mime-types@npm:^2.1.12": - version: 2.1.35 - resolution: "mime-types@npm:2.1.35" - dependencies: - mime-db: 1.52.0 - checksum: 89a5b7f1def9f3af5dad6496c5ed50191ae4331cc5389d7c521c8ad28d5fdad2d06fd81baf38fed813dc4e46bb55c8145bb0ff406330818c9cf712fb2e9b3836 - languageName: node - linkType: hard - "mime@npm:^3.0.0": version: 3.0.0 resolution: "mime@npm:3.0.0" @@ -4218,7 +4147,6 @@ __metadata: "@types/node": ^20.2.3 "@types/pg": ^8.10.2 arg: ^5.0.2 - axios: ^1.6.0 eslint: ^8.41.0 eslint-config-codex: ^1.8.3 eslint-plugin-vitest: ^0.3.1 @@ -4865,13 +4793,6 @@ __metadata: languageName: node linkType: hard -"proxy-from-env@npm:^1.1.0": - version: 1.1.0 - resolution: "proxy-from-env@npm:1.1.0" - checksum: ed7fcc2ba0a33404958e34d95d18638249a68c430e30fcb6c478497d72739ba64ce9810a24f53a7d921d0c065e5b78e3822759800698167256b04659366ca4d4 - languageName: node - linkType: hard - "pstree.remy@npm:^1.1.8": version: 1.1.8 resolution: "pstree.remy@npm:1.1.8" @@ -6470,4 +6391,4 @@ __metadata: resolution: "zod@npm:3.22.4" checksum: 80bfd7f8039b24fddeb0718a2ec7c02aa9856e4838d6aa4864335a047b6b37a3273b191ef335bf0b2002e5c514ef261ffcda5a589fb084a48c336ffc4cdbab7f languageName: node - linkType: hard + linkType: hard \ No newline at end of file From f45371fe344c584c16de90213050cc5e7b161a5a Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 9 Nov 2023 21:57:27 +0300 Subject: [PATCH 22/34] fix almost all comments v2.3 --- package.json | 2 +- yarn.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 10abf1e4..80240b7a 100644 --- a/package.json +++ b/package.json @@ -55,4 +55,4 @@ "zod": "^3.21.4" }, "packageManager": "yarn@3.6.4" -} \ No newline at end of file +} diff --git a/yarn.lock b/yarn.lock index 89bf505f..5d3f8483 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6391,4 +6391,4 @@ __metadata: resolution: "zod@npm:3.22.4" checksum: 80bfd7f8039b24fddeb0718a2ec7c02aa9856e4838d6aa4864335a047b6b37a3273b191ef335bf0b2002e5c514ef261ffcda5a589fb084a48c336ffc4cdbab7f languageName: node - linkType: hard \ No newline at end of file + linkType: hard From 477bb34eae3768351ef4c2bc0251de32136fd3dc Mon Sep 17 00:00:00 2001 From: Danya Date: Fri, 10 Nov 2023 22:20:55 +0300 Subject: [PATCH 23/34] add script to dynamicly set tomorrow expiration day for token --- .github/workflows/run-build-check.yml | 7 +++--- .github/workflows/run-eslint-check.yml | 9 ++++--- .github/workflows/run-tests.yml | 9 ++++--- src/tests/test-data/userSessions.json | 24 +++++++++---------- src/tests/utils/insert-data.ts | 5 ++++ .../utils/insert-tomorrow-expiration-day.ts | 18 ++++++++++++++ 6 files changed, 46 insertions(+), 26 deletions(-) create mode 100644 src/tests/utils/insert-tomorrow-expiration-day.ts diff --git a/.github/workflows/run-build-check.yml b/.github/workflows/run-build-check.yml index 2b35f141..3bbfbc66 100644 --- a/.github/workflows/run-build-check.yml +++ b/.github/workflows/run-build-check.yml @@ -3,14 +3,13 @@ name: Run build check on: push: branches: - - '*' + - 'main' tags: - 'v*' pull_request: - types: [opened, edited] - branches: - - '*' + types: [opened, synchronize, reopened] + jobs: build: diff --git a/.github/workflows/run-eslint-check.yml b/.github/workflows/run-eslint-check.yml index 9b80e964..478d7b59 100644 --- a/.github/workflows/run-eslint-check.yml +++ b/.github/workflows/run-eslint-check.yml @@ -3,14 +3,13 @@ name: Run ESlint check on: push: branches: - - '*' + - 'main' tags: - 'v*' - + pull_request: - types: [opened, edited] - branches: - - '*' + types: [opened, synchronize, reopened] + jobs: eslint: diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index d3ae72da..e4a034ff 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -3,14 +3,13 @@ name: Run tests on: push: branches: - - '*' + - 'main' tags: - 'v*' - + pull_request: - types: [opened, edited] - branches: - - '*' + types: [opened, synchronize, reopened] + jobs: tests: diff --git a/src/tests/test-data/userSessions.json b/src/tests/test-data/userSessions.json index 21c4ad52..7e02c2d8 100644 --- a/src/tests/test-data/userSessions.json +++ b/src/tests/test-data/userSessions.json @@ -1,14 +1,14 @@ [ - { - "refreshToken": "pv-jIqfPj1", - "refresh_token_expires_at": "2024-11-04 10:23:54+02", - "user_Id": 1, - "Id":1 - }, - { - "refreshToken": "F5tTF24K9Q", - "refresh_token_expires_at": "2023-11-09 11:23:54+02", - "user_Id": 1, - "Id":2 - } + { + "refreshToken": "pv-jIqfPj1", + "refresh_token_expires_at": "2023-11-11 19:17:54+02", + "user_Id": 1, + "Id": 1 + }, + { + "refreshToken": "F5tTF24K9Q", + "refresh_token_expires_at": "2023-11-09 11:23:54+02", + "user_Id": 1, + "Id": 2 + } ] \ No newline at end of file diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 58bfda22..21030ef5 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -3,7 +3,12 @@ import users from '../test-data/users.json'; import notes from '../test-data/notes.json'; import noteSettings from '../test-data/notes-settings.json'; import userSessions from '../test-data/userSessions.json'; +import { updateRefreshTokenExpiry } from './insert-tomorrow-expiration-day'; +const filePath = 'src/tests/test-data/userSessions.json'; + +/** set tomorrow expiration day for token */ +updateRefreshTokenExpiry(filePath); /** * Fills in the database with users data * diff --git a/src/tests/utils/insert-tomorrow-expiration-day.ts b/src/tests/utils/insert-tomorrow-expiration-day.ts new file mode 100644 index 00000000..318ef6cf --- /dev/null +++ b/src/tests/utils/insert-tomorrow-expiration-day.ts @@ -0,0 +1,18 @@ +import * as fs from 'fs'; +/** create string of tomorrow expiration day */ +export const formattedDate = (): string => { + const tomorrow = new Date(); + const border = 19; + + tomorrow.setDate(tomorrow.getDate() + 1); + + return tomorrow.toISOString().slice(0, border) + .replace('T', ' ') + '+02'; +}; + +export const updateRefreshTokenExpiry = (filePath: string): void => { + const userSessionData = JSON.parse(fs.readFileSync(filePath, 'utf-8')); + + userSessionData[0].refresh_token_expires_at = formattedDate(); + fs.writeFileSync(filePath, JSON.stringify(userSessionData, null, 2), 'utf-8'); +}; From 702079425989725ed46f1fb04f19081e27b9e0bc Mon Sep 17 00:00:00 2001 From: Danya Date: Sun, 12 Nov 2023 20:53:37 +0300 Subject: [PATCH 24/34] looks like that all right --- src/tests/test-data/userSessions.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/test-data/userSessions.json b/src/tests/test-data/userSessions.json index 7e02c2d8..604ef8aa 100644 --- a/src/tests/test-data/userSessions.json +++ b/src/tests/test-data/userSessions.json @@ -1,7 +1,7 @@ [ { "refreshToken": "pv-jIqfPj1", - "refresh_token_expires_at": "2023-11-11 19:17:54+02", + "refresh_token_expires_at": "2023-11-13 17:45:31+02", "user_Id": 1, "Id": 1 }, From d1f42f9bbadd70877f6009b82c787149215c93d3 Mon Sep 17 00:00:00 2001 From: Danya Date: Sun, 12 Nov 2023 22:13:41 +0300 Subject: [PATCH 25/34] add script to dynamically update expiration date --- .github/workflows/deploy-API.yml | 2 +- .github/workflows/run-build-check.yml | 3 +-- .github/workflows/run-eslint-check.yml | 1 - .github/workflows/run-tests.yml | 2 -- src/tests/test-data/userSessions.json | 2 +- 5 files changed, 3 insertions(+), 7 deletions(-) diff --git a/.github/workflows/deploy-API.yml b/.github/workflows/deploy-API.yml index 038f99b9..a8f77852 100644 --- a/.github/workflows/deploy-API.yml +++ b/.github/workflows/deploy-API.yml @@ -53,4 +53,4 @@ jobs: context: . tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} - push: ${{ startsWith(github.ref, 'refs/tags/v') || endsWith(github.ref, '/stage') || endsWith(github.ref, '/main') }} + push: ${{ startsWith(github.ref, 'refs/tags/v') || endsWith(github.ref, '/stage') || endsWith(github.ref, '/main') }} \ No newline at end of file diff --git a/.github/workflows/run-build-check.yml b/.github/workflows/run-build-check.yml index 3bbfbc66..b2777626 100644 --- a/.github/workflows/run-build-check.yml +++ b/.github/workflows/run-build-check.yml @@ -10,7 +10,6 @@ on: pull_request: types: [opened, synchronize, reopened] - jobs: build: name: Run yarn build @@ -31,4 +30,4 @@ jobs: - name: Build run: yarn build - + \ No newline at end of file diff --git a/.github/workflows/run-eslint-check.yml b/.github/workflows/run-eslint-check.yml index 478d7b59..2dcc99d0 100644 --- a/.github/workflows/run-eslint-check.yml +++ b/.github/workflows/run-eslint-check.yml @@ -10,7 +10,6 @@ on: pull_request: types: [opened, synchronize, reopened] - jobs: eslint: name: Run eslint check diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index e4a034ff..377a2f63 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -10,7 +10,6 @@ on: pull_request: types: [opened, synchronize, reopened] - jobs: tests: runs-on: ubuntu-22.04 @@ -54,4 +53,3 @@ jobs: - name: Run tests run: yarn test - diff --git a/src/tests/test-data/userSessions.json b/src/tests/test-data/userSessions.json index 604ef8aa..da0404be 100644 --- a/src/tests/test-data/userSessions.json +++ b/src/tests/test-data/userSessions.json @@ -1,7 +1,7 @@ [ { "refreshToken": "pv-jIqfPj1", - "refresh_token_expires_at": "2023-11-13 17:45:31+02", + "refresh_token_expires_at": "2023-11-13 19:06:16+02", "user_Id": 1, "Id": 1 }, From adbc3cbf5c0a27499554223fc9fb2d537d02e661 Mon Sep 17 00:00:00 2001 From: Danya Date: Mon, 13 Nov 2023 19:49:27 +0300 Subject: [PATCH 26/34] fix review's comments --- src/presentation/http/router/auth.test.ts | 11 ++++++----- src/tests/test-data/user-sessions.json | 12 ++++++------ src/tests/test-data/userSessions.json | 14 -------------- src/tests/utils/insert-data.ts | 13 +------------ src/tests/utils/insert-tomorrow-expiration-day.ts | 2 +- 5 files changed, 14 insertions(+), 38 deletions(-) delete mode 100644 src/tests/test-data/userSessions.json diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 6c359b38..ff47f8ee 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -4,7 +4,7 @@ describe('Auth API', () => { describe('POST /auth', () => { test('Returns 401 when session is not valid', async () => { const expectedStatus = 401; - const refreshToken = 'not-validToken'; + const refreshToken = 'EF1JX65xSZ'; const response = await global.api?.fakeRequest({ method: 'POST', url: '/auth', @@ -36,7 +36,8 @@ describe('Auth API', () => { const response = await global.api?.fakeRequest({ method: 'POST', url: '/auth', - body: { token: refreshToken }, /** Include the token in the request body*/ + /** Include the token in the request body*/ + body: { token: refreshToken }, }); expect(response?.statusCode).toBe(expectedStatus); @@ -56,15 +57,15 @@ describe('Auth API', () => { }); test('Returns 401 when expiration day has passed', async () => { - const expectedStatus=401; - const refreshToken = 'F5tTF24K9Q'; + const expectedStatus = 401; + const outdatedToken = 'F5tTF24K9Q'; const response=await global.api?.fakeRequest({ method: 'POST', url: '/auth', - body:{ token: refreshToken }, + body:{ token: outdatedToken }, }); expect (response?.statusCode).toBe(expectedStatus); diff --git a/src/tests/test-data/user-sessions.json b/src/tests/test-data/user-sessions.json index 143c628d..2ebb5ffe 100644 --- a/src/tests/test-data/user-sessions.json +++ b/src/tests/test-data/user-sessions.json @@ -1,13 +1,13 @@ [ { - "id" : 7, - "user_id" : 4, - "refresh_token" : "IqrTkSKmel", - "refresh_token_expires_at" : "2025-11-21 19:19:40.911+03" + "id": 7, + "user_id": 4, + "refresh_token": "IqrTkSKmel", + "refresh_token_expires_at": "2025-11-21 19:19:40.911+03" }, { "refresh_token": "pv-jIqfPj1", - "refresh_token_expires_at": "2023-11-13 19:06:16+02", + "refresh_token_expires_at": "2023-11-14 16:47:51+02", "user_id": 1, "id": 5 }, @@ -17,4 +17,4 @@ "user_id": 1, "id": 6 } -] +] \ No newline at end of file diff --git a/src/tests/test-data/userSessions.json b/src/tests/test-data/userSessions.json deleted file mode 100644 index 0e44deda..00000000 --- a/src/tests/test-data/userSessions.json +++ /dev/null @@ -1,14 +0,0 @@ -[ - { - "refreshToken": "pv-jIqfPj1", - "refresh_token_expires_at": "2023-11-13 20:53:50+02", - "user_Id": 1, - "Id": 1 - }, - { - "refreshToken": "F5tTF24K9Q", - "refresh_token_expires_at": "2023-11-09 11:23:54+02", - "user_Id": 1, - "Id": 2 - } -] \ No newline at end of file diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 84e222f7..1fee1fd0 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -6,7 +6,7 @@ import noteSettings from '../test-data/notes-settings.json'; // import user_sessions from '../test-data/userSessions.json'; import { updateRefreshTokenExpiry } from './insert-tomorrow-expiration-day'; -const filePath = 'src/tests/test-data/userSessions.json'; +const filePath = 'src/tests/test-data/user-sessions.json'; /** set tomorrow expiration day for token */ updateRefreshTokenExpiry(filePath); @@ -53,16 +53,6 @@ async function insertNoteSettings(db: SequelizeOrm): Promise { } } -/** - * Fills in the database with tokens - * - * @param db - SequelizeOrm instance - */ -// async function insertUser_sessions(db:SequelizeOrm): Promise { -// for (const token of userSessions) { -// await db.connection.query(`INSERT INTO public.user_sessions("id","user_id","refresh_token","refresh_token_expires_at") VALUES (${token.Id}, ${token.user_Id}, '${token.refreshToken}', '${token.refresh_token_expires_at}')`); -// } -// } /** * Fills in the database with test data @@ -74,6 +64,5 @@ export async function insertData(db: SequelizeOrm): Promise { await insertUserSessions(db); await insertNotes(db); await insertNoteSettings(db); - // await insertUser_sessions(db); } diff --git a/src/tests/utils/insert-tomorrow-expiration-day.ts b/src/tests/utils/insert-tomorrow-expiration-day.ts index 318ef6cf..e5441c47 100644 --- a/src/tests/utils/insert-tomorrow-expiration-day.ts +++ b/src/tests/utils/insert-tomorrow-expiration-day.ts @@ -13,6 +13,6 @@ export const formattedDate = (): string => { export const updateRefreshTokenExpiry = (filePath: string): void => { const userSessionData = JSON.parse(fs.readFileSync(filePath, 'utf-8')); - userSessionData[0].refresh_token_expires_at = formattedDate(); + userSessionData[1].refresh_token_expires_at = formattedDate(); fs.writeFileSync(filePath, JSON.stringify(userSessionData, null, 2), 'utf-8'); }; From d41a1f78af08c01f255a91d99fb6f92404c91833 Mon Sep 17 00:00:00 2001 From: Danya Date: Mon, 13 Nov 2023 20:32:10 +0300 Subject: [PATCH 27/34] fix others review's comments --- src/presentation/http/router/auth.test.ts | 4 ++-- src/tests/test-data/user-sessions.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index ff47f8ee..391c2dcc 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -22,7 +22,7 @@ describe('Auth API', () => { const expectedStatus = 200; /** Define the token to include in the request body */ - const refreshToken = 'pv-jIqfPj1'; + const missingToken = 'pv-jIqfPj1'; /** Define regular expression to be sure that string is not empty */ const notEmptyString = /^.+$/; @@ -37,7 +37,7 @@ describe('Auth API', () => { method: 'POST', url: '/auth', /** Include the token in the request body*/ - body: { token: refreshToken }, + body: { token: missingToken }, }); expect(response?.statusCode).toBe(expectedStatus); diff --git a/src/tests/test-data/user-sessions.json b/src/tests/test-data/user-sessions.json index 2ebb5ffe..8d4b79bb 100644 --- a/src/tests/test-data/user-sessions.json +++ b/src/tests/test-data/user-sessions.json @@ -7,7 +7,7 @@ }, { "refresh_token": "pv-jIqfPj1", - "refresh_token_expires_at": "2023-11-14 16:47:51+02", + "refresh_token_expires_at": "2023-11-14 17:27:04+02", "user_id": 1, "id": 5 }, From 94ee6902fbc11dbb02d102bceae41ea30b66031b Mon Sep 17 00:00:00 2001 From: Danya Date: Tue, 14 Nov 2023 23:49:27 +0300 Subject: [PATCH 28/34] fix review's comments except dynamically updating date --- src/presentation/http/router/auth.test.ts | 26 ++++++++++------------- src/tests/test-data/user-sessions.json | 2 +- src/tests/utils/insert-data.ts | 1 - 3 files changed, 12 insertions(+), 17 deletions(-) diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 391c2dcc..8758c089 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -18,20 +18,11 @@ describe('Auth API', () => { expect(body).toStrictEqual({ message: 'Session is not valid' }); }); - test('Returns 200 when refreshToken is in database', async () => { + test('Returns 200 when refreshToken is in the database', async () => { const expectedStatus = 200; /** Define the token to include in the request body */ const missingToken = 'pv-jIqfPj1'; - /** Define regular expression to be sure that string is not empty */ - const notEmptyString = /^.+$/; - - - const expectedAuthReply = { - refreshToken: notEmptyString, - accessToken: notEmptyString, - }; - const response = await global.api?.fakeRequest({ method: 'POST', @@ -44,18 +35,23 @@ describe('Auth API', () => { const body = await response?.json(); - expect(body.refreshToken).toBeDefined(); - expect(body.refreshToken).not.toBeNull(); - expect(body.refreshToken).not.toBe(''); + expect(typeof body.refreshToken).toBe('string'); + expect(typeof body.accessToken).toBe('string'); + // Optionally, you can also check if the strings are not empty or null + expect(body.refreshToken).toBeDefined(); expect(body.accessToken).toBeDefined(); + expect(body.refreshToken).not.toBeNull(); expect(body.accessToken).not.toBeNull(); + expect(body.refreshToken).not.toBe(''); expect(body.accessToken).not.toBe(''); - - expect(body).toMatchObject(expectedAuthReply); + // Check if the response object matches the expected structure + expect(body).toHaveProperty('refreshToken'); + expect(body).toHaveProperty('accessToken'); }); + test('Returns 401 when expiration day has passed', async () => { const expectedStatus = 401; const outdatedToken = 'F5tTF24K9Q'; diff --git a/src/tests/test-data/user-sessions.json b/src/tests/test-data/user-sessions.json index 8d4b79bb..463c4b2b 100644 --- a/src/tests/test-data/user-sessions.json +++ b/src/tests/test-data/user-sessions.json @@ -7,7 +7,7 @@ }, { "refresh_token": "pv-jIqfPj1", - "refresh_token_expires_at": "2023-11-14 17:27:04+02", + "refresh_token_expires_at": "2023-11-15 20:47:30+02", "user_id": 1, "id": 5 }, diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 1fee1fd0..756f4845 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -3,7 +3,6 @@ import users from '../test-data/users.json'; import userSessions from '../test-data/user-sessions.json'; import notes from '../test-data/notes.json'; import noteSettings from '../test-data/notes-settings.json'; -// import user_sessions from '../test-data/userSessions.json'; import { updateRefreshTokenExpiry } from './insert-tomorrow-expiration-day'; const filePath = 'src/tests/test-data/user-sessions.json'; From 33d01673e3a6700940705f9c9958286b5b9e3637 Mon Sep 17 00:00:00 2001 From: Danya Date: Wed, 15 Nov 2023 00:08:02 +0300 Subject: [PATCH 29/34] rewrite insertUserSessions to fill dynamically updated expiration date --- src/tests/utils/insert-data.ts | 8 ++++---- src/tests/utils/insert-tomorrow-expiration-day.ts | 14 ++++++-------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 756f4845..28abd798 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -3,12 +3,10 @@ import users from '../test-data/users.json'; import userSessions from '../test-data/user-sessions.json'; import notes from '../test-data/notes.json'; import noteSettings from '../test-data/notes-settings.json'; -import { updateRefreshTokenExpiry } from './insert-tomorrow-expiration-day'; +import { formattedDate } from './insert-tomorrow-expiration-day'; +const date = formattedDate(); -const filePath = 'src/tests/test-data/user-sessions.json'; -/** set tomorrow expiration day for token */ -updateRefreshTokenExpiry(filePath); /** * Fills in the database with users data * @@ -28,6 +26,8 @@ async function insertUsers(db: SequelizeOrm): Promise { async function insertUserSessions(db: SequelizeOrm): Promise { for (const userSession of userSessions) { await db.connection.query(`INSERT INTO public.user_sessions (id, "user_id", "refresh_token", "refresh_token_expires_at") VALUES (${userSession.id}, ${userSession.user_id}, '${userSession.refresh_token}', '${userSession.refresh_token_expires_at}')`); + await db.connection.query(`UPDATE public.user_sessions SET "refresh_token_expires_at" = '${date}' WHERE id = 5; + `); } } /** diff --git a/src/tests/utils/insert-tomorrow-expiration-day.ts b/src/tests/utils/insert-tomorrow-expiration-day.ts index e5441c47..85716a84 100644 --- a/src/tests/utils/insert-tomorrow-expiration-day.ts +++ b/src/tests/utils/insert-tomorrow-expiration-day.ts @@ -1,18 +1,16 @@ -import * as fs from 'fs'; /** create string of tomorrow expiration day */ export const formattedDate = (): string => { const tomorrow = new Date(); const border = 19; + tomorrow.setDate(tomorrow.getDate() + 1); - return tomorrow.toISOString().slice(0, border) + const newExpirationDay: string = tomorrow.toISOString().slice(0, border) .replace('T', ' ') + '+02'; -}; -export const updateRefreshTokenExpiry = (filePath: string): void => { - const userSessionData = JSON.parse(fs.readFileSync(filePath, 'utf-8')); - - userSessionData[1].refresh_token_expires_at = formattedDate(); - fs.writeFileSync(filePath, JSON.stringify(userSessionData, null, 2), 'utf-8'); + return newExpirationDay; }; +// Export the newExpirationDay variable directly +export const newExpirationDay: string = formattedDate(); + From 1e9bd9e4a97f15dd4fce9a11665a1b2d45a75f6a Mon Sep 17 00:00:00 2001 From: Danya Date: Thu, 16 Nov 2023 12:03:03 +0300 Subject: [PATCH 30/34] move function to insert dynamic updated date in auth.test.ts --- src/presentation/http/router/auth.test.ts | 25 +++++++++++++++++++++++ src/tests/utils/insert-data.ts | 4 ---- src/tests/utils/setup.ts | 3 ++- 3 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 8758c089..69e64e38 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -1,4 +1,28 @@ +import { formattedDate } from '@tests/utils/insert-tomorrow-expiration-day'; import { describe, test, expect } from 'vitest'; +import type SequelizeOrm from '@repository/storage/postgres/orm/index.js'; + + +/** + * Fills in the database with user sessions + * + * @param db - SequelizeOrm instance + */ +async function insertUserSessions(db: SequelizeOrm): Promise { + const date = formattedDate(); + + await db.connection.query(`UPDATE public.user_sessions SET "refresh_token_expires_at" = '${date}' WHERE id = 5; + `); +} +/** + * Fills in the database with test data + * + * @param db - SequelizeOrm instance + */ +export async function insertDataForAuthTest(db: SequelizeOrm): Promise { + await insertUserSessions(db); +} + describe('Auth API', () => { describe('POST /auth', () => { @@ -18,6 +42,7 @@ describe('Auth API', () => { expect(body).toStrictEqual({ message: 'Session is not valid' }); }); + test('Returns 200 when refreshToken is in the database', async () => { const expectedStatus = 200; diff --git a/src/tests/utils/insert-data.ts b/src/tests/utils/insert-data.ts index 28abd798..149991a4 100644 --- a/src/tests/utils/insert-data.ts +++ b/src/tests/utils/insert-data.ts @@ -3,8 +3,6 @@ import users from '../test-data/users.json'; import userSessions from '../test-data/user-sessions.json'; import notes from '../test-data/notes.json'; import noteSettings from '../test-data/notes-settings.json'; -import { formattedDate } from './insert-tomorrow-expiration-day'; -const date = formattedDate(); /** @@ -26,8 +24,6 @@ async function insertUsers(db: SequelizeOrm): Promise { async function insertUserSessions(db: SequelizeOrm): Promise { for (const userSession of userSessions) { await db.connection.query(`INSERT INTO public.user_sessions (id, "user_id", "refresh_token", "refresh_token_expires_at") VALUES (${userSession.id}, ${userSession.user_id}, '${userSession.refresh_token}', '${userSession.refresh_token_expires_at}')`); - await db.connection.query(`UPDATE public.user_sessions SET "refresh_token_expires_at" = '${date}' WHERE id = 5; - `); } } /** diff --git a/src/tests/utils/setup.ts b/src/tests/utils/setup.ts index c9be8c95..afe65af3 100644 --- a/src/tests/utils/setup.ts +++ b/src/tests/utils/setup.ts @@ -2,6 +2,7 @@ import path from 'path'; import type { StartedPostgreSqlContainer } from '@testcontainers/postgresql'; import { PostgreSqlContainer } from '@testcontainers/postgresql'; +import { insertDataForAuthTest } from '@presentation/http/router/auth.test'; import { insertData } from './insert-data'; import { initORM, init as initRepositories } from '@repository/index.js'; import { init as initDomainServices } from '@domain/index.js'; @@ -57,7 +58,7 @@ beforeAll(async () => { await runTenantMigrations(migrationsPath, postgresContainer.getConnectionUri()); await insertData(orm); - + await insertDataForAuthTest(orm); global.api = api; global.auth = (userId: number) => { return domainServices.authService.signAccessToken({ id : userId }); From 281460fdfb8ad86d8824e6eb0b8ee3c257839bbf Mon Sep 17 00:00:00 2001 From: Tanya Fomina Date: Sat, 25 Nov 2023 16:25:42 +0300 Subject: [PATCH 31/34] Remove useless changes --- .github/workflows/deploy-API.yml | 2 +- .github/workflows/run-build-check.yml | 2 +- .github/workflows/run-tests.yml | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-API.yml b/.github/workflows/deploy-API.yml index a8f77852..038f99b9 100644 --- a/.github/workflows/deploy-API.yml +++ b/.github/workflows/deploy-API.yml @@ -53,4 +53,4 @@ jobs: context: . tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} - push: ${{ startsWith(github.ref, 'refs/tags/v') || endsWith(github.ref, '/stage') || endsWith(github.ref, '/main') }} \ No newline at end of file + push: ${{ startsWith(github.ref, 'refs/tags/v') || endsWith(github.ref, '/stage') || endsWith(github.ref, '/main') }} diff --git a/.github/workflows/run-build-check.yml b/.github/workflows/run-build-check.yml index b2777626..9e61cf5e 100644 --- a/.github/workflows/run-build-check.yml +++ b/.github/workflows/run-build-check.yml @@ -1,4 +1,4 @@ -name: Run build check +name: Build check on: push: diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 377a2f63..9368da48 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -53,3 +53,4 @@ jobs: - name: Run tests run: yarn test + From 9d9da5a7ace299141e33311f4dc1417a7f9f1a25 Mon Sep 17 00:00:00 2001 From: Tanya Fomina Date: Sat, 25 Nov 2023 17:37:51 +0300 Subject: [PATCH 32/34] Various fixes --- .eslintrc.cjs | 6 ++ .github/workflows/run-build-check.yml | 2 - src/presentation/http/router/auth.test.ts | 69 +++++-------------- src/tests/test-data/user-sessions.json | 20 ++---- ...-day.ts => get-tomorrow-date-formatted.ts} | 9 ++- src/tests/utils/setup.ts | 6 +- 6 files changed, 38 insertions(+), 74 deletions(-) rename src/tests/utils/{insert-tomorrow-expiration-day.ts => get-tomorrow-date-formatted.ts} (54%) diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 889b85c8..9eb082ae 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -10,6 +10,12 @@ module.exports = { 'tsconfigRootDir': __dirname, 'sourceType': 'module', }, + 'overrides': [{ + 'files': ['*.test.ts'], + 'rules': { + '@typescript-eslint/no-magic-numbers': 'off' + } + }], 'rules': { '@typescript-eslint/naming-convention': [ 'error', diff --git a/.github/workflows/run-build-check.yml b/.github/workflows/run-build-check.yml index 9e61cf5e..13f89570 100644 --- a/.github/workflows/run-build-check.yml +++ b/.github/workflows/run-build-check.yml @@ -29,5 +29,3 @@ jobs: - name: Build run: yarn build - - \ No newline at end of file diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 69e64e38..147e03a0 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -1,95 +1,64 @@ -import { formattedDate } from '@tests/utils/insert-tomorrow-expiration-day'; +import { getTomorrowDateFormatted } from '@tests/utils/get-tomorrow-date-formatted'; import { describe, test, expect } from 'vitest'; -import type SequelizeOrm from '@repository/storage/postgres/orm/index.js'; - - -/** - * Fills in the database with user sessions - * - * @param db - SequelizeOrm instance - */ -async function insertUserSessions(db: SequelizeOrm): Promise { - const date = formattedDate(); - - await db.connection.query(`UPDATE public.user_sessions SET "refresh_token_expires_at" = '${date}' WHERE id = 5; - `); -} -/** - * Fills in the database with test data - * - * @param db - SequelizeOrm instance - */ -export async function insertDataForAuthTest(db: SequelizeOrm): Promise { - await insertUserSessions(db); -} - describe('Auth API', () => { describe('POST /auth', () => { - test('Returns 401 when session is not valid', async () => { - const expectedStatus = 401; + test('Returns 401 when refresh token in not valid', async () => { const refreshToken = 'EF1JX65xSZ'; + const response = await global.api?.fakeRequest({ method: 'POST', url: '/auth', body: { token: refreshToken }, }); - expect(response?.statusCode).toBe(expectedStatus); + expect(response?.statusCode).toBe(401); const body = await response?.json(); expect(body).toStrictEqual({ message: 'Session is not valid' }); }); + test('Returns 200 when refresh token is valid and expiration date has not passed', async () => { + const refreshToken = 'pv-jIqfPj2'; - test('Returns 200 when refreshToken is in the database', async () => { - const expectedStatus = 200; - - /** Define the token to include in the request body */ - const missingToken = 'pv-jIqfPj1'; + /** + * Insert session data to the DB with tomorrow expiration date + */ + await global.db.query(`INSERT INTO public.user_sessions (id, "user_id", "refresh_token", "refresh_token_expires_at") VALUES (9999, 1, '${refreshToken}', '${getTomorrowDateFormatted()}')`); const response = await global.api?.fakeRequest({ method: 'POST', url: '/auth', - /** Include the token in the request body*/ - body: { token: missingToken }, + body: { token: refreshToken }, }); - expect(response?.statusCode).toBe(expectedStatus); + expect(response?.statusCode).toBe(200); const body = await response?.json(); expect(typeof body.refreshToken).toBe('string'); - expect(typeof body.accessToken).toBe('string'); - - // Optionally, you can also check if the strings are not empty or null expect(body.refreshToken).toBeDefined(); - expect(body.accessToken).toBeDefined(); expect(body.refreshToken).not.toBeNull(); - expect(body.accessToken).not.toBeNull(); expect(body.refreshToken).not.toBe(''); - expect(body.accessToken).not.toBe(''); - // Check if the response object matches the expected structure - expect(body).toHaveProperty('refreshToken'); - expect(body).toHaveProperty('accessToken'); + expect(typeof body.accessToken).toBe('string'); + expect(body.accessToken).toBeDefined(); + expect(body.accessToken).not.toBeNull(); + expect(body.accessToken).not.toBe(''); }); - test('Returns 401 when expiration day has passed', async () => { - const expectedStatus = 401; const outdatedToken = 'F5tTF24K9Q'; - - const response=await global.api?.fakeRequest({ + const response = await global.api?.fakeRequest({ method: 'POST', url: '/auth', - body:{ token: outdatedToken }, }); - expect (response?.statusCode).toBe(expectedStatus); + expect (response?.statusCode).toBe(401); + const body = await response?.json(); expect(body).toStrictEqual({ message:'Session is not valid' }); diff --git a/src/tests/test-data/user-sessions.json b/src/tests/test-data/user-sessions.json index 463c4b2b..6eac4761 100644 --- a/src/tests/test-data/user-sessions.json +++ b/src/tests/test-data/user-sessions.json @@ -1,20 +1,14 @@ [ { - "id": 7, + "id": 2, "user_id": 4, - "refresh_token": "IqrTkSKmel", - "refresh_token_expires_at": "2025-11-21 19:19:40.911+03" - }, - { - "refresh_token": "pv-jIqfPj1", - "refresh_token_expires_at": "2023-11-15 20:47:30+02", - "user_id": 1, - "id": 5 + "refresh_token": "F5tTF24K9Q", + "refresh_token_expires_at": "2023-11-09 11:23:54+02" }, { - "refresh_token": "F5tTF24K9Q", - "refresh_token_expires_at": "2023-11-09 11:23:54+02", + "id": 3, "user_id": 1, - "id": 6 + "refresh_token": "IqrTkSKmel", + "refresh_token_expires_at": "2025-11-21 19:19:40.911+03" } -] \ No newline at end of file +] diff --git a/src/tests/utils/insert-tomorrow-expiration-day.ts b/src/tests/utils/get-tomorrow-date-formatted.ts similarity index 54% rename from src/tests/utils/insert-tomorrow-expiration-day.ts rename to src/tests/utils/get-tomorrow-date-formatted.ts index 85716a84..b112cb05 100644 --- a/src/tests/utils/insert-tomorrow-expiration-day.ts +++ b/src/tests/utils/get-tomorrow-date-formatted.ts @@ -1,9 +1,10 @@ -/** create string of tomorrow expiration day */ -export const formattedDate = (): string => { +/** + * Returns tomorrow date in DB compatible format + */ +export const getTomorrowDateFormatted = (): string => { const tomorrow = new Date(); const border = 19; - tomorrow.setDate(tomorrow.getDate() + 1); const newExpirationDay: string = tomorrow.toISOString().slice(0, border) @@ -11,6 +12,4 @@ export const formattedDate = (): string => { return newExpirationDay; }; -// Export the newExpirationDay variable directly -export const newExpirationDay: string = formattedDate(); diff --git a/src/tests/utils/setup.ts b/src/tests/utils/setup.ts index 52d2605e..66226af3 100644 --- a/src/tests/utils/setup.ts +++ b/src/tests/utils/setup.ts @@ -2,7 +2,6 @@ import path from 'path'; import type { StartedPostgreSqlContainer } from '@testcontainers/postgresql'; import { PostgreSqlContainer } from '@testcontainers/postgresql'; -import { insertDataForAuthTest } from '@presentation/http/router/auth.test'; import { insertData } from './insert-data'; import { initORM, init as initRepositories } from '@repository/index.js'; import { init as initDomainServices } from '@domain/index.js'; @@ -34,7 +33,7 @@ declare global { * @param userId - id of the user that will be considered the author of the request * @returns accessToken for authorization */ - function auth(userId: number) : string; + function auth(userId: number): string; /* eslint-disable-next-line no-var */ var db: { @@ -43,7 +42,6 @@ declare global { * Might be used in tests to perform some specific database operations * * @param sql - string containing sql to executein test DB - * @returns */ query: (sql: string) => Promise; }; @@ -70,7 +68,7 @@ beforeAll(async () => { await runTenantMigrations(migrationsPath, postgresContainer.getConnectionUri()); await insertData(orm); - await insertDataForAuthTest(orm); + global.api = api; global.auth = (userId: number) => { From 178178470a05b52326eedc80a3f9365fb508edcf Mon Sep 17 00:00:00 2001 From: Tanya Fomina Date: Sat, 25 Nov 2023 17:41:45 +0300 Subject: [PATCH 33/34] Remove changes --- .github/workflows/run-build-check.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/run-build-check.yml b/.github/workflows/run-build-check.yml index 13f89570..09cb8332 100644 --- a/.github/workflows/run-build-check.yml +++ b/.github/workflows/run-build-check.yml @@ -29,3 +29,4 @@ jobs: - name: Build run: yarn build + From f87287c215f13592eee370dac66fac31a1a31b9d Mon Sep 17 00:00:00 2001 From: Tanya Fomina Date: Sat, 25 Nov 2023 18:04:15 +0300 Subject: [PATCH 34/34] Remove get-tommorrow-date-formatted --- src/presentation/http/router/auth.test.ts | 3 +-- src/tests/utils/get-tomorrow-date-formatted.ts | 15 --------------- 2 files changed, 1 insertion(+), 17 deletions(-) delete mode 100644 src/tests/utils/get-tomorrow-date-formatted.ts diff --git a/src/presentation/http/router/auth.test.ts b/src/presentation/http/router/auth.test.ts index 147e03a0..cb362465 100644 --- a/src/presentation/http/router/auth.test.ts +++ b/src/presentation/http/router/auth.test.ts @@ -1,4 +1,3 @@ -import { getTomorrowDateFormatted } from '@tests/utils/get-tomorrow-date-formatted'; import { describe, test, expect } from 'vitest'; describe('Auth API', () => { @@ -25,7 +24,7 @@ describe('Auth API', () => { /** * Insert session data to the DB with tomorrow expiration date */ - await global.db.query(`INSERT INTO public.user_sessions (id, "user_id", "refresh_token", "refresh_token_expires_at") VALUES (9999, 1, '${refreshToken}', '${getTomorrowDateFormatted()}')`); + await global.db.query(`INSERT INTO public.user_sessions (id, "user_id", "refresh_token", "refresh_token_expires_at") VALUES (9999, 1, '${refreshToken}', CURRENT_DATE + INTERVAL '1 day')`); const response = await global.api?.fakeRequest({ method: 'POST', diff --git a/src/tests/utils/get-tomorrow-date-formatted.ts b/src/tests/utils/get-tomorrow-date-formatted.ts deleted file mode 100644 index b112cb05..00000000 --- a/src/tests/utils/get-tomorrow-date-formatted.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Returns tomorrow date in DB compatible format - */ -export const getTomorrowDateFormatted = (): string => { - const tomorrow = new Date(); - const border = 19; - - tomorrow.setDate(tomorrow.getDate() + 1); - - const newExpirationDay: string = tomorrow.toISOString().slice(0, border) - .replace('T', ' ') + '+02'; - - return newExpirationDay; -}; -