From a4bbed926306b32d90ca6831ca2ceb6eb85a9978 Mon Sep 17 00:00:00 2001 From: jamila Date: Fri, 5 Dec 2025 14:43:33 +0300 Subject: [PATCH] Week20 --- middleware/auth.js | 31 ++++++++++++++- prisma/schema.prisma | 4 +- routes/auth.js | 94 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 124 insertions(+), 5 deletions(-) diff --git a/middleware/auth.js b/middleware/auth.js index 7deb650..396af26 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -7,14 +7,41 @@ export const authenticateToken = async (req, res, next) => { try { // TODO: Implement the authentication middleware // 1. Get the token from the request header + const token = req.headers["authorization"]?.split(" ")[1] + + // 2. Verify the token + if (!token) { + return res.status(401).json({ + success: false, + message: "Access token required" + }) + } // 3. Get the user from the database + const decoded = jwt.verify( + token, + process.env.JWT_SECRET || "secretkey" + ) // 4. If the user doesn't exist, throw an error + const user = await prisma.user.findUnique({ + where: { id: decoded.userId}, + select: { + id: true, + name: true, + email: true + } + }) + if (!user) { + return res.status(401).json({ + success: false, + message: "Invalid token - user not found", + }); + } // 5. Attach the user to the request object + req.user = user // 6. Call the next middleware + next() - - } catch (error) { if (error.name === "JsonWebTokenError") { return res.status(401).json({ diff --git a/prisma/schema.prisma b/prisma/schema.prisma index a320a24..44fca68 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -7,9 +7,9 @@ generator client { datasource db { provider = "postgresql" - url = env("DATABASE_URL") + url = "postgresql://postgres.rxsshdaugggkxtxpxjsc:0nGTVhlZIGhwmZ1d@aws-1-eu-west-1.pooler.supabase.com:5432/postgres" } - +//url = env("DATABASE_URL") model User { id String @id @default(cuid()) email String @unique diff --git a/routes/auth.js b/routes/auth.js index 7a78cfc..a24507c 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -11,13 +11,62 @@ const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key"; router.post("/register", async (req, res) => { try { // TODO: Implement the registration logic + const { email, password, name } = req.body + // 1. Validate the input + if (!name || !email || !password) { + return res.status(400).json({ + status: 'failed', + message: 'You are missing required field, all fields are required' + }) + } + // 2. Check if the user already exists + const existsUser = await prisma.user.findUnique({ + where: { email: email} + }) + + if (existsUser) { + return res.status(400).json({ + status: "failed", + "message": "This user already exists in the database" + }) + } + // 3. Hash the password + const hashPassword = await bcrypt.hash(password, 10) + // 4. Create the user + const newUser = await prisma.user.create({ + data: { + name, + email, + password: hashPassword, + + + }, + select: { + id: true, + name: true, + email: true + + } + }) + // 5. Generate a JWT token + const token = jwt.sign( + { userId: newUser.id, email: newUser.email }, + process.env.JWT_SECRET || "secretkey", + { expiresIn: "24h" } + ); + // 6. Return the user data and token - + res.status(201).json({ + status: "success", + message: "User registered successfully", + user: newUser, + token}) + } catch (error) { @@ -34,11 +83,54 @@ router.post("/register", async (req, res) => { router.post("/login", async (req, res) => { try { // TODO: Implement the login logic + const { email, password} = req.body + // 1. Validate the input + if (!email || !password) { + return res.status(400).json({ + status: 'failed', + message: 'You are missing required field, all fields are required' + }) + } // 2. Check if the user exists + const user = await prisma.user.findUnique({ + where: { email: email } + }) + + if (!user) { + return res.status(400).json({ + status: "failed", + "message": "This email does not exists in the database" + }) + } // 3. Compare the password + const iscomparePassword = await bcrypt.compare(password, user.password) + + if (iscomparePassword == false) { + 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 }, + process.env.JWT_SECRET || "secretkey", + { expiresIn: "24h" } + ); + + const {password: _, ...userInfo } = user + // 5. Return the user data and token + res.status(201).json({ + status: "success", + message: "User logged in successfully", + data: { + user: userInfo, + token + } + }) } catch (error) {