From 308fe4b7a5d2ebe8276a6cea0fc377107ff5164f Mon Sep 17 00:00:00 2001 From: Flavien G <44913995+fgaujard@users.noreply.github.com> Date: Tue, 23 Jan 2024 15:56:42 +0100 Subject: [PATCH 1/2] Tokenfix --- backend/src/router.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/src/router.js b/backend/src/router.js index 3cba355..b06c49b 100644 --- a/backend/src/router.js +++ b/backend/src/router.js @@ -54,7 +54,7 @@ router.post("/login", AuthControllers.login); // Import recipeControllers module for handling item-related operations const RecipeControllers = require("./controllers/recipeControllers"); -router.get("/recipes", AuthMiddleware.verifyToken, RecipeControllers.browse); // Route to get a list of items +router.get("/recipes", RecipeControllers.browse); // Route to get a list of items router.get("/recipes/:id", RecipeControllers.read); // Route to get a specific item by ID router.get("/recipebyuser/:id", RecipeControllers.readByUser); router.post( From f8e9b6fa29e80e84e2e3b53d5e46ab847326a9d0 Mon Sep 17 00:00:00 2001 From: Flavien G <44913995+fgaujard@users.noreply.github.com> Date: Tue, 23 Jan 2024 18:36:33 +0100 Subject: [PATCH 2/2] Tokenfix --- backend/src/app.js | 11 ++++++----- backend/src/controllers/authControllers.js | 9 +++++++-- backend/src/controllers/userControllers.js | 1 - backend/src/middleware/authMiddleware.js | 19 +++++++++++-------- backend/src/router.js | 4 +--- frontend/src/main.jsx | 9 ++++++++- frontend/src/pages/Connexion.jsx | 6 +++--- frontend/src/pages/RecipeDetails.jsx | 2 +- frontend/src/pages/RecipeList.jsx | 22 +++++++++++++--------- frontend/src/pages/style/RecipeList.scss | 10 +++++----- 10 files changed, 55 insertions(+), 38 deletions(-) diff --git a/backend/src/app.js b/backend/src/app.js index a236d25..550856d 100644 --- a/backend/src/app.js +++ b/backend/src/app.js @@ -28,13 +28,14 @@ const app = express(); const cors = require("cors"); -app.use(cors()); -/* +// app.use(cors()); + app.use( cors({ origin: [ process.env.FRONTEND_URL, // keep this one, after checking the value in `backend/.env` ], + credentials: true, }) ); @@ -54,9 +55,9 @@ app.use( // Uncomment one or more of these options depending on the format of the data sent by your client: app.use(express.json()); -app.use(express.urlencoded()); -app.use(express.text()); -app.use(express.raw()); +// app.use(express.urlencoded()); +// app.use(express.text()); +// app.use(express.raw()); /* ************************************************************************* */ diff --git a/backend/src/controllers/authControllers.js b/backend/src/controllers/authControllers.js index 42f5c67..3261d57 100644 --- a/backend/src/controllers/authControllers.js +++ b/backend/src/controllers/authControllers.js @@ -51,10 +51,15 @@ const login = async (req, res, next) => { // Create a token for open & keep the user session as logged const token = jwt.sign( { username: user.username, is_admin: user.is_admin }, - process.env.APP_SECRET + process.env.APP_SECRET, + { expiresIn: "1h" } ); // Respond with the Token of the user, in JSON format - res.cookie("token_eating_nam_nam_usr", token).json(token); + res.cookie("token", token, { + httpOnly: true, + maxAge: 3600000, // 1h in ms + }); + res.status(200).send(token); } else { res.sendStatus(422); } diff --git a/backend/src/controllers/userControllers.js b/backend/src/controllers/userControllers.js index e5f874a..1607326 100644 --- a/backend/src/controllers/userControllers.js +++ b/backend/src/controllers/userControllers.js @@ -65,7 +65,6 @@ const edit = async (req, res, next) => { const add = async (req, res, next) => { // Extract the user data from the request body const item = req.body; - console.info(item); const existingUsername = await tables.user.readByUsername(item.username); const existingEmail = await tables.user.readByEmail(item.email); diff --git a/backend/src/middleware/authMiddleware.js b/backend/src/middleware/authMiddleware.js index 64ccb2b..cd05213 100644 --- a/backend/src/middleware/authMiddleware.js +++ b/backend/src/middleware/authMiddleware.js @@ -21,20 +21,23 @@ const hashPwd = async (req, res, next) => { }; const verifyToken = async (req, res, next) => { - const token = req.body.cookies; + try { + const { token } = req.cookies; + + console.info(req.cookies); + + console.info(token); - console.info(token); - if (!token) { - res.status(401).json({ error: "No token founded" }); - } else { - try { + if (!token) { + res.status(401).json({ error: "No token founded" }); + } else { const decoded = jwt.verify(token, process.env.APP_SECRET); const user = await tables.user.read(decoded.id); console.info({ user }); next(); - } catch (err) { - res.status(401).json({ error: "The token is invalid" }); } + } catch (err) { + res.status(401).json({ error: "The token is invalid" }); } }; diff --git a/backend/src/router.js b/backend/src/router.js index b06c49b..1136bb1 100644 --- a/backend/src/router.js +++ b/backend/src/router.js @@ -40,8 +40,6 @@ router.post( UserControllers.add ); -// lala ceci est un test - // Route to get specific items and block the register if they exists router.get("/username/:username", AuthControllers.readByUsername); router.get("/email/:email", AuthControllers.readByEmail); @@ -54,7 +52,7 @@ router.post("/login", AuthControllers.login); // Import recipeControllers module for handling item-related operations const RecipeControllers = require("./controllers/recipeControllers"); -router.get("/recipes", RecipeControllers.browse); // Route to get a list of items +router.get("/recipes", AuthMiddleware.verifyToken, RecipeControllers.browse); // Route to get a list of items router.get("/recipes/:id", RecipeControllers.read); // Route to get a specific item by ID router.get("/recipebyuser/:id", RecipeControllers.readByUser); router.post( diff --git a/frontend/src/main.jsx b/frontend/src/main.jsx index 8c487d7..727576d 100644 --- a/frontend/src/main.jsx +++ b/frontend/src/main.jsx @@ -3,6 +3,8 @@ import ReactDOM from "react-dom/client"; import { createBrowserRouter, RouterProvider } from "react-router-dom"; +import axios from "axios"; + import App from "./App"; import Accueil from "./pages/Accueil"; import Connexion from "./pages/Connexion"; @@ -23,7 +25,12 @@ const router = createBrowserRouter([ path: "/recipes/:id", element: , loader: ({ params }) => { - return fetch(`http://localhost:3310/api/recipes/${params.id}`); + return axios.get( + `${import.meta.env.VITE_BACKEND_URL}/api/recipes/${params.id}`, + { + withCredentials: true, + } + ); }, }, { diff --git a/frontend/src/pages/Connexion.jsx b/frontend/src/pages/Connexion.jsx index d9804e6..204d7a6 100644 --- a/frontend/src/pages/Connexion.jsx +++ b/frontend/src/pages/Connexion.jsx @@ -45,12 +45,13 @@ function TypeOfForm({ checkbox, setCheckbox }) { username, password, }; - console.info(formData); try { // Appel à l'API pour demander une connexion const response = await axios - .post(`${import.meta.env.VITE_BACKEND_URL}/api/login`, formData) + .post(`${import.meta.env.VITE_BACKEND_URL}/api/login`, formData, { + withCredentials: true, + }) .catch((err) => console.error(err)); // Redirection vers la page de connexion si la création réussit @@ -123,7 +124,6 @@ function TypeOfForm({ checkbox, setCheckbox }) { // Redirection sur le login en gardant la valeur de username document.getElementsByTagName("form")[2].email.value = ""; if (!checkbox) setCheckbox(true); - console.info("response =", res); } }) .catch((err) => { diff --git a/frontend/src/pages/RecipeDetails.jsx b/frontend/src/pages/RecipeDetails.jsx index 5c76a64..b2ed88a 100644 --- a/frontend/src/pages/RecipeDetails.jsx +++ b/frontend/src/pages/RecipeDetails.jsx @@ -7,7 +7,7 @@ function RecipeDetails() { return (
- +

retour

diff --git a/frontend/src/pages/RecipeList.jsx b/frontend/src/pages/RecipeList.jsx index df8d1d9..9b1ef4e 100644 --- a/frontend/src/pages/RecipeList.jsx +++ b/frontend/src/pages/RecipeList.jsx @@ -8,22 +8,26 @@ function RecipeList() { const [filters, setFilters] = useState([]); const [filtersRecipe, setFiltersRecipe] = useState(""); - const getData = () => { + useEffect(() => { const endpoints = [ "http://localhost:3310/api/recipes", "http://localhost:3310/api/tags", ]; - Promise.all(endpoints.map((endpoint) => axios.get(endpoint))).then( - ([{ data: recipe }, { data: tag }]) => { + Promise.all( + endpoints.map((endpoint) => + axios.get(endpoint, { + withCredentials: true, + }) + ) + ) + .then(([{ data: recipe }, { data: tag }]) => { setAllRecipe(recipe); setFilters(tag); console.info(recipe, tag); - } - ); - }; - - useEffect(() => { - getData(); + }) + .catch(() => { + window.location.href = "/"; + }); }, []); return ( diff --git a/frontend/src/pages/style/RecipeList.scss b/frontend/src/pages/style/RecipeList.scss index 4b515c5..98f835a 100644 --- a/frontend/src/pages/style/RecipeList.scss +++ b/frontend/src/pages/style/RecipeList.scss @@ -29,9 +29,9 @@ list-style: none; background-color: $white-color; border-radius: 1.5rem; - height: 150px; + height: 200px; min-width: 300px; - max-width: 350px; + max-width: 400px; box-shadow: 0px 15px 20px rgba(0, 0, 0, 0.1); display: flex; @@ -42,11 +42,11 @@ .image-recipe-pos { width: 45%; - height: 150px; - max-width: 150px; + height: 200px; + max-width: 200px; } .image-recipe { - height: 150px; + height: 200px; width: 100%; object-fit: cover; border-radius: 1.5rem 0 0 1.5rem;