Users test passes and the UserController works (manual testing)

This commit is contained in:
C. Fuhrman 2024-10-01 18:03:55 -04:00
parent a175718eec
commit 59a59710ea
4 changed files with 72 additions and 70 deletions

View file

@ -21,7 +21,7 @@ describe('Users', () => {
getConnection: jest.fn().mockReturnThis(), // Add getConnection method getConnection: jest.fn().mockReturnThis(), // Add getConnection method
collection: jest.fn().mockReturnThis(), collection: jest.fn().mockReturnThis(),
findOne: jest.fn(), findOne: jest.fn(),
insertOne: jest.fn().mockResolvedValue({ _id: new ObjectId() }), // Mock insertOne to return an ObjectId insertOne: jest.fn().mockResolvedValue({ insertedId: new ObjectId() }), // Mock insertOne to return an ObjectId
updateOne: jest.fn(), updateOne: jest.fn(),
deleteOne: jest.fn(), deleteOne: jest.fn(),
}; };
@ -31,7 +31,7 @@ describe('Users', () => {
it('should register a new user', async () => { it('should register a new user', async () => {
db.collection().findOne.mockResolvedValue(null); // No user found db.collection().findOne.mockResolvedValue(null); // No user found
db.collection().insertOne.mockResolvedValue({ _id: new ObjectId() }); db.collection().insertOne.mockResolvedValue({ insertedId: new ObjectId() });
bcrypt.hash.mockResolvedValue('hashedPassword'); bcrypt.hash.mockResolvedValue('hashedPassword');
Folders.create.mockResolvedValue(true); Folders.create.mockResolvedValue(true);
@ -48,7 +48,7 @@ describe('Users', () => {
created_at: expect.any(Date), created_at: expect.any(Date),
}); });
expect(Folders.create).toHaveBeenCalledWith('Dossier par Défaut', expect.any(String)); expect(Folders.create).toHaveBeenCalledWith('Dossier par Défaut', expect.any(String));
expect(result._id).toBeDefined(); // Ensure result has _id expect(result.insertedId).toBeDefined(); // Ensure result has insertedId
}); });
// it('should update the user password', async () => { // it('should update the user password', async () => {

View file

