Skip to content

Commit

Permalink
added login
Browse files Browse the repository at this point in the history
  • Loading branch information
rocambille committed Jan 4, 2024
1 parent 9c44c9f commit 87e6745
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 9 deletions.
23 changes: 23 additions & 0 deletions backend/src/controllers/authControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Import access to database tables
const tables = require("../tables");

const login = async (req, res, next) => {
try {
// Fetch all users from the database
const user = await tables.user.readByEmail(req.body.email);

if (user == null || user.password !== req.body.password) {
res.sendStatus(422);
} else {
// Respond with the users in JSON format
res.json(user);
}
} catch (err) {
// Pass any errors to the error-handling middleware
next(err);
}
};

module.exports = {
login,
};
11 changes: 11 additions & 0 deletions backend/src/models/UserManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,17 @@ class UserManager extends AbstractManager {
return rows;
}

async readByEmail(email) {
// Execute the SQL SELECT query to retrieve a specific user by its email
const [rows] = await this.database.query(
`select * from ${this.table} where email = ?`,
[email]
);

// Return the first row of the result, which represents the user
return rows[0];
}

// The U of CRUD - Update operation
// TODO: Implement the update operation to modify an existing user

Expand Down
15 changes: 10 additions & 5 deletions backend/src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,24 @@ const router = express.Router();
// Define Your API Routes Here
/* ************************************************************************* */

// Import itemControllers module for handling item-related operations
const itemControllers = require("./controllers/itemControllers");

router.get("/items", itemControllers.browse);
router.get("/items/:id", itemControllers.read);
router.post("/items", itemControllers.add);

// Import userControllers module for handling user-related operations
const userControllers = require("./controllers/userControllers");

router.get("/users", userControllers.browse);
router.get("/users/:id", userControllers.read);
router.post("/users", userControllers.add);

// Import itemControllers module for handling item-related operations
const itemControllers = require("./controllers/itemControllers");
// Import authControllers module for handling auth-related operations
const authControllers = require("./controllers/authControllers");

router.get("/items", itemControllers.browse);
router.get("/items/:id", itemControllers.read);
router.post("/items", itemControllers.add);
router.post("/login", authControllers.login);

/* ************************************************************************* */

Expand Down
29 changes: 25 additions & 4 deletions frontend/src/App.jsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,43 @@
import { Link, Outlet } from "react-router-dom";

import "./App.css";
import { useState } from "react";

function App() {
const [user, setUser] = useState();

return (
<>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/register">Register</Link>
</li>
{user == null ? (
<>
<li>
<Link to="/login">Login</Link>
</li>
<li>
<Link to="/register">Register</Link>
</li>
</>
) : (
<li>
<button
type="button"
onClick={() => {
setUser(null);
}}
>
Logout
</button>
</li>
)}
</ul>
</nav>
<main>
<Outlet />
<Outlet context={{ user, setUser }} />
</main>
</>
);
Expand Down
5 changes: 5 additions & 0 deletions frontend/src/main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { createBrowserRouter, RouterProvider } from "react-router-dom";
import App from "./App";

import Home from "./pages/Home";
import Login from "./pages/Login";
import Register from "./pages/Register";

const router = createBrowserRouter([
Expand All @@ -16,6 +17,10 @@ const router = createBrowserRouter([
path: "/",
element: <Home />,
},
{
path: "/login",
element: <Login />,
},
{
path: "/register",
element: <Register />,
Expand Down
68 changes: 68 additions & 0 deletions frontend/src/pages/Login.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { useRef } from "react";
import { useNavigate, useOutletContext } from "react-router-dom";

function Login() {
// Références pour les champs email et mot de passe
const emailRef = useRef();
const passwordRef = useRef();

const { setUser } = useOutletContext();

// Hook pour la navigation
const navigate = useNavigate();

// Gestionnaire de soumission du formulaire
const handleSubmit = async (event) => {
event.preventDefault();

try {
// Appel à l'API pour demander une connexion
const response = await fetch(
`${import.meta.env.VITE_BACKEND_URL}/api/login`,
{
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: emailRef.current.value,
password: passwordRef.current.value,
}),
}
);

// Redirection vers la page de connexion si la création réussit
if (response.status === 200) {
const user = await response.json();

setUser(user);

navigate("/");
} else {
// Log des détails de la réponse en cas d'échec
console.info(response);
}
} catch (err) {
// Log des erreurs possibles
console.error(err);
}
};

// Rendu du composant formulaire
return (
<form onSubmit={handleSubmit}>
<div>
{/* Champ pour l'email */}
<label htmlFor="email">email</label>{" "}
<input ref={emailRef} type="email" id="email" />
</div>
<div>
{/* Champ pour le mot de passe */}
<label htmlFor="password">password</label>{" "}
<input type="password" id="password" ref={passwordRef} />
</div>
{/* Bouton de soumission du formulaire */}
<button type="submit">Send</button>
</form>
);
}

export default Login;

0 comments on commit 87e6745

Please sign in to comment.