Skip to content

Commit

Permalink
Merge branch 'Langres-App:main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
kiloutyg authored Mar 21, 2024
2 parents 60e6441 + 9231cfb commit 0f8d07e
Show file tree
Hide file tree
Showing 15 changed files with 79 additions and 36 deletions.
1 change: 0 additions & 1 deletion API/controllers/AuthController.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
*/

const express = require('express');
const { login } = require('../data/queries/AuthorizedUserQueries');
const { handle } = require('./functionHandler');
const AuthManager = require('../model/Managers/AuthManager');
const router = express.Router();
Expand Down
6 changes: 5 additions & 1 deletion API/data/queries/DocumentsQueries.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,12 +181,16 @@ async function rename(id, title) {
assert(id, '[DocumentsQueries.rename] The document ID is required');
assert(title, '[DocumentsQueries.rename] The file name is required');

// get the old name for to change the folder and files names
const old = await getById(id);
const oldTitle = old.name;

// Update the document name
const documentQuery = 'UPDATE document SET file_name = ? WHERE id = ?';
await query(documentQuery, [title, id]);

// Update the version file paths
await versionQueries.updatePathes(id, title);
await versionQueries.updatePathes(id, oldTitle, title);
});

}
Expand Down
9 changes: 6 additions & 3 deletions API/data/queries/VersionQueries.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,16 +121,19 @@ async function getPdfPath(id, date) {
* @param {string} newName - The new name to replace in the file paths.
* @returns {Promise} A promise that resolves with the result of the update operation.
*/
async function updatePathes(docId, newName) {
async function updatePathes(docId, oldTitle, newName) {

// Check if the required fields are present
assert(docId, '[VersionQueries.updatePathes] The document ID is required');
assert(newName, '[VersionQueries.updatePathes] The new name is required');

return await executeWithCleanup(async (query) => {

console.log('oldTitle: ', oldTitle);
console.log('newName: ', newName);

let queryStr = 'UPDATE version SET file_path = REPLACE(file_path, ?, ?) WHERE doc_id = ?';
return await query(queryStr, [newName, docId, newName]);
return await query(queryStr, [oldTitle, newName, docId]);

});

Expand Down
15 changes: 10 additions & 5 deletions API/model/Managers/AuthManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,19 @@ async function register(data) {
data.username = data.username.trim();
data.password = data.password.trim();

await queries.createUser(data);

// Check if the user exists, if not throw an error with 'Bad credentials' so that no information is leaked
assert(await userExist(), 'Bad credentials');
try {
await userExist();
} catch (e) {
if (e.message.includes('not found')) {
await queries.createUser(data);
}
}

return await login(data);

// Check if the user exists, if not throw an error
assert(await userExist(), 'Oops, something went wrong. Please try again.');

return login(data);

}

Expand Down
2 changes: 1 addition & 1 deletion API/model/Managers/DocumentManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ async function updateTitle(id, title) {
id = parseInt(id);
assert(Number(id), '[DocumentManager.updateTitle] Document ID must be a number');

changeFolderAndFilesNames(path.join(__dirname, '../Docs', oldName), title);
changeFolderAndFilesNames(path.join(__dirname, '../../Docs', oldName), title);
await queries.rename(id, title);

}
Expand Down
8 changes: 6 additions & 2 deletions FRONT/js/data/dao/AuthDao.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ class AuthDao extends Dao {
*/
async login(user) {
let resp = await this.post('/login', user);
return await resp.text();
if (resp.status === 200) {
return await resp.text();
}
}

/**
Expand All @@ -44,7 +46,9 @@ class AuthDao extends Dao {
*/
async register(user) {
let resp = await this.post('/register', user);
return await resp.json();
if (resp.status === 201) {
return await resp.text();
}
}

/**
Expand Down
4 changes: 4 additions & 0 deletions FRONT/js/model/Canvas.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,10 @@ class Canvas {
return this.#canvas.toDataURL("image/png");
}

/**
* Exports the canvas as a Blob object.
* @returns {Promise<Blob>} A promise that resolves with the Blob object representing the canvas.
*/
exportToBlob() {
return new Promise((resolve) => {
this.#canvas.toBlob((blob) => {
Expand Down
14 changes: 14 additions & 0 deletions FRONT/js/model/Instantiator.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,10 @@ class Instantiator {
return new DocumentManager();
}

/**
* Retrieves the user manager instance.
* @returns {UserManager} The user manager instance.
*/
static async getUserManager() {
await Promise.all([
this.#loadSequentially([this.#pathes.data.access.Dao, this.#pathes.data.access.UserDao]),
Expand Down Expand Up @@ -220,6 +224,11 @@ class Instantiator {

}

/**
* Creates an instance of the MainUserDocSignedTemplateManager class.
* @param {Container} container - The container object.
* @returns {MainUserDocSignedTemplateManager} The MainUserDocSignedTemplateManager instance.
*/
static async mainUserDocSignedTemplateManager(container) {
await this.#loadSequentially([
this.#pathes.template.manager,
Expand All @@ -229,6 +238,11 @@ class Instantiator {
return new MainUserDocSignedTemplateManager(container);
}

/**
* Creates a new instance of the MainUserDocWaitingTemplateManager class.
* @param {Container} container - The container object.
* @returns {MainUserDocWaitingTemplateManager} The new instance of MainUserDocWaitingTemplateManager.
*/
static async mainUserDocWaitingTemplateManager(container) {
await this.#loadSequentially([
this.#pathes.template.manager,
Expand Down
4 changes: 3 additions & 1 deletion FRONT/js/model/auth/AuthManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class AuthManager {
response = await this.dao.checkForExistingUser();
toReturn.userExists = response.status === 200;

if (toReturn) {
if (toReturn.userExists) {
let responseBody = await response.json();
if (responseBody.logged) {
document.dispatchEvent(new Event('USER_LOGGED_IN'));
Expand Down Expand Up @@ -68,6 +68,7 @@ class AuthManager {
*/
async login(user) {
let response = await this.dao.login(user);
if (!response) throw new Error('Login failed');
this.#setToken(response);
}

Expand All @@ -78,6 +79,7 @@ class AuthManager {
*/
async register(user) {
let response = await this.dao.register(user);
if (!response) throw new Error('Login failed');
this.#setToken(response);
}

Expand Down
14 changes: 10 additions & 4 deletions FRONT/js/model/data/DocumentManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ class DocumentManager extends DataManager {
}
}


let toReturn = [];
let data;

Expand Down Expand Up @@ -146,8 +146,10 @@ class DocumentManager extends DataManager {
console.log(e);
}

// depending on what appened we either reload the page or return a message
if (data) { } // TODO: message popup that reload the view
if (data) {
window.location.reload();
}

}

/**
Expand All @@ -166,7 +168,9 @@ class DocumentManager extends DataManager {
}

// depending on the api call, either tell the element was added, or return an error message
if (data) { } // TODO: message popup that reload the view / error message
if (data) {
window.location.reload();
}
}


Expand All @@ -178,6 +182,8 @@ class DocumentManager extends DataManager {
let data;
try {
data = await super.update(object);
alert('Document renommé avec succès !');
window.location.reload();
} catch (e) {
console.log(e);
}
Expand Down
19 changes: 6 additions & 13 deletions FRONT/js/model/popups/DocumentClickedPopup.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,24 +102,20 @@ class DocumentClickedPopup extends Popup {
admin_only: true,
action: async (dataMap, docId) => {
const documentManager = dataMap['manager'];
const popupManager = dataMap['popupManager'];

super.close();

let messageContent;
try {
// archive the document
await documentManager.archive(docId);
messageContent = `Le document ${this.document.getFileName()} a été archivé avec succès.
Vous pouvez le retrouver dans la liste des documents archivés. (connexion requise)`;
messageContent = `Le document ${this.document.getFileName()} a été archivé avec succès.\nsVous pouvez le retrouver dans la liste des documents archivés. (connexion requise)`;
} catch (e) {
console.log(e);
messageContent = `Une erreur est survenue lors de l'archivage du document ${this.document.getFileName()}. Veuillez réessayer.`;
} finally {
popupManager.open('message-popup', {
title: 'Archivage du document',
message: messageContent
});
alert(messageContent);
window.location.reload();
}
},
archive_button: false
Expand All @@ -138,16 +134,13 @@ class DocumentClickedPopup extends Popup {
try {
// archive the document
await documentManager.unarchive(docId);
messageContent = `Le document ${this.document.getFileName()} a été désarchivé avec succès.
Vous pouvez le retrouver dans la liste des documents non archivés.`;
messageContent = `Le document ${this.document.getFileName()} a été désarchivé avec succès.\nVous pouvez le retrouver dans la liste des documents non archivés.`;
} catch (e) {
console.log(e);
messageContent = `Une erreur est survenue lors du désarchivage du document ${this.document.getFileName()}. Veuillez réessayer.`;
} finally {
popupManager.open('message-popup', {
title: 'Désarchivage du document',
message: messageContent
});
alert(messageContent);
window.location.reload();
}
},
archive_button: true
Expand Down
4 changes: 2 additions & 2 deletions FRONT/js/model/template/MainUserTemplateManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ class MainUserTemplateManager extends TemplateManager {
// values is a map that contains the values to be replaced in the template,
// the key is the name of the variable in the template and the value is the value to replace
let values = [];

values['id'] = user.id;

if (!user.archived_date) {
const signedCount = user.docs_signatures.length;
const outdatedCount = user.docs_signatures.filter(doc => doc.toUpdate === true).length;
const waitingCount = user.docs_waiting.length;

values['DisplayName'] = user.display_name;
values['DisplayName'] = user.display_name;
values['Signed'] = signedCount < 10 ? '0' + signedCount : signedCount;
values['Outdated'] = outdatedCount < 10 ? '0' + outdatedCount : outdatedCount;
values['Waiting'] = waitingCount < 10 ? '0' + waitingCount : waitingCount;
Expand Down
6 changes: 4 additions & 2 deletions FRONT/js/view/HeaderManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@ class HeaderManager {
// add the event listener to log out
accountButton.addEventListener('click', (e) => {
e.preventDefault();
document.dispatchEvent(new CustomEvent('USER_NOT_LOGGED_IN', { detail: { userExist: true } }));


// remove the user from the local storage
window.localStorage.removeItem('userToken');

document.dispatchEvent(new CustomEvent('USER_LOGGED_OUT', { detail: { userExist: true } }));

});
});

Expand Down
7 changes: 7 additions & 0 deletions FRONT/js/view/signedList.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,20 @@ class SignedListView extends View {
async #init(authManager) {
this.#setPageTitle();
await this.initTemplateManager();
this.isLogged = false;

// Wait for auth Check
document.addEventListener('USER_LOGGED_IN', () => {
this.#displayUsers().then(() => {
this.isLogged = true;
this.addButtons();
this.#manageSearch();
});
});

// if the user is not logged in, we redirect to the index page
document.addEventListener('USER_NOT_LOGGED_IN', () => {
this.isLogged = false;
this.#displayUsers().then(() => {
this.removeButtons();
this.#manageSearch();
Expand Down Expand Up @@ -172,5 +175,9 @@ class SignedListView extends View {
let userList = users.filter(user => user.getDisplayName().toLowerCase().includes(searchValue.toLowerCase()));
await this.templateManager.addSignedUsers(userList);

if (!this.isLogged) {
this.removeButtons();
}

}
}
2 changes: 1 addition & 1 deletion FRONT/visual/pages/login.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ <h2 class="smallcaps">Connexion</h2>
<form action="#">
<div class="field">
<label for="user-identifier" class="lightText">Identifiant :</label>
<input type="text" placeholder="Identifiant " name="identifier" id="user-identifier" required>
<input type="text" placeholder="prénom.nom" name="identifier" id="user-identifier" required>
</div>
<div class="field">
<label for="user-password" class="lightText">Mot de passe :</label>
Expand Down

0 comments on commit 0f8d07e

Please sign in to comment.