@ -1,41 +1,45 @@
const emailer = require('../config/email.js'); const emailer = require('../config/email.js');
const model = require('../models/users.js'); const userModel = require('../models/users.js');
const jwt = require('../middleware/jwtToken.js'); const jwt = require('../middleware/jwtToken.js');
const db = require('../config/db.js'); const db = require('../config/db.js');
const AppError = require('../middleware/AppError.js'); const AppError = require('../middleware/AppError.js');
const { MISSING_REQUIRED_PARAMETER, LOGIN_CREDENTIALS_ERROR, GENERATE_PASSWORD_ERROR, UPDATE_PASSWORD_ERROR, DELETE_USER_ERROR } = require('../constants/errorCodes'); const { MISSING_REQUIRED_PARAMETER, LOGIN_CREDENTIALS_ERROR, GENERATE_PASSWORD_ERROR, UPDATE_PASSWORD_ERROR, DELETE_USER_ERROR } = require('../constants/errorCodes');
// controllers must use arrow functions to bind 'this' to the class instance in order to access class properties as callbacks in Express
class UsersController { class UsersController {
constructor() { constructor() {
console.log("UsersController constructor: db", db)
this.db = db; this.db = db;
this.users = new model(this.db); this.users = new userModel(this.db);
console.log("UsersController constructor: users", this.users);
} }
async register(req, res, next) { register = async (req, res, next) => {
try { try {
const { email, password } = req.body; const { email, password } = req.body;
if (!email || !password) { if (!email || !password) {
throw new AppError(MISSING_REQUIRED_PARAMETER); throw new AppError(MISSING_REQUIRED_PARAMETER);
} }
await model.register(email, password); if (!this.users) {
throw new AppError('Users model not found');
emailer.registerConfirmation(email) }
await this.users.register(email, password);
emailer.registerConfirmation(email);
return res.status(200).json({ return res.status(200).json({
message: 'Utilisateur créé avec succès.' message: 'Utilisateur créé avec succès.'
}); });
} } catch (error) {
catch (error) {
return next(error); return next(error);
} }
} }
login = async (req, res, next) => {
async login(req, res, next) {
try { try {
const { email, password } = req.body; const { email, password } = req.body;
@ -43,7 +47,11 @@ class UsersController {
throw new AppError(MISSING_REQUIRED_PARAMETER); throw new AppError(MISSING_REQUIRED_PARAMETER);
} }
const user = await model.login(email, password); if (!this) {
throw new AppError('UsersController not initialized');
}
const user = await this.users.login(email, password);
if (!user) { if (!user) {
throw new AppError(LOGIN_CREDENTIALS_ERROR); throw new AppError(LOGIN_CREDENTIALS_ERROR);
@ -51,102 +59,93 @@ class UsersController {
const token = jwt.create(user.email, user._id); const token = jwt.create(user.email, user._id);
return res.status(200).json({ return res.status(200).json({ token });
token: token, } catch (error) {
id: user.email next(error);
});
}
catch (error) {
return next(error);
} }
} }
async resetPassword(req, res, next) { resetPassword = async (req, res, next) => {
try { try {
const { email } = req.body; const { email } = req.body;
if (!email) { if (!email) {
throw new AppError(MISSING_REQUIRED_PARAMETER); throw new AppError(MISSING_REQUIRED_PARAMETER);
} }
const newPassword = await model.resetPassword(email); const newPassword = await this.users.resetPassword(email);
if (!newPassword) { if (!newPassword) {
throw new AppError(GENERATE_PASSWORD_ERROR); throw new AppError(GENERATE_PASSWORD_ERROR);
} }
emailer.newPasswordConfirmation(email, newPassword); emailer.newPasswordConfirmation(email, newPassword);
return res.status(200).json({ return res.status(200).json({
message: 'Nouveau mot de passe envoyé par courriel.' message: 'Nouveau mot de passe envoyé par courriel.'
}); });
} } catch (error) {
catch (error) {
return next(error); return next(error);
} }
} }
async changePassword(req, res, next) { changePassword = async (req, res, next) => {
try { try {
const { email, oldPassword, newPassword } = req.body; const { email, oldPassword, newPassword } = req.body;
if (!email || !oldPassword || !newPassword) { if (!email || !oldPassword || !newPassword) {
throw new AppError(MISSING_REQUIRED_PARAMETER); throw new AppError(MISSING_REQUIRED_PARAMETER);
} }
// verify creds first // verify creds first
const user = await model.login(email, oldPassword); const user = await this.users.login(email, oldPassword);
if (!user) { if (!user) {
throw new AppError(LOGIN_CREDENTIALS_ERROR); throw new AppError(LOGIN_CREDENTIALS_ERROR);
} }
const password = await model.changePassword(email, newPassword) const password = await this.users.changePassword(email, newPassword);
if (!password) { if (!password) {
throw new AppError(UPDATE_PASSWORD_ERROR); throw new AppError(UPDATE_PASSWORD_ERROR);
} }
return res.status(200).json({ return res.status(200).json({
message: 'Mot de passe changé avec succès.' message: 'Mot de passe changé avec succès.'
}); });
} } catch (error) {
catch (error) {
return next(error); return next(error);
} }
} }
async delete(req, res, next) { delete = async (req, res, next) => {
try { try {
const { email, password } = req.body; const { email, password } = req.body;
if (!email || !password) { if (!email || !password) {
throw new AppError(MISSING_REQUIRED_PARAMETER); throw new AppError(MISSING_REQUIRED_PARAMETER);
} }
// verify creds first // verify creds first
const user = await model.login(email, password); const user = await this.users.login(email, password);
if (!user) { if (!user) {
throw new AppError(LOGIN_CREDENTIALS_ERROR); throw new AppError(LOGIN_CREDENTIALS_ERROR);
} }
const result = await model.delete(email) const result = await this.users.delete(email);
if (!result) { if (!result) {
throw new AppError(DELETE_USER_ERROR) throw new AppError(DELETE_USER_ERROR);
} }
return res.status(200).json({ return res.status(200).json({
message: 'Utilisateur supprimé avec succès' message: 'Utilisateur supprimé avec succès'
}); });
} } catch (error) {
catch (error) {
return next(error); return next(error);
} }
} }
} }
module.exports = new UsersController; module.exports = UsersController;

View file

@ -42,7 +42,8 @@ class Users {
}; };
const result = await userCollection.insertOne(newUser); const result = await userCollection.insertOne(newUser);
const userId = result._id.toString(); console.log("userCollection.insertOne() result", result);
const userId = result.insertedId.toString();
const folderTitle = 'Dossier par Défaut'; const folderTitle = 'Dossier par Défaut';
await Folders.create(folderTitle, userId); await Folders.create(folderTitle, userId);

View file

@ -2,12 +2,14 @@ const express = require('express');
const router = express.Router(); const router = express.Router();
const jwt = require('../middleware/jwtToken.js'); const jwt = require('../middleware/jwtToken.js');
const usersController = require('../controllers/users.js') const usersController = require('../controllers/users.js');
// instantiate the controller
const users = new usersController();
router.post("/register", usersController.register); router.post("/register", users.register);
router.post("/login", usersController.login); router.post("/login", users.login);
router.post("/reset-password", usersController.resetPassword); router.post("/reset-password", users.resetPassword);
router.post("/change-password", jwt.authenticate, usersController.changePassword); router.post("/change-password", jwt.authenticate, users.changePassword);
router.post("/delete-user", jwt.authenticate, usersController.delete); router.post("/delete-user", jwt.authenticate, users.delete);
module.exports = router; module.exports = router;