Skip to content

Commit

Permalink
authmiddleware, adminMiddleware, getCv
Browse files Browse the repository at this point in the history
  • Loading branch information
FredD27 committed Jan 10, 2024
1 parent 41d3fe5 commit 53d0c36
Show file tree
Hide file tree
Showing 9 changed files with 114 additions and 94 deletions.
37 changes: 22 additions & 15 deletions backend/src/controllers/cvControllers.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,28 @@
const models = require("../models/index");

const getCv = (req, res) => {
const userId = parseInt(req.params.userId, 10);

models.cv
.findCvByUserId(userId)
.then(([item]) => {
if (item[0] != null) {
res.json(item[0]);
} else {
res.sendStatus(404);
const getCv = async (req, res) => {
const userId = parseInt(req.params.id, 10);
if (userId !== req.user.id) {
return res.status(403).send({ message: "Invalid user" });
}
try {
const [item] = await models.cv.findCvByUserId(userId);
let cv = item[0] ?? null;
if (cv === null) {
const result = await models.cv.create(userId);
if (result.affectedRows !== 1) {
return res
.status(422)
.send({ message: "Une erreur inconnue est survenue" });
}
})
.catch((err) => {
console.error(err);
res.sendStatus(422);
});
const [newCv] = await models.cv.findCvByUserId(userId);
[cv] = newCv;
}
return res.json(cv);
} catch (err) {
console.error(err);
return res.sendStatus(422);
}
};

const postCv = (req, res) => {
Expand Down
6 changes: 0 additions & 6 deletions backend/src/controllers/userControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,6 @@ const postUser = (req, res) => {
models.user
.create(req.body)
.then((rows) => {
const token = generateAccessToken({
id: rows.insertId,
email: req.body.email,
is_admin: req.body.is_admin,
});
res.send({
id: rows.insertId,
firstname: req.body.firstname,
Expand All @@ -35,7 +30,6 @@ const postUser = (req, res) => {
competence: req.body.competence,
email: req.body.email,
is_admin: req.body.is_admin,
token,
});
})
.catch((err) => {
Expand Down
66 changes: 50 additions & 16 deletions backend/src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,69 @@ const experienceControllers = require("./controllers/experienceControllers");
const courseControllers = require("./controllers/courseControllers");
const cvControllers = require("./controllers/cvControllers");
const {
authMiddleware,
authAdminMiddleware,
} = require("./middlewares/security/auth.middlewares");

router.get("/users", userControllers.getUsers);
router.post("/users", userControllers.postUser);

router.get("/users/:id/cvs", authMiddleware, cvControllers.getCv);
router.get("/users/me", authMiddleware, userControllers.getProfile);
router.post("/login", userControllers.postLogin);

router.get("/offer", offerControllers.getOffers);
router.get("/offer/:id", offerControllers.getOfferById);
router.post("/offer", offerControllers.postOffer);
router.delete("/offer/:id", offerControllers.deleteOfferById);
router.post(
"/offer",
authMiddleware,
authAdminMiddleware,
offerControllers.postOffer
);
router.delete(
"/offer/:id",
authMiddleware,
authAdminMiddleware,
offerControllers.deleteOfferById
);

router.get("/experiences", experienceControllers.getExperiences);
router.get("/experience/:id", experienceControllers.getExperienceById);
router.post("/experience", experienceControllers.postExperience);
router.put("/experience/:id", experienceControllers.updateExperience);
router.delete("/experience/:id", experienceControllers.deleteExperienceById);
router.get(
"/experiences",
authMiddleware,
experienceControllers.getExperiences
);
router.get(
"/experience/:id",
authMiddleware,
experienceControllers.getExperienceById
);
router.post(
"/experience",
authMiddleware,
experienceControllers.postExperience
);
router.put(
"/experience/:id",
authMiddleware,
experienceControllers.updateExperience
);
router.delete(
"/experience/:id",
authMiddleware,
experienceControllers.deleteExperienceById
);

router.get("/course", courseControllers.getCourse);
router.get("/course/:id", courseControllers.getCourseById);
router.post("/course", courseControllers.postCourse);
router.put("/course/:id", courseControllers.updateCourse);
router.delete("/course/:id", courseControllers.deleteCourseById);
router.get("/course", authMiddleware, courseControllers.getCourse);
router.get("/course/:id", authMiddleware, courseControllers.getCourseById);
router.post("/course", authMiddleware, courseControllers.postCourse);
router.put("/course/:id", authMiddleware, courseControllers.updateCourse);
router.delete(
"/course/:id",
authMiddleware,
courseControllers.deleteCourseById
);

router.get("/cvs/:userId", cvControllers.getCv);
router.post("/cvs", cvControllers.postCv);
router.post("/cvs", authMiddleware, authAdminMiddleware, cvControllers.postCv);

router.get("users/me", authAdminMiddleware, userControllers.getProfile);
// router.post("/signin", userControllers.postUser);
// router.update("/signin", userControllers.putUser);
module.exports = router;
3 changes: 1 addition & 2 deletions frontend/src/contexts/AdminContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ const AdminContext = createContext();

function AdminContextProvider({ children }) {
const { setErrorMsg, setSuccesMsg, setMsgContent } = useGlobalContext();

const [isAdmin, setIsAdmin] = useState(true);
const { isAdmin, setIsAdmin } = useGlobalContext();

const [addOffer, setAddOffer] = useState({
id: uuid(),
Expand Down
23 changes: 19 additions & 4 deletions frontend/src/contexts/GlobalContext.jsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import { useState, createContext, useContext, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useLoaderData, useNavigate } from "react-router-dom";
import PropTypes from "prop-types";
import ApiService from "../services/api.service";

const GlobalContext = createContext();

function GlobalContextProvider({ children }) {
function GlobalContextProvider({ children, apiService }) {
// Messages d'alertes.
const givenData = useLoaderData();
const [isAdmin, setIsAdmin] = useState(givenData?.preloadUser?.data?.isAdmin);
const [user, setUser] = useState(givenData?.preloadUser?.data);
const [errorMsg, setErrorMsg] = useState(false);
const [succesMsg, setSuccesMsg] = useState(false);
const [msgContent, setMsgContent] = useState("");

const navigate = useNavigate();

const getItemInLS = (key) => {
return JSON.parse(localStorage.getItem(key));
};
Expand All @@ -32,8 +38,6 @@ function GlobalContextProvider({ children }) {
}));
};

const navigate = useNavigate();

const emailRegex = /[a-z0-9._]+@[a-z0-9-]+\.[a-z]{2,3}/;
const passwordRegex =
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
Expand All @@ -53,6 +57,11 @@ function GlobalContextProvider({ children }) {
navigate,
emailRegex,
passwordRegex,
isAdmin,
setIsAdmin,
user,
setUser,
apiService,
}),
[
getItemInLS,
Expand All @@ -68,6 +77,11 @@ function GlobalContextProvider({ children }) {
navigate,
emailRegex,
passwordRegex,
isAdmin,
setIsAdmin,
user,
setUser,
apiService,
]
);

Expand All @@ -78,6 +92,7 @@ function GlobalContextProvider({ children }) {

GlobalContextProvider.propTypes = {
children: PropTypes.element.isRequired,
apiService: PropTypes.instanceOf(ApiService).isRequired,
};

export default GlobalContextProvider;
Expand Down
38 changes: 18 additions & 20 deletions frontend/src/contexts/LogContext.jsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import { useState, createContext, useContext, useMemo } from "react";
import PropTypes from "prop-types";
import axios from "axios";
import { jwtDecode } from "jwt-decode";
import { useGlobalContext } from "./GlobalContext";

const LogContext = createContext();

function LogContextProvider({ children }) {
// Messages d'alertes.
const { setErrorMsg, setSuccesMsg, setMsgContent, navigate } =
useGlobalContext();
const {
apiService,
setUser,
// setErrorMsg,
// setSuccesMsg,
// setMsgContent,
navigate,
} = useGlobalContext();

const [userConnected, setUserConnected] = useState(false);
const [logIn, setLogIn] = useState({
Expand All @@ -21,33 +25,27 @@ function LogContextProvider({ children }) {
const getUserFromStorage = () => {
setShowStorage(JSON.parse(localStorage.getItem("User")));
};

const handleSubmitLogIn = async () => {
try {
const { data } = await axios.post(
const data = await apiService.post(
`http://localhost:3310/api/login`,
logIn
);
localStorage.setItem("token", data.token);
const tokenData = jwtDecode(data.token);
setSuccesMsg(true);
setMsgContent(`Bienvenue, connexion avec ${tokenData.firstname}`);
setTimeout(() => {
setSuccesMsg(false);
navigate("/");
}, 3000);
setLogIn(tokenData);
if (tokenData.is_admin === 1) {

apiService.setToken(data.token);

const result = await apiService.get("http://localhost:3310/api/users/me");

alert(`Content de vous revoir ${result.data.email}`);
setUser(result.data);
if (result.data.isAdmin === 1) {
return navigate("/dashboard");
}
return navigate("/");
} catch (err) {
console.error(err);
setErrorMsg(true);
setMsgContent("Identifiants non valides.");
setTimeout(() => {
setErrorMsg(false);
}, 4000);
alert(err.message);
}

return null;
Expand Down
29 changes: 1 addition & 28 deletions frontend/src/contexts/UserContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,6 @@ function UserContextProvider({ children }) {

// const [profileSaved, setProfileSaved] = useState([]);

const [addXp, setAddXp] = useState({
id: uuid(),
title: "",
company: "",
city: "",
type: "",
isWorking: false,
dateBegin: "",
dateEnd: "",
description: "",
});
const [xpSaved, setXpSaved] = useState([]);

// const handleSubmitProfile = () => {
// const updatedProfile = {
// ...editProfile,
Expand Down Expand Up @@ -95,25 +82,11 @@ function UserContextProvider({ children }) {
() => ({
editProfile,
setEditProfile,
addXp,
setAddXp,
xpSaved,
setXpSaved,
addCv,
setAddCv,
handleAddCv,
}),
[
editProfile,
setEditProfile,
addXp,
setAddXp,
xpSaved,
setXpSaved,
addCv,
setAddCv,
handleAddCv,
]
[editProfile, setEditProfile, addCv, setAddCv, handleAddCv]
);

return (
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import SignContextProvider from "./contexts/SignContext";
import LogContextProvider from "./contexts/LogContext";
import GlobalContextProvider from "./contexts/GlobalContext";
import UserContextProvider from "./contexts/UserContext";
import ApiService from "../../backend/src/services/api.service";
import ApiService from "./services/api.service";

const apiService = new ApiService();

Expand All @@ -33,15 +33,15 @@ const router = createBrowserRouter([
loader: async () => {
try {
const data = await apiService.get("http://localhost:3310/api/users/me");
return data;
return { preloadUser: data ?? null };
} catch (err) {
console.error(err.message);
return null;
}
},

element: (
<GlobalContextProvider>
<GlobalContextProvider apiService={apiService}>
<UserContextProvider>
<App />
</UserContextProvider>
Expand Down
File renamed without changes.

0 comments on commit 53d0c36

Please sign in to comment.