Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Routes test #69

Merged
merged 6 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion backend/database/database.sql
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ CREATE TABLE
phone VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
address VARCHAR(155) NOT NULL,
competence VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
is_admin BOOL NOT NULL,
UNIQUE (email)
Expand Down
6 changes: 5 additions & 1 deletion backend/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ const app = express();

const cors = require("cors");

app.use(cors());
app.use(
cors({
origin: process.env.FRONTEND_URL,
})
);
/*
app.use(
cors({
Expand Down
28 changes: 25 additions & 3 deletions backend/src/controllers/userControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,35 @@ const postLogin = (req, res) => {
});
};

// const putUser = (req, res) => {
// models.user.sigin(req.body).then((user) => {});
// };
const updateUser = async (req, res) => {
const id = parseInt(req.params.id, 10);
if (!id) {
res.sendStatus(500);
}

models.experience
.update(id, req.body)
.then((result) => {
if (result.affectedRows === 0) {
res.sendStatus(500);
}
res.sendStatus(200);
})
.catch((error) => {
console.error(error);
res.status(422).send({ error: error.message });
});
};

const getProfile = (req, res) => {
res.send(req.user);
};

module.exports = {
getUsers,
postUser,
postSkills,
postLogin,
updateUser,
getProfile,
};
37 changes: 37 additions & 0 deletions backend/src/middlewares/security/auth.middlewares.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const jwt = require("jsonwebtoken");
const model = require("../../models");

const authMiddleware = (req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: "User not authorized" });
}

return jwt.verify(
req.headers.authorization.split(" ")[1],
process.env.APP_SECRET,
(err, data) => {
if (err) {
return res.status(401).json({ error: err.message });
} // Step 3: get user data from token payload
model.user.getProfile(data.id).then(([rows]) => {
if (!rows.length) {
return res.status(401).json({ error: "Utilisateur inexistant" });
} // Step 4: share user data between different middlewares// eslint-disable-next-line prefer-destructuring
// eslint-disable-next-line prefer-destructuring
req.user = rows[0];
return next();
});
return null;
}
);
};

const authAdminMiddleware = (req, res, next) => {
if (req?.user?.isAdmin !== 1) {
return res.status(403).json({ error: "Vous n'êtes pas Admin" });
}

return next();
};

module.exports = { authMiddleware, authAdminMiddleware };
9 changes: 8 additions & 1 deletion backend/src/models/UserManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class UserManager extends AbstractManager {
user.address,
user.email,
hash,
user.is_admin,
0,
]
);
return rows;
Expand Down Expand Up @@ -59,6 +59,13 @@ class UserManager extends AbstractManager {
return result ? dbUser : undefined;
}

getProfile(id) {
return this.database.query(
`SELECT id, email, is_admin AS isAdmin FROM ${this.table} WHERE id = ?`,
[id]
);
}

static hashPassword(password, workFactor = 5) {
return bcrypt.hash(password, workFactor);
}
Expand Down
5 changes: 5 additions & 0 deletions backend/src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ const offerControllers = require("./controllers/offerControllers");
const experienceControllers = require("./controllers/experienceControllers");
const courseControllers = require("./controllers/courseControllers");
const cvControllers = require("./controllers/cvControllers");
const {
authAdminMiddleware,
} = require("./middlewares/security/auth.middlewares");

router.get("/users", userControllers.getUsers);
router.post("/users", userControllers.postUser);
Expand All @@ -32,6 +35,8 @@ router.delete("/course/:id", courseControllers.deleteCourseById);

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

router.get("users/me", authAdminMiddleware, userControllers.getProfile);
// router.post("/signin", userControllers.postUser);
// router.update("/signin", userControllers.putUser);
module.exports = router;
38 changes: 38 additions & 0 deletions backend/src/services/api.service.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import axios from "axios";

export default class ApiService {
#token;

constructor() {
this.#token = localStorage.getItem("token");
}

getToken() {
return this.#token;
}

setToken(token) {
this.#token = token;

return this;
}

getConfig() {
const config = { headers: {} };

if (this.#token) {
config.headers.Authorization = `bearer ${this.#token}`;
}

return config;
}

get(url) {
return axios.get(url, this.getConfig());
}

async post(url, content) {
const { data } = await axios.post(url, content, this.getConfig());
return data;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import "../../default-settings.css";
function CompetenceSwitch({
textCompetence,
fieldName,
valueInput,
handleChange,
valueInput,
}) {
return (
<div className="competence-line">
Expand All @@ -32,8 +32,8 @@ function CompetenceSwitch({
CompetenceSwitch.propTypes = {
textCompetence: PropTypes.string.isRequired,
fieldName: PropTypes.string.isRequired,
valueInput: PropTypes.string.isRequired,
handleChange: PropTypes.func.isRequired,
valueInput: PropTypes.func.isRequired,
};

export default CompetenceSwitch;
25 changes: 25 additions & 0 deletions frontend/src/main.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from "react";
import ReactDOM from "react-dom";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import axios from "axios";
import App from "./App";
import Home from "./pages/HomeOffer/Home";
import ReadOffer from "./pages/Offer/ReadOffer";
Expand All @@ -22,10 +23,23 @@ 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";

const apiService = new ApiService();

const router = createBrowserRouter([
{
path: "/",
loader: async () => {
try {
const data = await apiService.get("http://localhost:3310/api/users/me");
return data;
} catch (err) {
console.error(err.message);
return null;
}
},

element: (
<GlobalContextProvider>
<UserContextProvider>
Expand Down Expand Up @@ -73,6 +87,17 @@ const router = createBrowserRouter([
{
path: "/edit-profile/cv",
element: <CreateCV />,
loader: async () => {
try {
const data = await axios.get(
"http://localhost:3310/api/cvs/userId"
);
return data;
} catch (err) {
console.error(err.message);
return null;
}
},
},
{
path: "/edit-profile/experience",
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/Connexion/SignIn.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ function SignIn() {
setSuccesMsg(false);
}, 2000);

axios.post("http://localhost:3010/api/user/", signIn);
axios.post("http://localhost:3310/api/users", signIn);

setSignIn({
email: "",
Expand Down