Skip to content

Commit

Permalink
Add username validation and error handling in userRoutes.ts and SignI…
Browse files Browse the repository at this point in the history
…n page.tsx
  • Loading branch information
etienne committed Feb 15, 2024
1 parent d2fdba2 commit 142e944
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 20 deletions.
15 changes: 10 additions & 5 deletions backend/src/routes/userRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ router.post("/register", async (req: Request, res: Response) => {
return res.status(409).json({ message: "Email already exists" });
}

const existingUsername = await User.findOne({ username });

if (existingUsername) {
return res.status(408).json({ message: "Username already exists" });
}

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

Expand Down Expand Up @@ -60,22 +66,21 @@ router.get("/:username", async (req: Request, res: Response) => {
});

router.post("/login", async (req: Request, res: Response) => {
const { email, password } = req.body;
const { username, password } = req.body;

try {
const user = await User.findOne({ email });
const user = await User.findOne({ username });

if (!user) {
return res.status(404).json({ message: "User not found" });
return res.status(404).json({ message: "Login failed" });
}

const isPasswordValid = await bcrypt.compare(password, user.password);

if (!isPasswordValid) {
return res.status(401).json({ message: "Invalid password" });
}
const token = jwt.sign(
{ id: user.id, email: user.email },
{ id: user?.id, email: user?.username },
process.env.JWT_SECRET || "",
{ expiresIn: "7d" }
);
Expand Down
44 changes: 29 additions & 15 deletions frontend/src/app/signin/page.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,50 @@
"use client";
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import { useUser } from "@/contexts/UserContext";
import Link from "next/link";
import { useRouter } from "next/router";
import { useRouter } from "next/navigation";
import { Container } from "./styles";
import ThemeSwitcher from "@/components/shared/themeswitcher";
import Layout from "../layout";

export default function SignIn() {
const [username, setUsername] = useState("");
const { username, setUsername } = useUser();
const [password, setPassword] = useState("");

const router = useRouter();
const { signIn } = useAuth();
const router = useRouter(); // Déplacez cette ligne ici

const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();

try {
await signIn({ username, password });
const url = process.env.NEXT_PUBLIC_BASE_URL + "user/login";
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username,
password,
}),
});

if (response.status === 404) {
alert("User not found");
} else if (response.status === 401) {
alert("Invalid password");
} else if (response.status === 200) {
const data = await response.json();
localStorage.setItem("token", data.token);
router.push("/chat");
} catch (error) {
console.error(error);
alert("Erreur de connexion, veuillez vérifier vos identifiants.");
localStorage.setItem("name", username);
} else {
throw new Error("Une erreur inattendue s'est produite");
}
};

return (
<Container>
<div>
<ThemeSwitcher />
<form data-testid="login-form" onSubmit={handleSubmit}>
<h2>Connectez-vous</h2>
<p> Connectez-vous pour accéder à votre espace </p>
Expand Down Expand Up @@ -57,7 +75,3 @@ export default function SignIn() {
</Container>
);
}

function useAuth(): { signIn: any } {
throw new Error("Function not implemented.");
}

0 comments on commit 142e944

Please sign in to comment.