From 5ef3551a4e4ba33b2f092f24fb3b12f9c2fc8909 Mon Sep 17 00:00:00 2001 From: sahramayo Date: Mon, 22 Sep 2025 20:15:30 -0500 Subject: [PATCH] fisnish --- middleware/auth.js | 29 +++++++++++-- routes/auth.js | 104 ++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 125 insertions(+), 8 deletions(-) diff --git a/middleware/auth.js b/middleware/auth.js index 7deb650..f35717e 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -5,15 +5,38 @@ const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key"; export const authenticateToken = async (req, res, next) => { try { - // TODO: Implement the authentication middleware // 1. Get the token from the request header + const authHeader = req.headers.authorization; + const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN + + if (!token) { + return res.status(401).json({ + success: false, + message: "Access token required", + }); + } + // 2. Verify the token + const decoded = jwt.verify(token, JWT_SECRET); + // 3. Get the user from the database + const user = await prisma.user.findUnique({ + where: { id: decoded.userId }, + }); + // 4. If the user doesn't exist, throw an error + if (!user) { + return res.status(401).json({ + success: false, + message: "User not found", + }); + } + // 5. Attach the user to the request object - // 6. Call the next middleware + req.user = user; - + // 6. Call the next middleware + next(); } catch (error) { if (error.name === "JsonWebTokenError") { diff --git a/routes/auth.js b/routes/auth.js index 7a78cfc..b06db78 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -5,20 +5,71 @@ import prisma from "../lib/prisma.js"; import { authenticateToken } from "../middleware/auth.js"; const router = express.Router(); -const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key"; +const JWT_SECRET = process.env.JWT_SECRET || "week20"; // POST /api/auth/register - Register a new user router.post("/register", async (req, res) => { try { - // TODO: Implement the registration logic // 1. Validate the input + const { name, email, password } = req.body; + + if (!name || !email || !password) { + return res.status(400).json({ + success: false, + message: "Name, email, and password are required", + }); + } + + if (password.length < 6) { + return res.status(400).json({ + success: false, + message: "Password must be at least 6 characters long", + }); + } + // 2. Check if the user already exists + const existingUser = await prisma.user.findUnique({ + where: { email }, + }); + + if (existingUser) { + return res.status(409).json({ + success: false, + message: "User with this email already exists", + }); + } + // 3. Hash the password + const saltRounds = 10; + const hashedPassword = await bcrypt.hash(password, saltRounds); + // 4. Create the user + const user = await prisma.user.create({ + data: { + name, + email, + password: hashedPassword, + }, + }); + // 5. Generate a JWT token - // 6. Return the user data and token + const token = jwt.sign( + { userId: user.id, email: user.email }, + JWT_SECRET, + { expiresIn: "7d" } + ); + // 6. Return the user data and token + const { password: _, ...userWithoutPassword } = user; + res.status(201).json({ + success: true, + message: "User registered successfully", + data: { + user: userWithoutPassword, + token, + }, + }); } catch (error) { console.error("Registration error:", error); @@ -33,13 +84,56 @@ router.post("/register", async (req, res) => { // POST /api/auth/login - Login user router.post("/login", async (req, res) => { try { - // TODO: Implement the login logic // 1. Validate the input + const { email, password } = req.body; + + if (!email || !password) { + return res.status(400).json({ + success: false, + message: "Email and password are required", + }); + } + // 2. Check if the user exists + const user = await prisma.user.findUnique({ + where: { email }, + }); + + if (!user) { + return res.status(401).json({ + success: false, + message: "Invalid email or password", + }); + } + // 3. Compare the password + const isPasswordValid = await bcrypt.compare(password, user.password); + + if (!isPasswordValid) { + return res.status(401).json({ + success: false, + message: "Invalid email or password", + }); + } + // 4. Generate a JWT token + const token = jwt.sign( + { userId: user.id, email: user.email }, + JWT_SECRET, + { expiresIn: "7d" } + ); + // 5. Return the user data and token - + const { password: _, ...userWithoutPassword } = user; + + res.json({ + success: true, + message: "Login successful", + data: { + user: userWithoutPassword, + token, + }, + }); } catch (error) { console.error("Login error:", error);