From 719e25120f0e941365150db57e76a104c8147482 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E2=80=9EBAS8243=E2=80=9C?= <gerd.embruch@uni-hamburg.de>
Date: Fri, 2 Aug 2024 12:02:36 +0200
Subject: [PATCH] fixed verification

---
 .../confirmverification.test.js.snap          | 16 --------
 __tests__/auth/confirmverification.test.js    | 41 +------------------
 controllers/Auth.js                           | 13 +++---
 routes/auth.js                                |  2 +-
 utils/handleTokens.js                         |  7 ++--
 validationSchemes/Auth.js                     |  1 -
 6 files changed, 14 insertions(+), 66 deletions(-)

diff --git a/__tests__/auth/__snapshots__/confirmverification.test.js.snap b/__tests__/auth/__snapshots__/confirmverification.test.js.snap
index 74d300f..db3af42 100644
--- a/__tests__/auth/__snapshots__/confirmverification.test.js.snap
+++ b/__tests__/auth/__snapshots__/confirmverification.test.js.snap
@@ -1,20 +1,5 @@
 // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
 
-exports[`user verify registration token > given required fields are missing > should respond with a proper body 1`] = `
-{
-  "message": "Validation errors. Please check the error messages.",
-  "validationErrors": {
-    "email": "Required",
-  },
-}
-`;
-
-exports[`user verify registration token > given the email is unknown > should respond with a proper body 1`] = `
-{
-  "message": "Unknown eMail address",
-}
-`;
-
 exports[`user verify registration token > given the inputs are valid > should respond with a proper body 1`] = `
 {
   "message": "Account successfully verified. You can now login.",
@@ -25,7 +10,6 @@ exports[`user verify registration token > given the request body is empty > shou
 {
   "message": "Validation errors. Please check the error messages.",
   "validationErrors": {
-    "email": "Required",
     "token": "Required",
   },
 }
diff --git a/__tests__/auth/confirmverification.test.js b/__tests__/auth/confirmverification.test.js
index c97f685..bfa6ad3 100644
--- a/__tests__/auth/confirmverification.test.js
+++ b/__tests__/auth/confirmverification.test.js
@@ -27,7 +27,6 @@ const mockedVals = vi.hoisted(() => {
       id: '66a29da2942b3ebcaf047f07'
     },
     validInput: {
-      email: 'user@mail.local',
       token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbGIBBERISHTl9.lxQ5ZqO8qWJt15bbnSa4wrPQ02_7fvY4CgN1ZRM'
     },
     jwtPayload: {
@@ -55,7 +54,7 @@ vi.mock('../../utils/handleDB.js', async (importOriginal) => {
     ...await importOriginal(),
     dbConnection: vi.fn(() => 'mocked'),
     findOneRecord: vi.fn(() => mockedVals.foundUser),
-    updateOneRecord: vi.fn(() => mockedVals.foundUser)
+    findOneAndUpdate: vi.fn(() => mockedVals.foundUser)
   };
 });
 // import Token Service
@@ -90,24 +89,6 @@ describe('user verify registration token', () => {
     });
   });
 
-  // ############################
-
-  describe('given the email is unknown', async () => {
-    // set response by running route
-    beforeAll(async ({ expect, task }) => {
-      dbService.findOneRecord.mockImplementationOnce(() => null);
-
-      response = await supertest(app)
-        .patch(ROUTE)
-        .send(mockedVals.validInput);
-    });
-    it('should return a proper status code', () => {
-      expect(response.status).toBe(404);
-    });
-    it('should respond with a proper body', () => {
-      expect(response.body).toMatchSnapshot();
-    });
-  });
 
   // ############################
 
@@ -149,24 +130,4 @@ describe('user verify registration token', () => {
       expect(response.body).toMatchSnapshot();
     });
   });
-
-  // ############################
-
-  describe('given required fields are missing', () => {
-    beforeAll(async () => {
-      const { email, ...input } = mockedVals.validInput;
-
-      response = await supertest(app)
-        .post(ROUTE)
-        .send(input);
-    });
-
-    it('should return a proper status code status', () => {
-      expect(response.status).toBe(400);
-    });
-    it('should respond with a proper body', () => {
-      expect(response.body).toMatchSnapshot();
-    });
-  });
-
 });
\ No newline at end of file
diff --git a/controllers/Auth.js b/controllers/Auth.js
index c3b0091..2226855 100644
--- a/controllers/Auth.js
+++ b/controllers/Auth.js
@@ -1,6 +1,6 @@
 import { createAccessToken, createPasswordToken, createRefreshToken, createVerificationToken, deleteRefreshToken, verifyRefreshToken } from "../utils/handleTokens.js";
 import { sendEmail } from "../utils/handleMailer.js";
