Skip to content
Snippets Groups Projects
Commit 719e2512 authored by Embruch, Gerd's avatar Embruch, Gerd
Browse files

fixed verification

parent d027e5fd
Branches
No related tags found
No related merge requests found
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html // 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`] = ` 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.", "message": "Account successfully verified. You can now login.",
...@@ -25,7 +10,6 @@ exports[`user verify registration token > given the request body is empty > shou ...@@ -25,7 +10,6 @@ exports[`user verify registration token > given the request body is empty > shou
{ {
"message": "Validation errors. Please check the error messages.", "message": "Validation errors. Please check the error messages.",
"validationErrors": { "validationErrors": {
"email": "Required",
"token": "Required", "token": "Required",
}, },
} }
......
...@@ -27,7 +27,6 @@ const mockedVals = vi.hoisted(() => { ...@@ -27,7 +27,6 @@ const mockedVals = vi.hoisted(() => {
id: '66a29da2942b3ebcaf047f07' id: '66a29da2942b3ebcaf047f07'
}, },
validInput: { validInput: {
email: 'user@mail.local',
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbGIBBERISHTl9.lxQ5ZqO8qWJt15bbnSa4wrPQ02_7fvY4CgN1ZRM' token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbGIBBERISHTl9.lxQ5ZqO8qWJt15bbnSa4wrPQ02_7fvY4CgN1ZRM'
}, },
jwtPayload: { jwtPayload: {
...@@ -55,7 +54,7 @@ vi.mock('../../utils/handleDB.js', async (importOriginal) => { ...@@ -55,7 +54,7 @@ vi.mock('../../utils/handleDB.js', async (importOriginal) => {
...await importOriginal(), ...await importOriginal(),
dbConnection: vi.fn(() => 'mocked'), dbConnection: vi.fn(() => 'mocked'),
findOneRecord: vi.fn(() => mockedVals.foundUser), findOneRecord: vi.fn(() => mockedVals.foundUser),
updateOneRecord: vi.fn(() => mockedVals.foundUser) findOneAndUpdate: vi.fn(() => mockedVals.foundUser)
}; };
}); });
// import Token Service // import Token Service
...@@ -90,24 +89,6 @@ describe('user verify registration token', () => { ...@@ -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', () => { ...@@ -149,24 +130,4 @@ describe('user verify registration token', () => {
expect(response.body).toMatchSnapshot(); 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
import { createAccessToken, createPasswordToken, createRefreshToken, createVerificationToken, deleteRefreshToken, verifyRefreshToken } from "../utils/handleTokens.js"; import { createAccessToken, createPasswordToken, createRefreshToken, createVerificationToken, deleteRefreshToken, verifyRefreshToken } from "../utils/handleTokens.js";
import { sendEmail } from "../utils/handleMailer.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 User from "../models/User.js";
import bcrypt from 'bcrypt'; import bcrypt from 'bcrypt';
import { hideConfidentialFields } from "../utils/handleSchemes.js"; import { hideConfidentialFields } from "../utils/handleSchemes.js";
...@@ -15,8 +15,10 @@ export const sendVerificationEmail = async (req, res, next) => { ...@@ -15,8 +15,10 @@ export const sendVerificationEmail = async (req, res, next) => {
let subject = "[RagChat] Account Verification"; let subject = "[RagChat] Account Verification";
let to = req.document.email; let to = req.document.email;
let link = `${process.env.FRONTEND_URL}/verification/${verificationToken}`; 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> 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> <p>${verificationToken}</p>
<br><p>If you did not request this, please ignore this email.</p>`; <br><p>If you did not request this, please ignore this email.</p>`;
await sendEmail({ to, subject, html }); await sendEmail({ to, subject, html });
...@@ -33,8 +35,9 @@ export const sendVerificationEmail = async (req, res, next) => { ...@@ -33,8 +35,9 @@ export const sendVerificationEmail = async (req, res, next) => {
*/ */
export const confirmVerification = async (req, res, next) => { export const confirmVerification = async (req, res, next) => {
try { try {
req.document.verified = true; // req.document.verified = true;
const updatedUser = await updateOneRecord(req.document); // const updatedUser = await updateOneRecord(req.document);
const updatedUser = await findOneAndUpdate(User, { email: req.body.email }, { verified: true });
// remember document but remove confidential info // remember document but remove confidential info
const document = hideConfidentialFields(User, updatedUser); const document = hideConfidentialFields(User, updatedUser);
return res.json({ message: 'Account successfully verified. You can now login.' }); return res.json({ message: 'Account successfully verified. You can now login.' });
......
...@@ -31,7 +31,7 @@ router.post('/verification', ...@@ -31,7 +31,7 @@ router.post('/verification',
*/ */
router.patch('/verification', router.patch('/verification',
validate(confirmVerificationSchema), validate(confirmVerificationSchema),
prefetchUserByEmail, // prefetchUserByEmail,
verifyVerificationToken, verifyVerificationToken,
confirmVerification confirmVerification
); );
......
...@@ -14,7 +14,7 @@ import { performance } from "node:perf_hooks"; ...@@ -14,7 +14,7 @@ import { performance } from "node:perf_hooks";
* @return {token} * @return {token}
*/ */
export const createVerificationToken = (payload) => { 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) => { ...@@ -30,10 +30,11 @@ export const createVerificationToken = (payload) => {
*/ */
export const verifyVerificationToken = async (req, res, next) => { export const verifyVerificationToken = async (req, res, next) => {
// verify token // 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 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 // if valid
req.body.email = payload.email;
next(); next();
}); });
}; };
......
...@@ -8,7 +8,6 @@ export const requestVerificationSchema = z.object({ ...@@ -8,7 +8,6 @@ export const requestVerificationSchema = z.object({
// CONFIRM VERIFICATION // CONFIRM VERIFICATION
export const confirmVerificationSchema = z.object({ export const confirmVerificationSchema = z.object({
email: z.string().email(),
token: z.string().min(1), token: z.string().min(1),
}); });
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment