Skip to content

Commit

Permalink
Merge branch 'dev' into S06_US14
Browse files Browse the repository at this point in the history
  • Loading branch information
TristanZvunka authored Jan 24, 2024
2 parents 0895e7e + a512018 commit f5e4376
Show file tree
Hide file tree
Showing 9 changed files with 124 additions and 50 deletions.
25 changes: 13 additions & 12 deletions backend/database/schema.sql
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#Access to DB

USE eating_nam_nam;

#Create tables for eating nam nam DB
Expand Down Expand Up @@ -114,18 +115,18 @@ VALUES

INSERT INTO ingredient (name, unit, kcal)
VALUES
('oeuf', 'pièce(s)', 20),
('beurre', 'grammes', 5),
('chocolat noir', 'grammes', 3),
('farine de blé', 'grammes', 1),
('pâtes', 'grammes', 2),
('nouilles udon', 'grammes',50),
('steak haché', 'pièce(s)',100),
('pain bun','pièce(s)', 40),
('cheddar', 'grammes', 200),
('tomate','pièce(s)',10),
('lait','centilitres',5),
('farine', 'grammes', 0.5)
('oeuf', 'pièce(s)', 20),
('beurre', 'grammes', 5),
('chocolat noir', 'grammes', 3),
('farine de blé', 'grammes', 1),
('pâtes', 'grammes', 2),
('nouilles udon', 'grammes',50),
('steak haché', 'pièce(s)',100),
('pain bun','pièce(s)', 40),
('cheddar', 'grammes', 200),
('tomate','pièce(s)',10),
('lait','centilitres',5),
('farine', 'grammes', 0.5)
;

INSERT INTO instruction (description, recipe_id)
Expand Down
29 changes: 28 additions & 1 deletion backend/src/controllers/authControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const login = async (req, res, next) => {
try {
// Verify if the username exist in the database
const user = await tables.user.readByUsername(req.body.username);
console.info(user);

if (user) {
// Verify if the password match with the hashed in the database
Expand All @@ -50,7 +51,7 @@ const login = async (req, res, next) => {
if (verified) {
// Create a token for open & keep the user session as logged
const token = jwt.sign(
{ username: user.username, is_admin: user.is_admin },
{ id: user.id, username: user.username, is_admin: user.is_admin },
process.env.APP_SECRET,
{ expiresIn: "1h" }
);
Expand All @@ -72,11 +73,37 @@ const login = async (req, res, next) => {
}
};

const verifyToken = async (req, res, next) => {
try {
const { token } = req.cookies;

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);
if (user)
res.status(200).json({
success: "User is valid",
is_loggin: true,
is_admin: decoded.is_admin,
});
else
res
.status(401)
.json({ error: "The token is invalid", is_loggin: false });
}
} catch (err) {
next(err);
}
};

module.exports = {
// browse,
readByUsername,
readByEmail,
login,
verifyToken,
// edit,
// add,
// destroy,
Expand Down
12 changes: 5 additions & 7 deletions backend/src/middleware/authMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,18 @@ const verifyToken = async (req, res, next) => {
try {
const { token } = req.cookies;

console.info(req.cookies);

console.info(token);

if (!token) {
res.status(401).json({ error: "No token founded" });
} else {
const decoded = jwt.verify(token, process.env.APP_SECRET);
console.info(decoded);
const user = await tables.user.read(decoded.id);
console.info({ user });
next();
console.info(user);
if (user) next();
else res.status(401).json({ error: "The token is invalid" });
}
} catch (err) {
res.status(401).json({ error: "The token is invalid" });
res.status(401).json({ error: "Internal error" });
}
};

Expand Down
14 changes: 10 additions & 4 deletions backend/src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,22 @@ const AuthControllers = require("./controllers/authControllers");
// Import the middleware for hash password in DB when a new user register
const AuthMiddleware = require("./middleware/authMiddleware");

router.post("/login", AuthControllers.login);
router.post("/users", AuthMiddleware.hashPwd, UserControllers.add);
router.get("/verify-token", AuthControllers.verifyToken);

router.use(AuthMiddleware.verifyToken);

router.get("/users", UserControllers.browse); // Route to get a list of items
router.get("/users/:id", UserControllers.read); // Route to get a specific item by ID

router.post("/users", AuthMiddleware.hashPwd, UserControllers.add);
router.put(
"/users/:id",
uploadUsersAvatars.single("avatar"),
UserControllers.edit
); // Route to update user
);

// Route to update user
router.post(
"/users",
AuthMiddleware.hashPwd,
Expand All @@ -43,7 +50,6 @@ router.post(
// Route to get specific items and block the register if they exists
router.get("/username/:username", AuthControllers.readByUsername);
router.get("/email/:email", AuthControllers.readByEmail);
router.post("/login", AuthControllers.login);

/* ************************************************************************* */
// RECIPE
Expand All @@ -52,7 +58,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(
Expand Down
35 changes: 29 additions & 6 deletions frontend/src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,40 @@ const router = createBrowserRouter([
{
path: "/recipes",
element: <RecipeList />,
loader: () => {
return Promise.all([
axios.get(`${import.meta.env.VITE_BACKEND_URL}/api/recipes`, {
withCredentials: true,
}),
axios.get(`${import.meta.env.VITE_BACKEND_URL}/api/tags`, {
withCredentials: true,
}),
])
.then(([recipeResponse, tagsResponse]) => {
const recipe = recipeResponse.data; // Accédez aux données de la réponse
const tags = tagsResponse.data; // Accédez aux données de la réponse
return Promise.all([{ recipe }, { tags }]);
})
.catch(() => {
// Gérez l'erreur ici (redirection vers "/connexion" par exemple)
window.location.href = "/connexion";
});
},
},
{
path: "/recipes/:id",
element: <RecipeDetails />,
loader: ({ params }) => {
return axios.get(
`${import.meta.env.VITE_BACKEND_URL}/api/recipes/${params.id}`,
{
withCredentials: true,
}
);
return axios
.get(
`${import.meta.env.VITE_BACKEND_URL}/api/recipes/${params.id}`,
{
withCredentials: true,
}
)
.catch(() => {
window.location.href = "/connexion";
});
},
},
{
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/pages/Connexion.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useState } from "react";
import PropTypes from "prop-types";
import { ToastContainer, toast } from "react-toastify";
import axios from "axios";

import {
isValidUsername,
isValidEmail,
Expand All @@ -13,6 +14,7 @@ import {
resetErrMsgPassConfSign,
resetAllErrMsgSign,
} from "./services/postUserValid";

import "react-toastify/dist/ReactToastify.css";
import "./style/Connexion.scss";

Expand Down
22 changes: 14 additions & 8 deletions frontend/src/pages/Recipe.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,20 @@ function Recipe({ name, title, difficulty, id, image, tag1, tag2, tag3 }) {
<div className="desc-recipe">
<h2>{name}</h2>
<p>{title}</p>
<p className="level-recipe">{difficulty}</p>
<p>{tag1}</p>
<p>{tag2}</p>
<p>{tag3}</p>
<div className="link-to">
<Link to={`/recipes/${id}`}>
<p>En savoir plus</p>
</Link>
<div className="recipe-difficult">
<p className="level-recipe">{difficulty}</p>
<div className="recipe-bottom">
<div className="recip-tags">
<p>{tag1}</p>
<p>{tag2}</p>
<p>{tag3}</p>
</div>
<div className="link-to">
<Link to={`/recipes/${id}`}>
<p>En savoir plus</p>
</Link>
</div>
</div>
</div>
</div>
</>
Expand Down
13 changes: 8 additions & 5 deletions frontend/src/pages/RecipeList.jsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import axios from "axios";
import { useState, useEffect } from "react";
import { useState } from "react";
import { useLoaderData } from "react-router-dom";
import Recipe from "./Recipe";
import "./style/RecipeList.scss";

function RecipeList() {
const [allRecipe, setAllRecipe] = useState([]);
const [filters, setFilters] = useState([]);
const allRecipe = useLoaderData()[0].recipe;
const filters = useLoaderData()[1].tags;
const [filtersRecipe, setFiltersRecipe] = useState("");

/*
useEffect(() => {
const endpoints = [
"http://localhost:3310/api/recipes",
Expand All @@ -26,10 +27,12 @@ function RecipeList() {
console.info(recipe, tag);
})
.catch(() => {
window.location.href = "/";
window.location.href = "/connexion";
});
}, []);
*/

return (
<div className="body-content recipe-content">
<div className="filter">
Expand Down
22 changes: 15 additions & 7 deletions frontend/src/pages/style/RecipeList.scss
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@
list-style: none;
background-color: $white-color;
border-radius: 1.5rem;
height: 200px;
min-width: 300px;
max-width: 400px;
min-height: 200px;
min-width: 380px;
max-width: 420px;
box-shadow: 0px 15px 20px rgba(0, 0, 0, 0.1);

display: flex;
Expand All @@ -53,10 +53,18 @@
}

.desc-recipe {
padding: 0.25rem;
margin: 0.5rem;
width: 55%;
display: flex;
flex-direction: column;
justify-content: space-between;

.recipe-bottom {
display: flex;
justify-content: space-between;
align-items: last baseline;
}

h2 {
font-size: medium;
Expand All @@ -65,20 +73,20 @@
}
p {
font-size: small;
margin: 0.25rem 0.5rem 0.25rem 0;
}

.level-recipe {
margin: auto 0.25rem 0.25rem auto;
text-align: right;
}

.link-to {
display: flex;
margin: 0.25rem 0.25rem 0.25rem auto;
background-color: $orange-color;
padding-left: 0.5rem;
padding: 0.5rem;
margin: 0.25rem;
border-radius: 1rem;
text-align: right;
align-items: center;
&:hover {
background-color: #db9146;
cursor: pointer;
Expand Down

0 comments on commit f5e4376

Please sign in to comment.