Compare commits

..

No commits in common. "68f301b972e6c1b8eedbf283347d6fb62e5d02dc" and "d52078acbfb6d234b5c2c99f6f8325a72e909f9f" have entirely different histories.

20 changed files with 86 additions and 204 deletions

View file

@ -2,7 +2,6 @@ MIT License
Copyright (c) 2023 ETS-PFE004-Plateforme-sondage-minitest
Copyright (c) 2024 Louis-Antoine Caron, Mathieu Roy, Mélanie St-Hilaire, Samy Waddah
Copyright (c) 2024 Gabriel Moisan-Matte, Mathieu Sévigny-Lavallée, Jerry Kwok Hiu Fung, Bruno Roesner, Florent Serres
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View file

@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import { act } from 'react';
@ -17,30 +17,21 @@ const question = questions[0];
describe('MultipleChoiceQuestionDisplay', () => {
const mockHandleOnSubmitAnswer = jest.fn();
const TestWrapper = ({ showAnswer }: { showAnswer: boolean }) => {
const [showAnswerState, setShowAnswerState] = useState(showAnswer);
const handleOnSubmitAnswer = (answer: string) => {
mockHandleOnSubmitAnswer(answer);
setShowAnswerState(true);
};
return (
<MemoryRouter>
<MultipleChoiceQuestionDisplay
question={question}
handleOnSubmitAnswer={handleOnSubmitAnswer}
showAnswer={showAnswerState}
/>
</MemoryRouter>
);
const sampleProps = {
question: question,
handleOnSubmitAnswer: mockHandleOnSubmitAnswer,
showAnswer: false
};
const choices = question.choices;
beforeEach(() => {
render(<TestWrapper showAnswer={false} />);
render(
<MemoryRouter>
<MultipleChoiceQuestionDisplay
{...sampleProps}
/>
</MemoryRouter>);
});
test('renders the question and choices', () => {
@ -64,6 +55,7 @@ describe('MultipleChoiceQuestionDisplay', () => {
act(() => {
fireEvent.click(choiceButton);
});
const submitButton = screen.getByText('Répondre');
act(() => {
fireEvent.click(submitButton);
@ -71,51 +63,4 @@ describe('MultipleChoiceQuestionDisplay', () => {
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith('Choice 1');
});
it('should show ✅ next to the correct answer and ❌ next to the wrong answers when showAnswer is true', async () => {
const choiceButton = screen.getByText('Choice 1').closest('button');
if (!choiceButton) throw new Error('Choice button not found');
// Click on choiceButton
act(() => {
fireEvent.click(choiceButton);
});
const button = screen.getByText("Répondre");
act(() => {
fireEvent.click(button);
});
// Wait for the DOM to update
const correctAnswer = screen.getByText("Choice 1").closest('button');
expect(correctAnswer).toBeInTheDocument();
expect(correctAnswer?.textContent).toContain('✅');
const wrongAnswer1 = screen.getByText("Choice 2").closest('button');
expect(wrongAnswer1).toBeInTheDocument();
expect(wrongAnswer1?.textContent).toContain('❌');
});
it('should not show ✅ or ❌ when repondre button is not clicked', async () => {
const choiceButton = screen.getByText('Choice 1').closest('button');
if (!choiceButton) throw new Error('Choice button not found');
// Click on choiceButton
act(() => {
fireEvent.click(choiceButton);
});
// Check for correct answer
const correctAnswer = screen.getByText("Choice 1").closest('button');
expect(correctAnswer).toBeInTheDocument();
expect(correctAnswer?.textContent).not.toContain('✅');
// Check for wrong answers
const wrongAnswer1 = screen.getByText("Choice 2");
expect(wrongAnswer1).toBeInTheDocument();
expect(wrongAnswer1?.textContent).not.toContain('❌');
});
});
});

View file

@ -1,5 +1,5 @@
// TrueFalseQuestion.test.tsx
import React, { useState } from 'react';
import React from 'react';
import { render, fireEvent, screen, act } from '@testing-library/react';
import '@testing-library/jest-dom';
import { MemoryRouter } from 'react-router-dom';
@ -9,31 +9,20 @@ import { parse, TrueFalseQuestion } from 'gift-pegjs';
describe('TrueFalseQuestion Component', () => {
const mockHandleSubmitAnswer = jest.fn();
const sampleStem = 'Sample True False Question';
const trueFalseQuestion =
const trueFalseQuestion =
parse(`${sampleStem}{T}`)[0] as TrueFalseQuestion;
const TestWrapper = ({ showAnswer }: { showAnswer: boolean }) => {
const [showAnswerState, setShowAnswerState] = useState(showAnswer);
const handleOnSubmitAnswer = (answer: boolean) => {
mockHandleSubmitAnswer(answer);
setShowAnswerState(true);
};
return (
<MemoryRouter>
<TrueFalseQuestionDisplay
question={trueFalseQuestion}
handleOnSubmitAnswer={handleOnSubmitAnswer}
showAnswer={showAnswerState}
/>
</MemoryRouter>
);
const sampleProps = {
question: trueFalseQuestion,
handleOnSubmitAnswer: mockHandleSubmitAnswer,
showAnswer: false
};
beforeEach(() => {
render(<TestWrapper showAnswer={false} />);
render(
<MemoryRouter>
<TrueFalseQuestionDisplay {...sampleProps} />
</MemoryRouter>);
});
it('renders correctly', () => {
@ -84,50 +73,4 @@ describe('TrueFalseQuestion Component', () => {
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(false);
});
it('should show ✅ next to the correct answer and ❌ next to the wrong answers when showAnswer is true', async () => {
const choiceButton = screen.getByText('Vrai').closest('button');
if (!choiceButton) throw new Error('T button not found');
// Click on choiceButton
act(() => {
fireEvent.click(choiceButton);
});
const button = screen.getByText("Répondre");
act(() => {
fireEvent.click(button);
});
// Wait for the DOM to update
const correctAnswer = screen.getByText("Vrai").closest('button');
expect(correctAnswer).toBeInTheDocument();
expect(correctAnswer?.textContent).toContain('✅');
const wrongAnswer1 = screen.getByText("Faux").closest('button');
expect(wrongAnswer1).toBeInTheDocument();
expect(wrongAnswer1?.textContent).toContain('❌');
});
it('should not show ✅ or ❌ when repondre button is not clicked', async () => {
const choiceButton = screen.getByText('Vrai').closest('button');
if (!choiceButton) throw new Error('Choice button not found');
// Click on choiceButton
act(() => {
fireEvent.click(choiceButton);
});
// Check for correct answer
const correctAnswer = screen.getByText("Vrai").closest('button');
expect(correctAnswer).toBeInTheDocument();
expect(correctAnswer?.textContent).not.toContain('✅');
// Check for wrong answers
const wrongAnswer1 = screen.getByText("Faux");
expect(wrongAnswer1).toBeInTheDocument();
expect(wrongAnswer1?.textContent).not.toContain('❌');
});
});

View file

@ -153,7 +153,7 @@ const GiftCheatSheet: React.FC = () => {
</pre>
</div>
<div className="question-type" id="images-section">
<div className="question-type">
<h4> 9. Images </h4>
<p>Il est possible d&apos;insérer une image dans une question, une réponse (choix multiple) et dans une rétroaction. D&apos;abord, <strong>le format de l&apos;élément doit être [markdown]</strong>. Ensuite utilisez la syntaxe suivante&nbsp;:</p>
<pre>
@ -185,7 +185,8 @@ const GiftCheatSheet: React.FC = () => {
Attention: l&apos;ancienne fonctionnalité avec les balises <code>{'<img>'}</code> n&apos;est plus
supportée.
</p>
</div>
</div>
<div className="question-type">
<h4> 10. Informations supplémentaires </h4>
<p>

View file

@ -12,9 +12,10 @@ interface Props {
}
const MultipleChoiceQuestionDisplay: React.FC<Props> = (props) => {
const { question, showAnswer, handleOnSubmitAnswer } = props;
const [answer, setAnswer] = useState<string>();
useEffect(() => {
setAnswer(undefined);
}, [question]);
@ -23,6 +24,7 @@ const MultipleChoiceQuestionDisplay: React.FC<Props> = (props) => {
setAnswer(choice);
};
const alpha = Array.from(Array(26)).map((_e, i) => i + 65);
const alphabet = alpha.map((x) => String.fromCharCode(x));
return (
@ -35,23 +37,25 @@ const MultipleChoiceQuestionDisplay: React.FC<Props> = (props) => {
const selected = answer === choice.formattedText.text ? 'selected' : '';
return (
<div key={choice.formattedText.text + i} className="choice-container">
<Button
<Button
variant="text"
className="button-wrapper"
onClick={() => !showAnswer && handleOnClickAnswer(choice.formattedText.text)}>
{showAnswer? (<div> {(choice.isCorrect ? '✅' : '❌')}</div>)
:``}
onClick={() => !showAnswer && handleOnClickAnswer(choice.formattedText.text)}
>
{choice.formattedFeedback === null &&
showAnswer &&
(choice.isCorrect ? '✅' : '❌')}
<div className={`circle ${selected}`}>{alphabet[i]}</div>
<div className={`answer-text ${selected}`}>
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(choice.formattedText) }} />
</div>
{choice.formattedFeedback && showAnswer && (
</Button>
{choice.formattedFeedback && showAnswer && (
<div className="feedback-container mb-1 mt-1/2">
{choice.isCorrect ? '✅' : '❌'}
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(choice.formattedFeedback) }} />
</div>
)}
</Button>
</div>
);
})}

View file

@ -22,6 +22,7 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
const selectedTrue = answer ? 'selected' : '';
const selectedFalse = answer !== undefined && !answer ? 'selected' : '';
const correctAnswer = question.isTrue === answer;
return (
<div className="question-container">
<div className="question content">
@ -33,7 +34,7 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
onClick={() => !showAnswer && setAnswer(true)}
fullWidth
>
{showAnswer? (<div> {(question.isTrue ? '✅' : '❌')}</div>):``}
{showAnswer && (correctAnswer ? '✅' : '❌')}
<div className={`circle ${selectedTrue}`}>V</div>
<div className={`answer-text ${selectedTrue}`}>Vrai</div>
</Button>
@ -42,7 +43,7 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
onClick={() => !showAnswer && setAnswer(false)}
fullWidth
>
{showAnswer? (<div> {(!question.isTrue ? '✅' : '❌')}</div>):``}
{showAnswer && (!correctAnswer ? '✅' : '❌')}
<div className={`circle ${selectedFalse}`}>F</div>
<div className={`answer-text ${selectedFalse}`}>Faux</div>
</Button>

View file

@ -61,14 +61,6 @@ const QuizForm: React.FC = () => {
};
}, []);
const scrollToImagesSection = (event: { preventDefault: () => void; }) => {
event.preventDefault();
const section = document.getElementById('images-section');
if (section) {
section.scrollIntoView({ behavior: 'smooth' });
}
};
useEffect(() => {
const fetchData = async () => {
const userFolders = await ApiService.getUserFolders();
@ -285,18 +277,10 @@ const QuizForm: React.FC = () => {
</div>
<h4>Mes images :</h4>
<div>
<div>
<div style={{ display: "inline" }}>(Voir section </div>
<a href="#images-section"style={{ textDecoration: "none" }} onClick={scrollToImagesSection}>
<u><em><h4 style={{ display: "inline" }}> 9. Images </h4></em></u>
</a>
<div style={{ display: "inline" }}> ci-dessous</div>
<div style={{ display: "inline" }}>)</div>
<br />
<em> - Cliquez sur un lien pour le copier</em>
</div>
<ul>
<div>(Cliquez sur un lien pour le copier)</div>
<ul>
{imageLinks.map((link, index) => {
const imgTag = `![alt_text](${escapeForGIFT(link)} "texte de l'infobulle")`;
return (

View file

@ -1,4 +1,4 @@
const request = require("supertest");
const AuthConfig = require("../config/auth.js");
const AuthManager = require("../auth/auth-manager.js");
@ -115,7 +115,7 @@ describe(
expressMock.get = () => {}
let authConfigInstance;
let authmanagerInstance;
let logSpy;
// Initialisez l'instance avec la configuration mockée
beforeAll(() => {
@ -158,7 +158,6 @@ describe(
};
authConfigInstance.loadConfigTest(validModule); // On injecte la configuration mockée
authmanagerInstance = new AuthManager(expressMock,authConfigInstance.config);
authmanagerInstance.getUserModel();
expect(logSpy).toHaveBeenCalledTimes(0);
logSpy.mockClear();
});
@ -201,7 +200,7 @@ describe(
};
authConfigInstance.loadConfigTest(validModuleInvalidProvider); // On injecte la configuration mockée
authmanagerInstance = new AuthManager(expressMock,authConfigInstance.config);
expect(logSpy).toHaveBeenCalledTimes(4);
expect(logSpy).toHaveBeenCalledTimes(2);
logSpy.mockClear();
});
})

View file

@ -103,9 +103,8 @@ app.use(session({
cookie: { secure: process.env.NODE_ENV === 'production' }
}));
let authManager = new AuthManager(app,null,userModel);
authManager.getUserModel();
app.use(errorHandler);
authManager = new AuthManager(app,null,userModel)
app.use(errorHandler)
// Start server
async function start() {

View file

@ -2,10 +2,8 @@ const fs = require('fs');
const AuthConfig = require('../config/auth.js');
const jwt = require('../middleware/jwtToken.js');
const emailer = require('../config/email.js');
const MISSING_REQUIRED_PARAMETER = {
message: 'Paramètre requis manquant.',
code: 400
};
const model = require('../controllers/users.js');
class AuthManager{
constructor(expressapp,configs=null,userModel){
this.modules = []
@ -35,7 +33,7 @@ class AuthManager{
this.modules.push(new Module(this,this.configs.auth[name]));
console.info(`Module d'authentification '${name}' ajouté`)
} else{
console.error(`Le module d'authentification ${name} n'as pas été chargé car il est introuvable`);
console.error(`Le module d'authentification ${name} n'as pas été chargé car il est introuvable`)
}
}
@ -44,14 +42,12 @@ class AuthManager{
try{
module.registerAuth(this.app)
} catch(error){
console.error(`L'enregistrement du module ${module} a échoué.`);
console.error(`Error: ${error} `);
console.error(`L'enregistrement du module ${module} a échoué.`)
}
}
}
// eslint-disable-next-line no-unused-vars
async login(userInfo,req,res,next){ //passport and simpleauth use next
async login(userInfo,req,res,next){
const tokenToSave = jwt.create(userInfo.email, userInfo._id,userInfo.roles);
res.redirect(`/auth/callback?user=${tokenToSave}&username=${userInfo.name}`);
console.info(`L'utilisateur '${userInfo.name}' vient de se connecter`)
@ -59,7 +55,7 @@ class AuthManager{
async register(userInfos){
if (!userInfos.email || !userInfos.password) {
throw MISSING_REQUIRED_PARAMETER;
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const user = await this.simpleregister.register(userInfos);
emailer.registerConfirmation(user.email)

View file

@ -2,6 +2,7 @@ var OAuth2Strategy = require('passport-oauth2')
var authUserAssoc = require('../../../models/authUserAssociation')
var users = require('../../../models/users')
var { hasNestedValue } = require('../../../utils')
var jwt = require('../../../middleware/jwtToken')
class PassportOAuth {
constructor(passportjs, auth_name) {

View file

@ -2,6 +2,7 @@ var OpenIDConnectStrategy = require('passport-openidconnect')
var authUserAssoc = require('../../../models/authUserAssociation')
var users = require('../../../models/users')
var { hasNestedValue } = require('../../../utils')
var jwt = require('../../../middleware/jwtToken')
class PassportOpenIDConnect {
constructor(passportjs, auth_name) {
@ -14,8 +15,7 @@ class PassportOpenIDConnect {
const config = await fetch(provider.OIDC_CONFIG_URL)
return await config.json()
} catch (error) {
console.error(`Les informations de connexions de la connexion OIDC ${name} n'ont pu être chargées.`);
console.error(`Error: ${error} `);
console.error(`Les informations de connexions de la connexion OIDC ${name} n'ont pu être chargées.`)
}
}
@ -70,11 +70,10 @@ class PassportOpenIDConnect {
user_account.name = received_user.name
user_account.roles = received_user.roles
await users.editUser(user_account);
await users.editUser(user_account)
return done(null, user_account);
} catch (error) {
console.error(`Error: ${error} `);
}
}));

View file

@ -24,8 +24,7 @@ class PassportJs{
this.registeredProviders[provider.type].register(expressapp,passport,this.endpoint,name,provider)
authprovider.create(auth_id)
} catch(error){
console.error(`La connexion ${name} de type ${provider.type} n'as pu être chargé.`);
console.error(`Error: ${error} `);
console.error(`La connexion ${name} de type ${provider.type} n'as pu être chargé.`)
}
}
}
@ -46,8 +45,7 @@ class PassportJs{
this.registeredProviders[providerType]= new Provider(this,auth_id)
console.info(`Le type de connexion '${providerType}' a été ajouté dans passportjs.`)
} catch(error){
console.error(`Le type de connexion '${providerType}' n'as pas pu être chargé dans passportjs.`);
console.error(`Error: ${error} `);
console.error(`Le type de connexion '${providerType}' n'as pas pu être chargé dans passportjs.`)
}
}

View file

@ -15,13 +15,12 @@ class SimpleAuth {
async registerAuth(expressapp) {
try {
expressapp.post(`${this.endpoint}/register`, (req, res) => this.register(this, req, res));
expressapp.post(`${this.endpoint}/login`, (req, res, next) => this.authenticate(this, req, res, next));
expressapp.post(`${this.endpoint}/reset-password`, (req, res, next) => this.resetPassword(this, req, res, next));
expressapp.post(`${this.endpoint}/change-password`, jwt.authenticate, (req, res, next) => this.changePassword(this, req, res, next));
expressapp.post(`${this.endpoint}/register`, (req, res, next) => this.register(this, req, res));
expressapp.post(`${this.endpoint}/login`, (req, res, next) => this.authenticate(this, req, res));
expressapp.post(`${this.endpoint}/reset-password`, (req, res, next) => this.resetPassword(this, req, res));
expressapp.post(`${this.endpoint}/change-password`, jwt.authenticate, (req, res, next) => this.changePassword(this, req, res));
} catch (error) {
console.error(`La connexion ${name} de type ${this.providers.type} n'as pu être chargé.`);
console.error(`Error: ${error} `);
console.error(`La connexion ${name} de type ${provider.type} n'as pu être chargé.`)
}
}

View file

@ -16,8 +16,7 @@ class AuthConfig {
this.config = JSON.parse(configData);
} catch (error) {
console.error("Erreur lors de la lecture du fichier de configuration. Ne pas se fier si vous n'avez pas mit de fichier de configuration.");
this.config = {};
throw error;
this.config = {}
}
return this.config
}

View file

@ -20,7 +20,7 @@ class authController {
}
}
async getRoomsRequireAuth(req, res) {
async getRoomsRequireAuth(req, res, next) {
const authC = new AuthConfig();
const roomsRequireAuth = authC.getRoomsRequireAuth();

View file

@ -19,7 +19,7 @@ class AuthUserAssociation {
const collection = conn.collection('authUserAssociation');
const provider_id = await authProvider.getId(provider_name)
const userAssociation = await collection.findOne({ authProvider_id: provider_id, auth_id: auth_id });
const userAssociation = await collection.findOne({ authProvider_id: provider_id,auth_id,auth_id });
return userAssociation
}

View file

@ -0,0 +1,13 @@
const db = require('../config/db.js')
const { ObjectId } = require('mongodb');
class AuthUserAssoc {
constructor(authProviderId, authId, userId) {
this._id = new ObjectId();
this.authProvider_id = authProviderId;
this.auth_id = authId;
this.user_id = userId;
}
}

View file

@ -1,6 +1,7 @@
const bcrypt = require("bcrypt");
const AppError = require("../middleware/AppError.js");
const { USER_ALREADY_EXISTS } = require("../constants/errorCodes");
const Folders = require("../models/folders.js");
class Users {
@ -66,7 +67,7 @@ class Users {
return user;
}
/*
async login(email, password) {
try {
await this.db.connect();
@ -95,7 +96,7 @@ class Users {
throw error;
}
}
*/
async resetPassword(email) {
const newPassword = this.generatePassword();

View file

@ -1,5 +1,6 @@
const express = require('express');
const router = express.Router();
const jwt = require('../middleware/jwtToken.js');
const authController = require('../controllers/auth.js')