From 5f149545be935fc02568b16c325ae44309ab7559 Mon Sep 17 00:00:00 2001 From: Sarakhman Anatoliy <63456632+Tolik170@users.noreply.github.com> Date: Fri, 17 Nov 2023 14:52:33 +0200 Subject: [PATCH] Added accessToken to httpOnly cookies and changed tests with swagger settings (#631) * added accessToken to httponly cookies * removed console.log --- consts/auth.js | 1 + controllers/auth.js | 14 +++- docs/adminInvitation/admin-invitation.yaml | 4 +- docs/attachments/attachment.yaml | 8 +- docs/auth/auth.yaml | 6 +- docs/category/category.yaml | 12 +-- docs/chat/chat.yaml | 12 +-- docs/comment/comment.yaml | 4 +- docs/cooperation/cooperation.yaml | 8 +- docs/course/course.yaml | 10 +-- docs/finishedQuiz/finishedQuiz.yaml | 4 +- docs/lesson/lesson.yaml | 10 +-- docs/message/message.yaml | 4 +- docs/notications/notification.yaml | 6 +- docs/offer/offer.yaml | 10 +-- docs/questions/question.yaml | 8 +- docs/quiz/quiz.yaml | 10 +-- docs/resourcesCategory/resourcesCategory.yaml | 10 +-- docs/review/review.yaml | 10 +-- docs/subject/subject.yaml | 10 +-- docs/user/user.yaml | 28 +++---- middlewares/auth.js | 6 +- swagger-settings.js | 10 +-- .../controllers/attachments.spec.js | 7 +- test/integration/controllers/auth.spec.js | 9 ++- test/integration/controllers/category.spec.js | 79 +++++++------------ test/integration/controllers/chat.spec.js | 27 ++++--- test/integration/controllers/comment.spec.js | 14 ++-- .../controllers/cooperation.spec.js | 21 ++--- test/integration/controllers/course.spec.js | 27 ++++--- .../controllers/finishedQuiz.spec.js | 38 ++++----- test/integration/controllers/lesson.spec.js | 35 +++++--- test/integration/controllers/message.spec.js | 26 +++--- .../controllers/notification.spec.js | 14 ++-- test/integration/controllers/offer.spec.js | 30 ++++--- test/integration/controllers/question.spec.js | 13 +-- test/integration/controllers/quiz.spec.js | 28 +++---- .../controllers/resourcesCategory.spec.js | 12 +-- test/integration/controllers/review.spec.js | 23 +++--- test/integration/controllers/subject.spec.js | 26 +++--- test/integration/controllers/user.spec.js | 27 ++++--- test/unit/middlewares/auth.spec.js | 30 ++----- 42 files changed, 351 insertions(+), 340 deletions(-) diff --git a/consts/auth.js b/consts/auth.js index 0a0ce09f..758b0278 100644 --- a/consts/auth.js +++ b/consts/auth.js @@ -6,6 +6,7 @@ const roles = { } const tokenNames = { + ACCESS_TOKEN: 'accessToken', REFRESH_TOKEN: 'refreshToken', RESET_TOKEN: 'resetToken', CONFIRM_TOKEN: 'confirmToken' diff --git a/controllers/auth.js b/controllers/auth.js index c00c19cc..0da142e9 100644 --- a/controllers/auth.js +++ b/controllers/auth.js @@ -4,7 +4,7 @@ const { config: { COOKIE_DOMAIN } } = require('~/configs/config') const { - tokenNames: { REFRESH_TOKEN } + tokenNames: { REFRESH_TOKEN, ACCESS_TOKEN } } = require('~/consts/auth') const COOKIE_OPTIONS = { @@ -29,6 +29,7 @@ const login = async (req, res) => { const tokens = await authService.login(email, password) + res.cookie(ACCESS_TOKEN, tokens.accessToken, COOKIE_OPTIONS) res.cookie(REFRESH_TOKEN, tokens.refreshToken, COOKIE_OPTIONS) delete tokens.refreshToken @@ -42,6 +43,7 @@ const googleAuth = async (req, res) => { const tokens = await authService.googleAuth(token.credential, role, lang) + res.cookie(ACCESS_TOKEN, tokens.accessToken, COOKIE_OPTIONS) res.cookie(REFRESH_TOKEN, tokens.refreshToken, COOKIE_OPTIONS) delete tokens.refreshToken @@ -53,7 +55,9 @@ const logout = async (req, res) => { const { refreshToken } = req.cookies await authService.logout(refreshToken) + res.clearCookie(REFRESH_TOKEN) + res.clearCookie(ACCESS_TOKEN) res.status(204).end() } @@ -69,7 +73,15 @@ const confirmEmail = async (req, res) => { const refreshAccessToken = async (req, res) => { const { refreshToken } = req.cookies + if (!refreshToken) { + res.clearCookie(ACCESS_TOKEN) + + return res.status(401).end() + } + const tokens = await authService.refreshAccessToken(refreshToken) + + res.cookie(ACCESS_TOKEN, tokens.accessToken, COOKIE_OPTIONS) res.cookie(REFRESH_TOKEN, tokens.refreshToken, COOKIE_OPTIONS) delete tokens.refreshToken diff --git a/docs/adminInvitation/admin-invitation.yaml b/docs/adminInvitation/admin-invitation.yaml index 82287707..83efa0c6 100644 --- a/docs/adminInvitation/admin-invitation.yaml +++ b/docs/adminInvitation/admin-invitation.yaml @@ -2,7 +2,7 @@ paths: /admin-invitations: post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Admin invitations summary: Invite admins @@ -62,7 +62,7 @@ paths: message: You do not have permission to perform this action. get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Admin invitations summary: Find all admin invitations diff --git a/docs/attachments/attachment.yaml b/docs/attachments/attachment.yaml index 971d799c..a508662d 100644 --- a/docs/attachments/attachment.yaml +++ b/docs/attachments/attachment.yaml @@ -2,7 +2,7 @@ paths: /attachments: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Attachments summary: Find all attachments. @@ -70,7 +70,7 @@ paths: message: You do not have permission to perform this action. post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Attachments summary: Create new attachments. @@ -130,7 +130,7 @@ paths: /attachments/{id}: patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Attachments summary: Finds and updates an attachment. @@ -214,7 +214,7 @@ paths: message: Attachment with the specified id was not found. delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Attachments summary: Delete attachment by ID diff --git a/docs/auth/auth.yaml b/docs/auth/auth.yaml index 09842a60..ad053bb7 100644 --- a/docs/auth/auth.yaml +++ b/docs/auth/auth.yaml @@ -55,7 +55,7 @@ paths: tags: - Auth summary: User authentication - description: Authenticates a user, returns an access token and sets cookie with a refresh token. + description: Authenticates a user, returns an access token and sets cookie with a refresh and access tokens. produces: - application/json requestBody: @@ -75,7 +75,7 @@ paths: Set-Cookie: schema: type: string - example: refreshToken=eyJhbGciOiJIUzI1NiIsInRI.0IiwiaXNatalXJzdExvZ2A5Mjg4ODMsImV4cCI6MWomanzMjQ4M30.gn_hJqB9zVi5Ux5oRu22hGQ9W4z2njkdnx4O; Max-Age=86400; Domain=s2s-back-stage.azurewebsites.net; Path=/; Expires=Sat, 20 Aug 2022 17:32:57 GMT; HttpOnly; Secure; SameSite=None + example: refreshToken=eyJhbGciOiJIUzI1NiIsInRI.0IiwiaXNatalXJzdExvZ2A5Mjg4ODMsImV4cCI6MWomanzMjQ4M30.gn_hJqB9zVi5Ux5oRu22hGQ9W4z2njkdnx5O; refreshToken=eyJhbGciOiJIUzI1NiIsInRI.0IiwiaXNatalXJzdExvZ2A5Mjg4ODMsImV4cCI6MWomanzMjQ4M30.gn_hJqB9zVi5Ux5oRu22hGQ9W4z2njkdnx4O; Max-Age=86400; Domain=s2s-back-stage.azurewebsites.net; Path=/; Expires=Sat, 20 Aug 2022 17:32:57 GMT; HttpOnly; Secure; SameSite=None content: application/json: schema: @@ -104,7 +104,7 @@ paths: tags: - Auth summary: Logs the current user out - description: Logs the current user out, deletes a refresh token from the DB and clears cookie. + description: Logs the current user out, deletes a refresh and access tokens from the DB and clears cookie. produces: - application/json parameters: diff --git a/docs/category/category.yaml b/docs/category/category.yaml index d13a10e8..25dda967 100644 --- a/docs/category/category.yaml +++ b/docs/category/category.yaml @@ -2,7 +2,7 @@ paths: /categories: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Categories summary: Find all categories @@ -61,7 +61,7 @@ paths: message: The requested URL requires user authorization. post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Category summary: Create new category. @@ -129,7 +129,7 @@ paths: /categories/{id}/subjects/names: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Categories summary: Find subjects' names for category @@ -177,7 +177,7 @@ paths: /categories/{id}: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Categories summary: Find category by ID @@ -239,7 +239,7 @@ paths: /categories/{categoryId}/subject/{subjectId}/price-range: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Offers summary: Find and return min and max price. @@ -288,7 +288,7 @@ paths: /categories/{id}/subjects: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Categories summary: Find subjects by category diff --git a/docs/chat/chat.yaml b/docs/chat/chat.yaml index 317749c4..e804a791 100644 --- a/docs/chat/chat.yaml +++ b/docs/chat/chat.yaml @@ -2,7 +2,7 @@ paths: /chats: post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Chats summary: Create a new chat. @@ -46,7 +46,7 @@ paths: message: The requested URL requires user authorization. get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Chats summary: Find all chats for current user. @@ -80,7 +80,7 @@ paths: /chats/{id}/messages: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Chats summary: Find your messages in chat @@ -144,7 +144,7 @@ paths: message: Chat with the specified id was not found. delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Chats summary: Delete all messages from the specified chat @@ -248,7 +248,7 @@ paths: /chats/{id}: delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Chats summary: Deletes Chat by ID @@ -306,7 +306,7 @@ paths: message: Chat with the specified id was not found. patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Chats summary: Marks chat as deleted by ID for current user diff --git a/docs/comment/comment.yaml b/docs/comment/comment.yaml index c2eef62d..18a778e8 100644 --- a/docs/comment/comment.yaml +++ b/docs/comment/comment.yaml @@ -2,7 +2,7 @@ paths: /cooperations/{id}/comments: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Comments summary: Find your comments of cooperation @@ -64,7 +64,7 @@ paths: message: Cooperation with the specified id was not found. post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Comments summary: Create new comment. diff --git a/docs/cooperation/cooperation.yaml b/docs/cooperation/cooperation.yaml index 46eb2e4c..4be56a27 100644 --- a/docs/cooperation/cooperation.yaml +++ b/docs/cooperation/cooperation.yaml @@ -2,7 +2,7 @@ paths: /cooperations: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Cooperations summary: Find all cooperations @@ -51,7 +51,7 @@ paths: message: 'The requested URL requires user authorization.' post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Cooperations summary: Create new cooperation. @@ -112,7 +112,7 @@ paths: /cooperations/{id}: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Cooperations summary: Find cooperation by ID @@ -176,7 +176,7 @@ paths: message: Cooperation with the specified id was not found. patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Cooperations summary: Update cooperation by ID diff --git a/docs/course/course.yaml b/docs/course/course.yaml index 5a430549..1e410a62 100644 --- a/docs/course/course.yaml +++ b/docs/course/course.yaml @@ -2,7 +2,7 @@ paths: /courses: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Courses summary: Find all courses. @@ -66,7 +66,7 @@ paths: message: You do not have permission to perform this action. post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Courses summary: Creates a new course. @@ -124,7 +124,7 @@ paths: /courses/{id}: patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Courses summary: Update a course. @@ -185,7 +185,7 @@ paths: message: Course with the specified id was not found. get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Courses summary: Find course by id. @@ -236,7 +236,7 @@ paths: message: Course with the specified id was not found. delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Courses summary: Delete a course. diff --git a/docs/finishedQuiz/finishedQuiz.yaml b/docs/finishedQuiz/finishedQuiz.yaml index d5f80b3d..360e341b 100644 --- a/docs/finishedQuiz/finishedQuiz.yaml +++ b/docs/finishedQuiz/finishedQuiz.yaml @@ -2,7 +2,7 @@ paths: /finished-quizzes: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Finished quizzes summary: Find all finished quizzes. @@ -80,7 +80,7 @@ paths: message: You do not have permission to perform this action. post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Finished quizzes summary: Creates a new finished quiz. diff --git a/docs/lesson/lesson.yaml b/docs/lesson/lesson.yaml index f6da2224..cc0c2e9f 100644 --- a/docs/lesson/lesson.yaml +++ b/docs/lesson/lesson.yaml @@ -2,7 +2,7 @@ paths: /lessons: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Lessons summary: Find all lessons. @@ -69,7 +69,7 @@ paths: message: You do not have permission to perform this action. post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Lessons summary: Creates a new lesson. @@ -129,7 +129,7 @@ paths: /lessons/{id}: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Lessons summary: Find and return lesson by ID @@ -208,7 +208,7 @@ paths: message: You do not have permission to perform this action. patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Lessons summary: Update a lesson. @@ -267,7 +267,7 @@ paths: message: Lesson with the specified id was not found. delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Lessons summary: Delete lesson by ID diff --git a/docs/message/message.yaml b/docs/message/message.yaml index 84909343..13274cfc 100644 --- a/docs/message/message.yaml +++ b/docs/message/message.yaml @@ -2,7 +2,7 @@ paths: /messages: post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Messages summary: Create a new message. @@ -49,7 +49,7 @@ paths: message: 'The requested URL requires user authorization.' get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Messages summary: Find your messages in chat diff --git a/docs/notications/notification.yaml b/docs/notications/notification.yaml index 042d4de1..24a048b6 100644 --- a/docs/notications/notification.yaml +++ b/docs/notications/notification.yaml @@ -2,7 +2,7 @@ paths: /notifications: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Notifications summary: Find and count user's notifications @@ -38,7 +38,7 @@ paths: message: The requested URL requires user authorization. delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Notifications summary: Remove all user's notifications @@ -61,7 +61,7 @@ paths: /notifications/{id}: delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Notifications summary: Remove certain notification diff --git a/docs/offer/offer.yaml b/docs/offer/offer.yaml index 76eaea0a..c5f60ea3 100644 --- a/docs/offer/offer.yaml +++ b/docs/offer/offer.yaml @@ -2,7 +2,7 @@ paths: /offers: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Offers summary: Find all offers @@ -148,7 +148,7 @@ paths: message: The requested URL requires user authorization. post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Offers summary: Create new offer. @@ -221,7 +221,7 @@ paths: /offers/{id}: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Offers summary: Find and return offer by ID @@ -321,7 +321,7 @@ paths: message: Subject with the specified id was not found. patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Offers summary: Find and update offer by ID @@ -395,7 +395,7 @@ paths: message: Offer with the specified id was not found. delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Offers summary: Find and delete offer by ID diff --git a/docs/questions/question.yaml b/docs/questions/question.yaml index 18684916..308253da 100644 --- a/docs/questions/question.yaml +++ b/docs/questions/question.yaml @@ -2,7 +2,7 @@ paths: /questions: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Questions summary: Find all questions. @@ -77,7 +77,7 @@ paths: message: The requested URL requires user authorization. post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Questions summary: Creates a new question. @@ -144,7 +144,7 @@ paths: /questions/{id}: patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Questions summary: Updates question by id and return it. @@ -218,7 +218,7 @@ paths: message: Question with the specified id was not found. delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Questions summary: Find and delete question by ID diff --git a/docs/quiz/quiz.yaml b/docs/quiz/quiz.yaml index ca1bc32b..9fb2cb79 100644 --- a/docs/quiz/quiz.yaml +++ b/docs/quiz/quiz.yaml @@ -2,7 +2,7 @@ paths: /quizzes: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Quizzes summary: Find all quizzes. @@ -73,7 +73,7 @@ paths: message: You do not have permission to perform this action. post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Quizzes summary: Creates a new quiz. @@ -129,7 +129,7 @@ paths: /quizzes/{id}: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Quizzes summary: Find quiz by id. @@ -179,7 +179,7 @@ paths: message: You do not have permission to perform this action. patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Quizzes summary: Update quiz by id. @@ -235,7 +235,7 @@ paths: message: Quiz with the specified id was not found. delete: security: - - bearerAuth: [ ] + - cookieAuth: [ ] tags: - Quizzes summary: Delete quiz by ID diff --git a/docs/resourcesCategory/resourcesCategory.yaml b/docs/resourcesCategory/resourcesCategory.yaml index 8fe350f6..622aa650 100644 --- a/docs/resourcesCategory/resourcesCategory.yaml +++ b/docs/resourcesCategory/resourcesCategory.yaml @@ -2,7 +2,7 @@ paths: /resources-categories: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Resources Categories summary: Find all resources categories. @@ -67,7 +67,7 @@ paths: message: You do not have permission to perform this action. post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Resources Categories summary: Creates a new resource category. @@ -119,7 +119,7 @@ paths: /resources-categories/names: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Resources Categories summary: Find all resources categories names. @@ -158,7 +158,7 @@ paths: /resources-categories/{id}: patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Resources Categories summary: Update resource category by id. @@ -214,7 +214,7 @@ paths: message: Resource Category with the specified id was not found. delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - ResourcesCategories summary: Delete ResourcesCategory by ID diff --git a/docs/review/review.yaml b/docs/review/review.yaml index ea400c0a..2c278ccc 100644 --- a/docs/review/review.yaml +++ b/docs/review/review.yaml @@ -2,7 +2,7 @@ paths: /reviews: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Reviews summary: Find all reviews @@ -100,7 +100,7 @@ paths: message: 'The requested URL requires user authorization.' post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Reviews summary: Create new review. @@ -207,7 +207,7 @@ paths: /reviews/{id}: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Reviews summary: Find review by ID @@ -319,7 +319,7 @@ paths: message: Review with the specified id was not found. patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Reviews summary: Update review by ID @@ -387,7 +387,7 @@ paths: message: Review with the specified id was not found. delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Reviews summary: Find and delete review by ID diff --git a/docs/subject/subject.yaml b/docs/subject/subject.yaml index 08c626be..05e93885 100644 --- a/docs/subject/subject.yaml +++ b/docs/subject/subject.yaml @@ -2,7 +2,7 @@ paths: /subjects: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Subjects summary: Find all subjects @@ -41,7 +41,7 @@ paths: message: 'The requested URL requires user authorization.' post: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Subjects summary: Create new subject. @@ -105,7 +105,7 @@ paths: /subjects/{id}: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Subjects summary: Find subject by ID @@ -164,7 +164,7 @@ paths: message: Subject with the specified id was not found. patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Subjects summary: Update subject by ID @@ -233,7 +233,7 @@ paths: message: Subject with the specified id was not found. delete: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Subjects summary: Delete subject by ID diff --git a/docs/user/user.yaml b/docs/user/user.yaml index 24d01a8b..5a5d8012 100644 --- a/docs/user/user.yaml +++ b/docs/user/user.yaml @@ -1,18 +1,8 @@ -components: - securitySchemes: - bearerAuth: - type: http - scheme: bearer - bearerFormat: JWT - role: - type: apiKey - name: Authorization - in: header paths: /users: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Users summary: Find all users @@ -119,7 +109,7 @@ paths: /users/{id}/change-status: patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Users summary: Find and update user status by ID @@ -187,7 +177,7 @@ paths: /users/{id}: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Users summary: Find user by ID @@ -329,7 +319,7 @@ paths: message: 'User with the specified id was not found.' patch: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Users summary: Find and update current user info @@ -377,7 +367,7 @@ paths: message: 'User with the specified id was not found.' delete: security: - - bearerAuth: [] + - cookieAuth: [] - role: - admin tags: @@ -438,7 +428,7 @@ paths: /users/{id}/reviews: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Users summary: Find all reviews for a user with the specified ID and role @@ -558,7 +548,7 @@ paths: /users/{id}/reviews/stats: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Users summary: Find review statistics for a user with the specified ID and role @@ -607,7 +597,7 @@ paths: /users/{id}/cooperations: get: security: - - bearerAuth: [ ] + - cookieAuth: [ ] tags: - Users summary: Find cooperations for a user with the specified ID @@ -671,7 +661,7 @@ paths: /users/{id}/offers: get: security: - - bearerAuth: [] + - cookieAuth: [] tags: - Users summary: Find offers for a user with the specified ID diff --git a/middlewares/auth.js b/middlewares/auth.js index 323d89c5..71cf2fbe 100644 --- a/middlewares/auth.js +++ b/middlewares/auth.js @@ -2,12 +2,8 @@ const { createUnauthorizedError, createForbiddenError } = require('~/utils/error const tokenService = require('~/services/token') const authMiddleware = (req, _res, next) => { - const authorizationHeader = req.headers.authorization - if (!authorizationHeader) { - throw createUnauthorizedError() - } + const { accessToken } = req.cookies - const accessToken = authorizationHeader.split(' ')[1] if (!accessToken) { throw createUnauthorizedError() } diff --git a/swagger-settings.js b/swagger-settings.js index 7b4ee676..11217b4f 100644 --- a/swagger-settings.js +++ b/swagger-settings.js @@ -17,11 +17,11 @@ const swagger = { ], components: { securitySchemes: { - bearerAuth: { - type: 'http', - scheme: 'bearer', - description: 'Enter JWT Bearer Token', - bearerFormat: 'JWT' + cookieAuth: { + type: 'apiKey', + in: 'cookie', + name: 'accessToken', + description: 'Enter your cookie for authentication' } } } diff --git a/test/integration/controllers/attachments.spec.js b/test/integration/controllers/attachments.spec.js index 01c1e7f6..284c03dc 100644 --- a/test/integration/controllers/attachments.spec.js +++ b/test/integration/controllers/attachments.spec.js @@ -66,7 +66,7 @@ describe('Attachments controller', () => { testAttachmentsResponse = await app .post(endpointUrl) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send({ testFile }) }) @@ -102,7 +102,10 @@ describe('Attachments controller', () => { it('should throw FORBIDDEN', async () => { accessToken = await testUserAuthentication(app) - const response = await app.post(endpointUrl).set('Authorization', `Bearer ${tutorAccessToken}`).send(testFile) + const response = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${tutorAccessToken}`]) + .send(testFile) expectError(403, FORBIDDEN, response) }) diff --git a/test/integration/controllers/auth.spec.js b/test/integration/controllers/auth.spec.js index 6063d1d7..9bd606f5 100644 --- a/test/integration/controllers/auth.spec.js +++ b/test/integration/controllers/auth.spec.js @@ -73,7 +73,7 @@ describe('Auth controller', () => { expectError(422, error, signupResponse) }) - it("should throw validation errors for the password's length", async () => { + it('should throw validation errors for the password`s length', async () => { const responseForMax = await app .post('/auth/signup') .send({ ...user, password: '1'.repeat(MAX_PASSWORD_LENGTH + 1) }) @@ -218,9 +218,12 @@ describe('Auth controller', () => { const loginUserResponse = await app.post('/auth/login').send({ email: user.email, password: user.password }) - const refreshToken = loginUserResponse.header['set-cookie'][0].split(';')[0].split('=')[1] + const refreshToken = loginUserResponse.header['set-cookie'][1].split(';')[0].split('=')[1] + const accessToken = loginUserResponse.header['set-cookie'][0].split(';')[0].split('=')[1] - const refreshResponse = await app.get('/auth/refresh').set('Cookie', `refreshToken=${refreshToken}`) + const refreshResponse = await app + .get('/auth/refresh') + .set('Cookie', [`refreshToken=${refreshToken}`, `accessToken=${accessToken}`]) expect(refreshResponse.statusCode).toBe(200) expect(refreshResponse.body).toEqual( diff --git a/test/integration/controllers/category.spec.js b/test/integration/controllers/category.spec.js index e014e073..ce3d840b 100644 --- a/test/integration/controllers/category.spec.js +++ b/test/integration/controllers/category.spec.js @@ -18,42 +18,18 @@ let categoryBody = { } const subjectBody = [ - { - name: 'Web design' - }, - { - name: 'Guitar' - }, - { - name: 'Bass' - }, - { - name: 'Piano' - }, - { - name: 'Spanish' - }, - { - name: 'Cybersecurity' - }, - { - name: 'Violins' - }, - { - name: 'pian' - }, - { - name: 'Sound design' - }, - { - name: 'Drums' - }, - { - name: 'English' - }, - { - name: 'Danish' - } + { name: 'Web design' }, + { name: 'Guitar' }, + { name: 'Bass' }, + { name: 'Piano' }, + { name: 'Spanish' }, + { name: 'Cybersecurity' }, + { name: 'Violins' }, + { name: 'pian' }, + { name: 'Sound design' }, + { name: 'Drums' }, + { name: 'English' }, + { name: 'Danish' } ] describe('Category controller', () => { @@ -76,7 +52,10 @@ describe('Category controller', () => { subject.category = category._id - testSubject = await app.post('/subjects/').set('Authorization', `Bearer ${accessToken}`).send(subject) + testSubject = await app + .post('/subjects/') + .set('Cookie', [`accessToken=${accessToken}`]) + .send(subject) subject._id = testSubject.body._id } @@ -98,7 +77,10 @@ describe('Category controller', () => { }) it('should create a new category', async () => { - testCategory = await app.post(endpointUrl).set('Authorization', `Bearer ${accessToken}`).send(categoryBody) + testCategory = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(categoryBody) subjectBody.category = testCategory.body._id categoryBody._id = testCategory.body._id @@ -127,7 +109,7 @@ describe('Category controller', () => { }) it('should get all categories', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toEqual(expect.objectContaining({ items: expect.any(Array), count: 7 })) @@ -139,7 +121,7 @@ describe('Category controller', () => { const response = await app .get(endpointUrl + '?' + params.toString()) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toEqual(expect.objectContaining({ items: expect.any(Array), count: 1 })) @@ -151,8 +133,7 @@ describe('Category controller', () => { const response = await app .get(endpointUrl + '?' + params.toString()) - .set('Authorization', `Bearer ${accessToken}`) - + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toEqual(expect.objectContaining({ items: expect.any(Array), count: 5 })) expect(response.body.items.length).toBe(5) @@ -165,7 +146,7 @@ describe('Category controller', () => { const response = await app .get(endpointUrl + '?' + params.toString()) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toEqual(expect.objectContaining({ items: expect.any(Array), count: 2 })) @@ -180,7 +161,7 @@ describe('Category controller', () => { }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.get(endpointUrl + nonExistingCategoryId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + nonExistingCategoryId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Category.modelName]), response) }) @@ -188,7 +169,7 @@ describe('Category controller', () => { it('should get a category by id', async () => { const response = await app .get(endpointUrl + categoryResponse[0]._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toEqual(expect.objectContaining(categoryData)) @@ -197,7 +178,7 @@ describe('Category controller', () => { describe(`GET ${endpointUrl}names`, () => { it('should return categories names', async () => { - const response = await app.get(endpointUrl + 'names').set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + 'names').set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(Array.isArray(response.body)).toBeTruthy() @@ -209,7 +190,7 @@ describe('Category controller', () => { it('should throw NOT_FOUND', async () => { const response = await app .get(endpointUrl + `${categoryBody._id}/price-range?authorRole=student`) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expectError(404, NOT_FOUND, response) }) @@ -217,7 +198,7 @@ describe('Category controller', () => { it('should return min and max prices for student offers', async () => { const response = await app .get(endpointUrl + `${categoryResponse[0]._id}/subjects/${subjectBody[0]._id}/price-range?authorRole=student`) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(typeof response.body).toBe('object') @@ -230,7 +211,7 @@ describe('Category controller', () => { it('should return min and max prices for tutor offers', async () => { const response = await app .get(endpointUrl + `${categoryResponse[0]._id}/subjects/${subjectBody[0]._id}/price-range?authorRole=tutor`) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(typeof response.body).toBe('object') diff --git a/test/integration/controllers/chat.spec.js b/test/integration/controllers/chat.spec.js index 977667ce..0550aed3 100644 --- a/test/integration/controllers/chat.spec.js +++ b/test/integration/controllers/chat.spec.js @@ -92,7 +92,10 @@ describe('Chat controller', () => { }) it('should create a new chat', async () => { - const newChat = await app.post(endpointUrl).set('Authorization', `Bearer ${accessToken}`).send(chatBody) + const newChat = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(chatBody) expect(newChat.statusCode).toBe(201) @@ -102,19 +105,22 @@ describe('Chat controller', () => { describe(`DELETE ${endpointUrl}:id`, () => { beforeEach(async () => { - testChat = await app.post(endpointUrl).set('Authorization', `Bearer ${accessToken}`).send(chatBody) + testChat = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(chatBody) }) it('should throw FORBIDDEN', async () => { const response = await app .delete(endpointUrl + testChat._body._id) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) it('should delete chat by ID', async () => { - const response = await app.delete(endpointUrl + testChat._body._id).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl + testChat._body._id).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) @@ -126,7 +132,7 @@ describe('Chat controller', () => { }) it('should throw NOT_FOUND', async () => { - const response = await app.delete(endpointUrl + nonExistingChatId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl + nonExistingChatId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Chat.modelName]), response) }) @@ -134,19 +140,22 @@ describe('Chat controller', () => { describe(`PATCH ${endpointUrl}:id`, () => { beforeEach(async () => { - testChat = await app.post(endpointUrl).set('Authorization', `Bearer ${accessToken}`).send(chatBody) + testChat = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(chatBody) }) it('should throw FORBIDDEN', async () => { const response = await app .patch(endpointUrl + testChat._body._id) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) it('should mark chat by ID as deleted', async () => { - const response = await app.patch(endpointUrl + testChat._body._id).set('Authorization', `Bearer ${accessToken}`) + const response = await app.patch(endpointUrl + testChat._body._id).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response._body).toEqual(expect.objectContaining(markedChatData)) @@ -159,7 +168,7 @@ describe('Chat controller', () => { }) it('should throw NOT_FOUND', async () => { - const response = await app.patch(endpointUrl + nonExistingChatId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.patch(endpointUrl + nonExistingChatId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Chat.modelName]), response) }) diff --git a/test/integration/controllers/comment.spec.js b/test/integration/controllers/comment.spec.js index 2bf7ce62..73885ca4 100644 --- a/test/integration/controllers/comment.spec.js +++ b/test/integration/controllers/comment.spec.js @@ -17,7 +17,7 @@ const testCooperationData = { receiverRole: 'tutor', proficiencyLevel: 'Beginner', additionalInfo: - 'I don\'t like both Dark Arts and Voldemort that\'s why i want to learn your subject and became your student', + "I don't like both Dark Arts and Voldemort that's why i want to learn your subject and became your student", receiver: '649c147ac75d3e44440e3a12', offer: '649c148cc75d3e44440e3a13', initiatorRole: 'student', @@ -47,7 +47,7 @@ describe('Comment controller', () => { testComment = await app .post(endpointUrl(testCooperation._id)) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send(testCommentData) }) @@ -61,7 +61,7 @@ describe('Comment controller', () => { describe(`GET ${endpointUrl()}`, () => { it('get all comments', async () => { - const response = await app.get(endpointUrl(testCooperation._id)).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl(testCooperation._id)).set('Cookie', [`accessToken=${accessToken}`]) expect(response.status).toBe(200) expect(response.body.length).toBe(1) @@ -86,7 +86,7 @@ describe('Comment controller', () => { initiator: mockedInitiatorId }) - const response = await app.post(endpointUrl(cooperation._id)).set('Authorization', `Bearer ${accessToken}`) + const response = await app.post(endpointUrl(cooperation._id)).set('Cookie', [`accessToken=${accessToken}`]) expectError(403, FORBIDDEN, response) }) @@ -94,7 +94,7 @@ describe('Comment controller', () => { it('should throw DOCUMENT_NOT_FOUND for cooperation', async () => { const response = await app .post(endpointUrl(nonExistingCooperationId)) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Cooperation.modelName]), response) }) @@ -125,7 +125,7 @@ describe('Comment controller', () => { initiator: mockedInitiatorId }) - const response = await app.post(endpointUrl(cooperation._id)).set('Authorization', `Bearer ${accessToken}`) + const response = await app.post(endpointUrl(cooperation._id)).set('Cookie', [`accessToken=${accessToken}`]) expectError(403, FORBIDDEN, response) }) @@ -133,7 +133,7 @@ describe('Comment controller', () => { it('should throw DOCUMENT_NOT_FOUND for cooperation', async () => { const response = await app .post(endpointUrl(nonExistingCooperationId)) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Cooperation.modelName]), response) }) diff --git a/test/integration/controllers/cooperation.spec.js b/test/integration/controllers/cooperation.spec.js index bede90e6..f2162ec7 100644 --- a/test/integration/controllers/cooperation.spec.js +++ b/test/integration/controllers/cooperation.spec.js @@ -42,7 +42,7 @@ const testCooperationData = { receiverRole: 'tutor', proficiencyLevel: 'Beginner', additionalInfo: - "I don't like both Dark Arts and Voldemort that's why i want to learn your subject and became your student" + 'I don`t like both Dark Arts and Voldemort that`s why i want to learn your subject and became your student' } const testOfferData = { @@ -106,7 +106,7 @@ describe('Cooperation controller', () => { testCooperation = await app .post(endpointUrl) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send({ receiver: testTutorUser._id, receiverRole: tutorUserData.role[0], @@ -131,7 +131,10 @@ describe('Cooperation controller', () => { sort: JSON.stringify({ order: 'asc', orderBy: 'updatedAt' }) } - const response = await app.get(endpointUrl).query(query).set('Authorization', `Bearer ${accessToken}`) + const response = await app + .get(endpointUrl) + .query(query) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.status).toBe(200) expect(response.body.count).toBe(1) @@ -164,7 +167,7 @@ describe('Cooperation controller', () => { it('get cooperation by ID', async () => { const response = await app .get(endpointUrl + testCooperation.body._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.status).toBe(200) expect(response.body).toMatchObject({ @@ -190,7 +193,7 @@ describe('Cooperation controller', () => { it('should throw DOCUMENT_NOT_FOUND', async () => { const response = await app .get(endpointUrl + nonExistingCooperationId) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Cooperation.modelName]), response) }) @@ -224,7 +227,7 @@ describe('Cooperation controller', () => { it('should throw DOCUMENT_NOT_FOUND for offer entity', async () => { const response = await app .post(endpointUrl) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send({ initiator: testStudentUser.id, receiver: testTutorUser._id, @@ -246,12 +249,12 @@ describe('Cooperation controller', () => { it('should update a cooperation', async () => { const updateResponse = await app .patch(endpointUrl + testCooperation._body._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send({ ...updateData, availableQuizzes: [testActiveQuiz._id] }) const response = await app .get(endpointUrl + testCooperation._body._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(updateResponse.status).toBe(204) expect(response.body.status).toBe(updateData.status) @@ -261,7 +264,7 @@ describe('Cooperation controller', () => { it('should throw DOCUMENT_NOT_FOUND', async () => { const response = (testCooperation = await app .patch(endpointUrl + nonExistingCooperationId) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send(updateData)) expectError(404, DOCUMENT_NOT_FOUND([Cooperation.modelName]), response) diff --git a/test/integration/controllers/course.spec.js b/test/integration/controllers/course.spec.js index e0fd14ef..05a38998 100644 --- a/test/integration/controllers/course.spec.js +++ b/test/integration/controllers/course.spec.js @@ -57,7 +57,10 @@ describe('Course controller', () => { uploadService.uploadFile = mockUploadFile - testCourseResponse = await app.post(endpointUrl).set('Authorization', `Bearer ${accessToken}`).send(testCourseData) + testCourseResponse = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(testCourseData) testCourse = testCourseResponse.body }) @@ -71,7 +74,7 @@ describe('Course controller', () => { describe(`GET ${endpointUrl}`, () => { it('should get all courses', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toEqual({ count: 1, items: [expect.objectContaining(testCourseData)] }) @@ -84,7 +87,7 @@ describe('Course controller', () => { }) it('should throw FORBIDDEN', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${studentAccessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) @@ -110,7 +113,7 @@ describe('Course controller', () => { it('should throw FORBIDDEN', async () => { const response = await app .patch(endpointUrl) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) .send(testCourseData) expectError(403, FORBIDDEN, response) @@ -121,7 +124,7 @@ describe('Course controller', () => { it('should update a course', async () => { const response = await app .patch(endpointUrl + testCourse._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send(updateData) const { title, description } = await Course.findById(testCourse._id) @@ -137,7 +140,7 @@ describe('Course controller', () => { }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.patch(endpointUrl + nonExistingCourseId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.patch(endpointUrl + nonExistingCourseId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Course.modelName]), response) }) @@ -145,7 +148,7 @@ describe('Course controller', () => { it('should throw FORBIDDEN', async () => { const response = await app .patch(endpointUrl) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) .send(updateData) expectError(403, FORBIDDEN, response) @@ -156,7 +159,7 @@ describe('Course controller', () => { it('should get course by id', async () => { const response = await app .get(endpointUrl + testCourseResponse.body._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toMatchObject({ @@ -172,7 +175,7 @@ describe('Course controller', () => { }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.get(endpointUrl + nonExistingCourseId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + nonExistingCourseId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Course.modelName]), response) }) @@ -186,7 +189,7 @@ describe('Course controller', () => { describe(`DELETE ${endpointUrl}:id`, () => { it('should delete a course', async () => { - const response = await app.delete(endpointUrl + testCourse._id).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl + testCourse._id).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) @@ -198,13 +201,13 @@ describe('Course controller', () => { }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.delete(endpointUrl + nonExistingCourseId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl + nonExistingCourseId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Course.modelName]), response) }) it('should throw FORBIDDEN', async () => { - const response = await app.delete(endpointUrl).set('Authorization', `Bearer ${studentAccessToken}`) + const response = await app.delete(endpointUrl).set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) diff --git a/test/integration/controllers/finishedQuiz.spec.js b/test/integration/controllers/finishedQuiz.spec.js index f070b584..ba0c7141 100644 --- a/test/integration/controllers/finishedQuiz.spec.js +++ b/test/integration/controllers/finishedQuiz.spec.js @@ -10,7 +10,6 @@ const { } = require('~/consts/auth') const TokenService = require('~/services/token') - const endpointUrl = '/finished-quizzes/' const nonExistingQuiz = '64cf8a3d40135fba5a0c8fa2' @@ -37,29 +36,16 @@ const testFinishedQuizData = { const testQuizData = { title: 'Assembly', - items: [ - { - question: 'Is it the best programming language?', - answers: [ - { - text: 'Yes', - isCorrect: true - }, - { - text: 'Yes, of course', - isCorrect: false - } - ] - } - ] + description: 'Description', + category: '6502ec2060ec37be943353e2', + items: ['6527ed6c14c6b72f36962364'] } - describe('Quiz controller', () => { let app, server, accessToken, currentUser, testFinishedQuiz, testQuiz beforeAll(async () => { - ; ({ app, server } = await serverInit()) + ;({ app, server } = await serverInit()) }) beforeEach(async () => { @@ -72,7 +58,10 @@ describe('Quiz controller', () => { ...testQuizData }) - testFinishedQuiz = await app.post(endpointUrl).send({ quiz: testQuiz._id, ...testFinishedQuizData }).set('Authorization', `Bearer ${accessToken}`) + testFinishedQuiz = await app + .post(endpointUrl) + .send({ quiz: testQuiz._id, ...testFinishedQuizData }) + .set('Cookie', [`accessToken=${accessToken}`]) }) afterEach(async () => { @@ -102,10 +91,13 @@ describe('Quiz controller', () => { }) it('should throw DOCUMENT_NOT_FOUND for quiz', async () => { - const response = await app.post(endpointUrl).send({ - ...testFinishedQuizData, - quiz: nonExistingQuiz - }).set('Authorization', `Bearer ${accessToken}`) + const response = await app + .post(endpointUrl) + .send({ + ...testFinishedQuizData, + quiz: nonExistingQuiz + }) + .set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Quiz.modelName]), response) }) diff --git a/test/integration/controllers/lesson.spec.js b/test/integration/controllers/lesson.spec.js index 50da4cf4..f98e1834 100644 --- a/test/integration/controllers/lesson.spec.js +++ b/test/integration/controllers/lesson.spec.js @@ -56,7 +56,10 @@ describe('Lesson controller', () => { accessToken = await testUserAuthentication(app, tutorUser) studentAccessToken = await testUserAuthentication(app) - testLessonResponse = await app.post(endpointUrl).set('Authorization', `Bearer ${accessToken}`).send(testLesson) + testLessonResponse = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(testLesson) testLessonId = testLessonResponse.body._id studentAccessToken = await testUserAuthentication(app, studentUserData) @@ -90,7 +93,10 @@ describe('Lesson controller', () => { it('should throw FORBIDDEN', async () => { accessToken = await testUserAuthentication(app) - const response = await app.post(endpointUrl).set('Authorization', `Bearer ${studentAccessToken}`).send(testLesson) + const response = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${studentAccessToken}`]) + .send(testLesson) expectError(403, FORBIDDEN, response) }) @@ -98,7 +104,7 @@ describe('Lesson controller', () => { describe(`GET ${endpointUrl}`, () => { it('get all lessons', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) expect(response.status).toBe(200) expect(response.body).toEqual(expect.objectContaining({ count: 1, items: [expect.any(Object)] })) @@ -113,7 +119,10 @@ describe('Lesson controller', () => { it('should throw FORBIDDEN', async () => { accessToken = await testUserAuthentication(app) - const response = await app.post(endpointUrl).set('Authorization', `Bearer ${studentAccessToken}`).send(testLesson) + const response = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${studentAccessToken}`]) + .send(testLesson) expectError(403, FORBIDDEN, response) }) @@ -123,14 +132,14 @@ describe('Lesson controller', () => { it('should throw FORBIDDEN', async () => { const response = await app .delete(endpointUrl + testLessonResponse.body._id) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) it('should delete lesson by ID', async () => { const response = await app .delete(endpointUrl + testLessonResponse.body._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) @@ -142,7 +151,7 @@ describe('Lesson controller', () => { }) it('should throw NOT_FOUND', async () => { - const response = await app.delete(endpointUrl + nonExistingLessonId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl + nonExistingLessonId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Lesson.modelName]), response) }) @@ -152,7 +161,7 @@ describe('Lesson controller', () => { it('should update a lesson', async () => { const response = await app .patch(endpointUrl + testLessonId) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send(updateData) expect(response.statusCode).toBe(204) @@ -171,7 +180,7 @@ describe('Lesson controller', () => { }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.patch(endpointUrl + nonExistingLessonId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.patch(endpointUrl + nonExistingLessonId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Lesson.modelName]), response) }) @@ -179,7 +188,7 @@ describe('Lesson controller', () => { it('should throw FORBIDDEN', async () => { const response = await app .patch(endpointUrl) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) .send(updateData) expectError(403, FORBIDDEN, response) @@ -190,7 +199,7 @@ describe('Lesson controller', () => { it('Should get lesson by ID', async () => { const response = await app .get(endpointUrl + testLessonResponse.body._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) @@ -207,7 +216,7 @@ describe('Lesson controller', () => { }) }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.get(endpointUrl + nonExistingLessonId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + nonExistingLessonId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Lesson.modelName]), response) }) @@ -219,7 +228,7 @@ describe('Lesson controller', () => { it('should throw FORBIDDEN', async () => { const response = await app .get(endpointUrl + testLessonResponse.body._id) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) diff --git a/test/integration/controllers/message.spec.js b/test/integration/controllers/message.spec.js index b8b7fa74..ed10a2fb 100644 --- a/test/integration/controllers/message.spec.js +++ b/test/integration/controllers/message.spec.js @@ -58,10 +58,16 @@ describe('Message controller', () => { beforeEach(async () => { accessToken = await testUserAuthentication(app) - chatResponse = await app.post(chatEndpointUrl).set('Authorization', `Bearer ${accessToken}`).send(chatBody) + chatResponse = await app + .post(chatEndpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(chatBody) messageBody.chat = chatResponse.body._id - await app.post(endpointUrl(messageBody.chat)).set('Authorization', `Bearer ${accessToken}`).send(messageBody) + await app + .post(endpointUrl(messageBody.chat)) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(messageBody) }) afterEach(async () => { @@ -76,7 +82,7 @@ describe('Message controller', () => { it('should create a new message', async () => { const response = await app .post(endpointUrl(messageBody.chat)) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send(messageBody) expect(response.statusCode).toBe(201) @@ -92,7 +98,7 @@ describe('Message controller', () => { describe(`GET ${endpointUrl}`, () => { it('should get all messages related to a chat', async () => { - const response = await app.get(endpointUrl(messageBody.chat)).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl(messageBody.chat)).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body[0]).toEqual(expect.objectContaining(messageData)) @@ -101,7 +107,7 @@ describe('Message controller', () => { it('should get messages matching the text query', async () => { const response = await app .get(endpointUrl(messageBody.chat)) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .query({ message: searchText }) expect(response.statusCode).toBe(200) @@ -119,13 +125,13 @@ describe('Message controller', () => { const response = await app .get(endpointUrl(messageBody.chat)) - .set('Authorization', `Bearer ${accessTokenForbidden}`) + .set('Cookie', [`accessToken=${accessTokenForbidden}`]) expectError(403, FORBIDDEN, response) }) it('should throw DOCUMENT_NOT_FOUND for chat', async () => { - const response = await app.get(endpointUrl(nonExistingChatId)).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl(nonExistingChatId)).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Chat.modelName]), response) }) @@ -133,7 +139,7 @@ describe('Message controller', () => { describe(`DELETE ${endpointUrl}`, () => { it('should delete all messages related to a chat', async () => { - const response = await app.delete(endpointUrl(messageBody.chat)).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl(messageBody.chat)).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) @@ -149,13 +155,13 @@ describe('Message controller', () => { const response = await app .delete(endpointUrl(messageBody.chat)) - .set('Authorization', `Bearer ${accessTokenForbidden}`) + .set('Cookie', [`accessToken=${accessTokenForbidden}`]) expectError(403, FORBIDDEN, response) }) it('should throw DOCUMENT_NOT_FOUND for chat', async () => { - const response = await app.delete(endpointUrl(nonExistingChatId)).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl(nonExistingChatId)).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Chat.modelName]), response) }) diff --git a/test/integration/controllers/notification.spec.js b/test/integration/controllers/notification.spec.js index a9b9fb5b..236ac592 100644 --- a/test/integration/controllers/notification.spec.js +++ b/test/integration/controllers/notification.spec.js @@ -43,8 +43,8 @@ describe('Notification controller', () => { }) describe(`GET ${endpointUrl}`, () => { - it('should get user\'s notifications and count them', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + it("should get user's notifications and count them", async () => { + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body.count).toBe(1) @@ -64,10 +64,10 @@ describe('Notification controller', () => { }) describe(`DELETE ${endpointUrl}`, () => { - it('should clear all user\'s notifications', async () => { - const response = await app.delete(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + it("should clear all user's notifications", async () => { + const response = await app.delete(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) - const notifications = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + const notifications = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) expect(notifications.body.count).toBe(0) @@ -84,7 +84,7 @@ describe('Notification controller', () => { it('should delete notification by id', async () => { const response = await app .delete(endpointUrl + testNotification._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) @@ -102,7 +102,7 @@ describe('Notification controller', () => { it('should throw DOCUMENT_NOT_FOUND', async () => { const response = await app .delete(endpointUrl + nonExistingNotificationId) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Notification.modelName]), response) }) diff --git a/test/integration/controllers/offer.spec.js b/test/integration/controllers/offer.spec.js index ba2fb230..b90264e3 100644 --- a/test/integration/controllers/offer.spec.js +++ b/test/integration/controllers/offer.spec.js @@ -47,16 +47,22 @@ describe('Offer controller', () => { const { _id, appearance } = categoryResponse[0] const category = { _id: _id.toString(), appearance } - const subjectResponse = await app.post('/subjects/').set('Authorization', `Bearer ${accessToken}`).send({ - name: 'testSubject', - category: category - }) + const subjectResponse = await app + .post('/subjects/') + .set('Cookie', [`accessToken=${accessToken}`]) + .send({ + name: 'testSubject', + category: category + }) const subject = subjectResponse.body._id testOffer.category = category testOffer.subject = subject - testOfferResponse = await app.post(endpointUrl).set('Authorization', `Bearer ${accessToken}`).send(testOffer) + testOfferResponse = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(testOffer) testOffer = testOfferResponse.body testOffer.category = category @@ -98,7 +104,7 @@ describe('Offer controller', () => { describe(`test GET ${endpointUrl}`, () => { it('should GET all offers', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toEqual(expect.objectContaining({ count: 1, items: [expect.any(Object)] })) @@ -107,7 +113,7 @@ describe('Offer controller', () => { describe(`test GET ${endpointUrl}:id`, () => { it('should get an offer by ID', async () => { - const response = await app.get(endpointUrl + testOffer._id).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + testOffer._id).set('Cookie', [`accessToken=${accessToken}`]) expect(response.body).toEqual({ ...testOffer, @@ -135,7 +141,7 @@ describe('Offer controller', () => { }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.get(endpointUrl + nonExistingOfferId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + nonExistingOfferId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Offer.modelName]), response) }) @@ -145,7 +151,7 @@ describe('Offer controller', () => { it('should update offer by ID', async () => { const response = await app .patch(endpointUrl + testOffer._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send(updateData) expect(response.statusCode).toBe(204) @@ -154,7 +160,7 @@ describe('Offer controller', () => { it('should throw DOCUMENT_NOT_FOUND', async () => { const response = await app .patch(endpointUrl + nonExistingOfferId) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send(updateData) expectError(404, DOCUMENT_NOT_FOUND([Offer.modelName]), response) @@ -163,13 +169,13 @@ describe('Offer controller', () => { describe(`test DELETE ${endpointUrl}:id`, () => { it('should delete offer by ID', async () => { - const response = await app.delete(endpointUrl + testOffer._id).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl + testOffer._id).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.get(endpointUrl + nonExistingOfferId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + nonExistingOfferId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Offer.modelName]), response) }) diff --git a/test/integration/controllers/question.spec.js b/test/integration/controllers/question.spec.js index 299a7fb0..53e02d92 100644 --- a/test/integration/controllers/question.spec.js +++ b/test/integration/controllers/question.spec.js @@ -57,7 +57,10 @@ describe('Question controller', () => { currentUser = TokenService.validateAccessToken(accessToken) - testQuestion = await app.post(endpointUrl).send(testQuestionData).set('Authorization', `Bearer ${accessToken}`) + testQuestion = await app + .post(endpointUrl) + .send(testQuestionData) + .set('Cookie', [`accessToken=${accessToken}`]) testQuestionId = testQuestion.body._id }) @@ -71,7 +74,7 @@ describe('Question controller', () => { describe(`GET ${endpointUrl}`, () => { it('should return list of questions', async () => { - const questions = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + const questions = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) expect(questions.statusCode).toBe(200) expect(questions.body.count).toBe(1) @@ -114,7 +117,7 @@ describe('Question controller', () => { const response = await app .post(endpointUrl) .send(testQuestionData) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) @@ -125,7 +128,7 @@ describe('Question controller', () => { const response = await app .patch(endpointUrl + testQuestionId) .send(updateData) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) const updatedQuestion = await Question.findById(testQuestionId) @@ -146,7 +149,7 @@ describe('Question controller', () => { const response = await app .patch(endpointUrl + testQuestionId) .send(updateData) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) diff --git a/test/integration/controllers/quiz.spec.js b/test/integration/controllers/quiz.spec.js index 7a9b819e..46e39103 100644 --- a/test/integration/controllers/quiz.spec.js +++ b/test/integration/controllers/quiz.spec.js @@ -12,7 +12,6 @@ const endpointUrl = '/quizzes/' const testQuizData = { title: 'Assembly', description: 'Description', - category: '6502ec2060ec37be943353e2', items: ['6527ed6c14c6b72f36962364'] } @@ -45,7 +44,10 @@ describe('Quiz controller', () => { currentUser = TokenService.validateAccessToken(accessToken) - testQuiz = await app.post(endpointUrl).set('Authorization', `Bearer ${accessToken}`).send(testQuizData) + testQuiz = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(testQuizData) testQuizId = testQuiz.body._id }) @@ -65,7 +67,6 @@ describe('Quiz controller', () => { createdAt: expect.any(String), updatedAt: expect.any(String), author: currentUser.id, - category: testQuizData.category, ...testQuizData }) }) @@ -79,7 +80,7 @@ describe('Quiz controller', () => { it('should throw FORBIDDEN', async () => { const response = await app .post(endpointUrl) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) .send(testQuizData) expectError(403, FORBIDDEN, response) @@ -88,7 +89,7 @@ describe('Quiz controller', () => { describe(`GET ${endpointUrl}`, () => { it('should get all quizzes', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(Array.isArray(response.body.items)).toBeTruthy() @@ -99,8 +100,8 @@ describe('Quiz controller', () => { author: currentUser.id, createdAt: expect.any(String), updatedAt: expect.any(String), - category: testQuizData.category, - ...testQuizData + ...testQuizData, + category: null } ], count: 1 @@ -114,7 +115,7 @@ describe('Quiz controller', () => { }) it('should throw FORBIDDEN', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${studentAccessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) @@ -122,13 +123,12 @@ describe('Quiz controller', () => { describe(`GET ${endpointUrl}:id`, () => { it('should get quiz by id', async () => { - const response = await app.get(endpointUrl + testQuizId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + testQuizId).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toMatchObject({ _id: expect.any(String), author: currentUser.id, - category: testQuizData.category, createdAt: expect.any(String), updatedAt: expect.any(String), ...testQuizData @@ -142,7 +142,7 @@ describe('Quiz controller', () => { }) it('should throw FORBIDDEN', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${studentAccessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) @@ -153,9 +153,9 @@ describe('Quiz controller', () => { await app .patch(endpointUrl + testQuizId) .send(updateData) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) - const quizResponse = await app.get(endpointUrl + testQuizId).set('Authorization', `Bearer ${accessToken}`) + const quizResponse = await app.get(endpointUrl + testQuizId).set('Cookie', [`accessToken=${accessToken}`]) expect(quizResponse.body).toMatchObject({ ...testQuizData, @@ -173,7 +173,7 @@ describe('Quiz controller', () => { const response = await app .patch(endpointUrl + testQuizId) .send(updateData) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) diff --git a/test/integration/controllers/resourcesCategory.spec.js b/test/integration/controllers/resourcesCategory.spec.js index 1e0dc85b..f7673b6d 100644 --- a/test/integration/controllers/resourcesCategory.spec.js +++ b/test/integration/controllers/resourcesCategory.spec.js @@ -45,7 +45,7 @@ describe('ResourceCategory controller', () => { testResourceCategory = await app .post(endpointUrl) .send(testResourceCategoryData) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) }) afterEach(async () => { @@ -78,18 +78,18 @@ describe('ResourceCategory controller', () => { const response = await app .post(endpointUrl) .send(testResourceCategoryData) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) }) - describe(`PATCH ${endpointUrl}`, () => { + describe(`PATCH ${endpointUrl}:id`, () => { it('should update resource category', async () => { const response = await app - .patch(endpointUrl) + .patch(endpointUrl + testResourceCategory.body._id) .send(updateResourceCategoryData) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) @@ -104,7 +104,7 @@ describe('ResourceCategory controller', () => { const response = await app .patch(endpointUrl) .send(updateResourceCategoryData) - .set('Authorization', `Bearer ${studentAccessToken}`) + .set('Cookie', [`accessToken=${studentAccessToken}`]) expectError(403, FORBIDDEN, response) }) diff --git a/test/integration/controllers/review.spec.js b/test/integration/controllers/review.spec.js index fa0b74b6..c7c725fb 100644 --- a/test/integration/controllers/review.spec.js +++ b/test/integration/controllers/review.spec.js @@ -65,12 +65,15 @@ describe('Review controller', () => { offerBody.category = category subjectBody.category = category - testSubject = await app.post(subjectEndpointUrl).set('Authorization', `Bearer ${accessToken}`).send(subjectBody) + testSubject = await app + .post(subjectEndpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(subjectBody) subjectBody = testSubject.body testOffer = await app .post(offerEndpointUrl) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send({ ...offerBody, subject: subjectBody._id }) offerBody = testOffer.body @@ -78,7 +81,7 @@ describe('Review controller', () => { testReview = await app .post(endpointUrl) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send({ ...reviewBody, offer: offerBody._id }) reviewBody = testReview.body @@ -125,7 +128,7 @@ describe('Review controller', () => { }) it('should get all reviews', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) const { author } = reviewBody const { _id } = offerBody const { _id: subject } = subjectBody @@ -171,7 +174,7 @@ describe('Review controller', () => { }) it('should get a review by ID', async () => { - const response = await app.get(endpointUrl + reviewBody._id).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + reviewBody._id).set('Cookie', [`accessToken=${accessToken}`]) const { author } = reviewBody const { _id } = offerBody const { _id: subject } = subjectBody @@ -203,7 +206,7 @@ describe('Review controller', () => { }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.get(endpointUrl + nonExistingReviewId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + nonExistingReviewId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Review.modelName]), response) }) @@ -219,7 +222,7 @@ describe('Review controller', () => { it('should update a review by ID', async () => { const response = await app .patch(endpointUrl + reviewBody._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send(updateData) expect(response.statusCode).toBe(204) @@ -228,7 +231,7 @@ describe('Review controller', () => { it('should throw DOCUMENT_NOT_FOUND', async () => { const response = await app .patch(endpointUrl + nonExistingReviewId) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send(updateData) expectError(404, DOCUMENT_NOT_FOUND([Review.modelName]), response) @@ -243,13 +246,13 @@ describe('Review controller', () => { }) it('should delete a review by ID', async () => { - const response = await app.delete(endpointUrl + reviewBody._id).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl + reviewBody._id).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.delete(endpointUrl + nonExistingReviewId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl + nonExistingReviewId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Review.modelName]), response) }) diff --git a/test/integration/controllers/subject.spec.js b/test/integration/controllers/subject.spec.js index 6d9dee3d..a5f5be9b 100644 --- a/test/integration/controllers/subject.spec.js +++ b/test/integration/controllers/subject.spec.js @@ -24,12 +24,15 @@ describe('Subject controller', () => { const categoryResponse = await app .post('/categories/') - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send(categoryBody) const category = categoryResponse.body._id subjectBody.category = category - testSubject = await app.post(endpointUrl).set('Authorization', `Bearer ${accessToken}`).send(subjectBody) + testSubject = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(subjectBody) }) afterEach(async () => { @@ -42,7 +45,10 @@ describe('Subject controller', () => { describe(`POST ${endpointUrl}`, () => { it('should throw DOCUMENT_ALREADY_EXISTS', async () => { - const error = await app.post(endpointUrl).set('Authorization', `Bearer ${accessToken}`).send(subjectBody) + const error = await app + .post(endpointUrl) + .set('Cookie', [`accessToken=${accessToken}`]) + .send(subjectBody) expectError(409, DOCUMENT_ALREADY_EXISTS('name'), error) }) @@ -67,7 +73,7 @@ describe('Subject controller', () => { describe(`GET ${endpointUrl}`, () => { it('should GET all subjects', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(Array.isArray(response.body.items)).toBeTruthy() @@ -89,7 +95,7 @@ describe('Subject controller', () => { describe(`GET ${endpointUrl}:id`, () => { it('should get a subject by ID', async () => { - const response = await app.get(endpointUrl + testSubject.body._id).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + testSubject.body._id).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toEqual( @@ -108,7 +114,7 @@ describe('Subject controller', () => { }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.get(endpointUrl + nonExistingSubjectId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + nonExistingSubjectId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Subject.modelName]), response) }) @@ -118,7 +124,7 @@ describe('Subject controller', () => { it('should update subject by ID', async () => { const response = await app .patch(endpointUrl + testSubject.body._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send({ name: 'Eng' }) expect(response.statusCode).toBe(204) @@ -127,7 +133,7 @@ describe('Subject controller', () => { it('should throw DOCUMENT_NOT_FOUND', async () => { const response = await app .patch(endpointUrl + nonExistingSubjectId) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) .send({ name: 'Eng' }) expectError(404, DOCUMENT_NOT_FOUND([Subject.modelName]), response) @@ -138,7 +144,7 @@ describe('Subject controller', () => { it('should delete subject by ID', async () => { const response = await app .delete(endpointUrl + testSubject.body._id) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) @@ -146,7 +152,7 @@ describe('Subject controller', () => { it('should throw DOCUMENT_NOT_FOUND', async () => { const response = await app .delete(endpointUrl + nonExistingSubjectId) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([Subject.modelName]), response) }) diff --git a/test/integration/controllers/user.spec.js b/test/integration/controllers/user.spec.js index 1034bb22..062c94b5 100644 --- a/test/integration/controllers/user.spec.js +++ b/test/integration/controllers/user.spec.js @@ -82,7 +82,7 @@ describe('User controller', () => { }) it('should GET all users', async () => { - const response = await app.get(endpointUrl).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(Array.isArray(response.body.items)).toBeTruthy() @@ -120,7 +120,10 @@ describe('User controller', () => { email: testUser.email } - const response = await app.get(endpointUrl).query(query).set('Authorization', `Bearer ${accessToken}`) + const response = await app + .get(endpointUrl) + .query(query) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.status).toBe(200) expect(Array.isArray(response.body.items)).toBeTruthy() @@ -170,7 +173,7 @@ describe('User controller', () => { }) it('should GET user by ID', async () => { - const response = await app.get(endpointUrl + user._id).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + user._id).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(200) expect(response.body).toMatchObject({ @@ -203,7 +206,7 @@ describe('User controller', () => { }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.get(endpointUrl + nonExistingUserId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.get(endpointUrl + nonExistingUserId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([User.modelName]), response) }) }) @@ -215,7 +218,7 @@ describe('User controller', () => { const response = await app .patch(endpointUrl + currentUserId) .send(updateUserData) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) @@ -232,7 +235,7 @@ describe('User controller', () => { const response = await app .patch(endpointUrl + user._id) .send(updateUserData) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expectError(403, FORBIDDEN, response) }) @@ -258,7 +261,7 @@ describe('User controller', () => { const response = await app .patch(endpointUrl + currentUser.id + changeStatusPath) .send(mockedStatus) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) @@ -267,7 +270,7 @@ describe('User controller', () => { const response = await app .patch(endpointUrl + nonExistingUserId + changeStatusPath) .send(mockedStatus) - .set('Authorization', `Bearer ${accessToken}`) + .set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([User.modelName]), response) }) @@ -284,7 +287,7 @@ describe('User controller', () => { const response = await app .patch(endpointUrl + userWithNoPermissions.id + changeStatusPath) .send(mockedStatus) - .set('Authorization', `Bearer ${noPermissionsAccessToken}`) + .set('Cookie', [`accessToken=${noPermissionsAccessToken}`]) expectError(403, FORBIDDEN, response) }) @@ -298,13 +301,13 @@ describe('User controller', () => { describe(`DELETE ${endpointUrl}:id`, () => { it('should DELETE user by ID', async () => { - const response = await app.delete(endpointUrl + currentUser.id).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl + currentUser.id).set('Cookie', [`accessToken=${accessToken}`]) expect(response.statusCode).toBe(204) }) it('should throw DOCUMENT_NOT_FOUND', async () => { - const response = await app.delete(endpointUrl + nonExistingUserId).set('Authorization', `Bearer ${accessToken}`) + const response = await app.delete(endpointUrl + nonExistingUserId).set('Cookie', [`accessToken=${accessToken}`]) expectError(404, DOCUMENT_NOT_FOUND([User.modelName]), response) }) @@ -320,7 +323,7 @@ describe('User controller', () => { const response = await app .delete(endpointUrl + userWithNoPermissions.id) - .set('Authorization', `Bearer ${noPermissionsAccessToken}`) + .set('Cookie', [`accessToken=${noPermissionsAccessToken}`]) expectError(403, FORBIDDEN, response) }) diff --git a/test/unit/middlewares/auth.spec.js b/test/unit/middlewares/auth.spec.js index e6075f8d..5c39e75d 100644 --- a/test/unit/middlewares/auth.spec.js +++ b/test/unit/middlewares/auth.spec.js @@ -8,32 +8,17 @@ describe('Auth middleware', () => { const mockResponse = {} const mockNextFunc = jest.fn() - it('Should throw UNAUTHORIZED error when auth header is not given', () => { - const mockRequest = { - headers: {} - } - const middlewareFunc = () => authMiddleware(mockRequest, mockResponse, mockNextFunc) - - expect(middlewareFunc).toThrow(error) - }) - it('Should throw UNAUTHORIZED error when access token is not given', () => { - const mockRequest = { - headers: { - authorization: 'invalid_token' - } - } + const mockRequest = { cookies: { accessToken: 'invalid_token' } } + const middlewareFunc = () => authMiddleware(mockRequest, mockResponse, mockNextFunc) expect(middlewareFunc).toThrow(error) }) it('Should throw UNAUTHORIZED error when access token is invalid', () => { - const mockRequest = { - headers: { - authorization: 'Bearer token' - } - } + const mockRequest = { cookies: { accessToken: 'token' } } + const middlewareFunc = () => authMiddleware(mockRequest, mockResponse, mockNextFunc) expect(middlewareFunc).toThrow(error) @@ -42,11 +27,8 @@ describe('Auth middleware', () => { it('Should save userData from accessToken to a request object', () => { const payload = { userId: 'testId' } const { accessToken } = tokenService.generateTokens(payload) - const mockRequest = { - headers: { - authorization: `Bearer ${accessToken}` - } - } + const mockRequest = { cookies: { accessToken } } + authMiddleware(mockRequest, mockResponse, mockNextFunc) expect(mockRequest.user).toEqual(expect.objectContaining(payload))