-import { findOneRecord, updateOneRecord } from "../utils/handleDB.js";
+import { findOneAndUpdate, findOneRecord, updateOneRecord } from "../utils/handleDB.js";
 import User from "../models/User.js";
 import bcrypt from 'bcrypt';
 import { hideConfidentialFields } from "../utils/handleSchemes.js";
@@ -15,8 +15,10 @@ export const sendVerificationEmail = async (req, res, next) => {
 
     let subject = "[RagChat] Account Verification";
     let to = req.document.email;
-    let link = `${process.env.FRONTEND_URL}/verification/${verificationToken}`;
-    let html = `<p>Hi<p><br><p>Please click on the following <a href="${link}">link</a> to process the password reset. This Token is valid for ${process.env.PASSWORD_TOKEN_TTL}.</p>
+    let link = `${process.env.FRONTEND_URL}/signup/${verificationToken}`;
+    let html = `<p>Hi<p><br><p>Please click on the following <a href="${link}">link</a> to process the password reset. 
+    This Token is valid for ${process.env.PASSWORD_TOKEN_TTL}.</p>
+    <p>${link}</p>
     <p>${verificationToken}</p>
          <br><p>If you did not request this, please ignore this email.</p>`;
     await sendEmail({ to, subject, html });
@@ -33,8 +35,9 @@ export const sendVerificationEmail = async (req, res, next) => {
  */
 export const confirmVerification = async (req, res, next) => {
   try {
-    req.document.verified = true;
-    const updatedUser = await updateOneRecord(req.document);
+    // req.document.verified = true;
+    // const updatedUser = await updateOneRecord(req.document);
+    const updatedUser = await findOneAndUpdate(User, { email: req.body.email }, { verified: true });
     // remember document but remove confidential info
     const document = hideConfidentialFields(User, updatedUser);
     return res.json({ message: 'Account successfully verified. You can now login.' });
diff --git a/routes/auth.js b/routes/auth.js
index 5b47862..c527528 100644
--- a/routes/auth.js
+++ b/routes/auth.js
@@ -31,7 +31,7 @@ router.post('/verification',
  */
 router.patch('/verification',
   validate(confirmVerificationSchema),
-  prefetchUserByEmail,
+  // prefetchUserByEmail,
   verifyVerificationToken,
   confirmVerification
 );
diff --git a/utils/handleTokens.js b/utils/handleTokens.js
index 794b2ae..ff5a02f 100644
--- a/utils/handleTokens.js
+++ b/utils/handleTokens.js
@@ -14,7 +14,7 @@ import { performance } from "node:perf_hooks";
  * @return  {token}
  */
 export const createVerificationToken = (payload) => {
-  return jwt.sign({ id: payload.id, email: payload.email }, process.env.VERIFICATION_TOKEN_KEY + payload.verified, { expiresIn: process.env.VERIFICATION_TOKEN_TTL });
+  return jwt.sign({ id: payload.id, email: payload.email }, process.env.VERIFICATION_TOKEN_KEY, { expiresIn: process.env.VERIFICATION_TOKEN_TTL });
 };
 
 /**
@@ -30,10 +30,11 @@ export const createVerificationToken = (payload) => {
  */
 export const verifyVerificationToken = async (req, res, next) => {
   // verify token
-  const valid = jwt.verify(req.body.token, process.env.VERIFICATION_TOKEN_KEY + req.document.verified, async (error, payload) => {
+  const valid = jwt.verify(req.body.token, process.env.VERIFICATION_TOKEN_KEY, async (error, payload) => {
     // if invalid
-    if (error) return res.status(403).json({ message: 'Token is no longer valid.' });
+    if (error) return res.status(498).json({ message: 'Token is no longer valid.' });
     // if valid
+    req.body.email = payload.email;
     next();
   });
 };
diff --git a/validationSchemes/Auth.js b/validationSchemes/Auth.js
index 89e4965..ce62a2f 100644
--- a/validationSchemes/Auth.js
+++ b/validationSchemes/Auth.js
@@ -8,7 +8,6 @@ export const requestVerificationSchema = z.object({
 
 // CONFIRM VERIFICATION
 export const confirmVerificationSchema = z.object({
-  email: z.string().email(),
   token: z.string().min(1),
 });
 
-- 
GitLab