From 810a3a48fc2262a810b2458be95668a22177f9f8 Mon Sep 17 00:00:00 2001
From: Lucas <lucas.villaume8@etu.univ-lorraine.fr>
Date: Sat, 25 Nov 2023 18:08:35 +0100
Subject: [PATCH] =?UTF-8?q?acc=C3=A8s=20aux=20infos=20de=20la=20session?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
app.js | 5 +++--
controller/AuthController.js | 14 ++++++++++++--
views/index.ejs | 9 ++++++---
3 files changed, 21 insertions(+), 7 deletions(-)
diff --git a/app.js b/app.js
index 6322dfd..97bd76f 100644
--- a/app.js
+++ b/app.js
@@ -1,7 +1,7 @@
const path = require('path');
const express = require('express');
const db = require('./db/Database.js');
-const { checkLogin } = require('./controller/AuthController.js');
+const auth = require('./controller/AuthController.js');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
@@ -15,6 +15,7 @@ app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
+app.use(auth.authenticate);
//chemin d'accès
app.get("/", defaut).get("/accueil",defaut);
app.get("/db/:collection", collection).get("/db", dbAdmin);
@@ -39,7 +40,7 @@ async function dbAdmin(req, res){
async function postLogin(req, res){
let { username, password } = req.body;
- let token = await checkLogin(username, password);
+ let token = await auth.checkLogin(username, password);
if (token == -1) {
res.render("login",{username, password, error: "Il semblerait que le nom d'utilisateur ou le mot de passe soit incorrect."});
} else {
diff --git a/controller/AuthController.js b/controller/AuthController.js
index f24efef..06f6ce4 100644
--- a/controller/AuthController.js
+++ b/controller/AuthController.js
@@ -8,7 +8,6 @@ async function checkLogin(username, password) {
if(user.length == 0){
return -1; //pas d'utilitisateur avec ce nom
}
-
let salt = user[0].salt;
password = salt+password;
let hash = createHash("sha256").update(password).digest("hex"); //hash du mot de passe rentré
@@ -22,4 +21,15 @@ async function checkLogin(username, password) {
}
}
-module.exports = {checkLogin};
\ No newline at end of file
+function authenticate(req, res, next) {
+ try {
+ let token = req.cookies.accessToken;
+ let user = jwt.verify(token, process.env.SECRET);
+ res.locals.user = user;
+ next();
+ } catch {
+ next();
+ }
+}
+
+module.exports = {checkLogin, authenticate};
\ No newline at end of file
diff --git a/views/index.ejs b/views/index.ejs
index 2b6d0f9..e8cb08c 100644
--- a/views/index.ejs
+++ b/views/index.ejs
@@ -5,8 +5,11 @@
</head>
<body>
<h1>Requête reçu</h1>
- <p>
- La requête <%= method %> a été reçu à l'adresse <%= url %>
- </p>
+ <p> La requête <%= method %> a été reçu à l'adresse <%= url %> </p>
+ <% if (locals.user) {%>
+ <p>Bonjour <%= locals.user.username %></p>
+ <% } else { %>
+ <p>Vous n'êtes pas connecté</p>
+ <% } %>
</body>
</html>
\ No newline at end of file
--
GitLab