From ca062d9ab780ad63bfc7a1e49dfbfbdd282dc63a Mon Sep 17 00:00:00 2001 From: naqib-axmed Date: Sun, 14 Dec 2025 20:25:20 +0300 Subject: [PATCH] =?UTF-8?q?=20assignment=20week=2020=20done=20=E2=9C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/prisma.js | 4 +- middleware/auth.js | 45 +++++++++++++++- package.json | 5 +- routes/auth.js | 113 +++++++++++++++++++++++++++++++++++++-- server.js | 2 + services/taskServices.js | 2 +- 6 files changed, 162 insertions(+), 9 deletions(-) diff --git a/lib/prisma.js b/lib/prisma.js index 569e176..857e8a6 100644 --- a/lib/prisma.js +++ b/lib/prisma.js @@ -1,4 +1,6 @@ -import { PrismaClient } from "@prisma/client"; +import pkg from "@prisma/client"; + +const { PrismaClient } = pkg; // Create a global variable to store the Prisma client instance // This prevents multiple instances during development with hot reload diff --git a/middleware/auth.js b/middleware/auth.js index 7deb650..12b0acb 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -1,19 +1,60 @@ import jwt from "jsonwebtoken"; import prisma from "../lib/prisma.js"; -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; + if(!authHeader || !authHeader.startsWith("Bearer ")){ + return res.status(401).json({ + success: false, + message: "access token required", + + }) + } + const token = authHeader && authHeader.split(" ")[1]; + // 2. Verify the token + + if (!token) { + return res.status(401).json({ + success: false, + message: "access token required" + }) + } +const decodeToken = jwt.verify( + token, + process.env.JWT_SECRET +) // 3. Get the user from the database + const user = await prisma.user.findUnique ({ + where: { + id: decodeToken.id + } + }) // 4. If the user doesn't exist, throw an error + if(!user ) { + return res.status(401).json({ + success: false, + message: "this 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") { diff --git a/package.json b/package.json index 99486e0..5499f34 100644 --- a/package.json +++ b/package.json @@ -22,15 +22,16 @@ "author": "Duraan", "license": "MIT", "dependencies": { - "@prisma/client": "^5.7.1", + "@prisma/client": "^5.22.0", "bcryptjs": "^2.4.3", "body-parser": "^1.20.2", "cors": "^2.8.5", + "dotenv": "^17.2.3", "express": "^4.18.2", "jsonwebtoken": "^9.0.2" }, "devDependencies": { "nodemon": "^3.0.1", - "prisma": "^5.7.1" + "prisma": "^5.22.0" } } diff --git a/routes/auth.js b/routes/auth.js index 7a78cfc..23997c8 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -5,19 +5,62 @@ 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 || "yfwelweofweour-secresfnkgskrt-keyefefefnkaefae"; -// POST /api/auth/register - Register a new user +// POST /api/auth/register - a new user router.post("/register", async (req, res) => { try { // TODO: Implement the registration logic + + //extract data from the req.body + + const {name, email, password} = req.body // 1. Validate the input +1 + if (!name || !email || !password) { + return res.status(400).json({ + success: false, + message: "missed required fields" + }) + } // 2. Check if the user already exists + + const isAlreadyExistsUser = await prisma.user.findUnique({ + where: {email} + }) + + if (isAlreadyExistsUser ) { + return res.status(400).json({ + success: false, + message: "user already exists" + }) + } // 3. Hash the password + + const hashedPassword = await bcrypt.hash(password, 10) // 4. Create the user + + const newUser = await prisma.user.create({ + data: { name, email, password: hashedPassword,}, + select: {id: true, name: true, email: true} + }) // 5. Generate a JWT token + + const token = jwt.sign( + {userId: newUser.id}, + process.env.JWT_SECRET || "yfwelweofweour-secresfnkgskrt-keyefefefnkaefae", + {expiresIn: "1h"} + ) // 6. Return the user data and token + return res.status(201).json({ + success: true, + user: newUser, + message: "user registered successfully", + token + + }) + } catch (error) { @@ -34,11 +77,73 @@ router.post("/register", async (req, res) => { router.post("/login", async (req, res) => { try { // TODO: Implement the login logic - // 1. Validate the input + + // 1. extract data from the req.body and Validate the input + + const {email, password} = req.body + + if (!email || !password) { + return res.status(400).json({ + success: false, + message: "missed required fields, please check your email or password is accurate" + }) + } // 2. Check if the user exists + + + const isUserExists = await prisma.user.findUnique({ + where: {email}, + select: { + id: true, + email: true, + name: true, + password: true, + createdAt: true, + updatedAt: true, + } + }) + + + + + if (!isUserExists) { + return res.status(400).json({ + success: false, + message: "email does not registered signUp now" + }) + } // 3. Compare the password + + const isPasswordCorrect = await bcrypt.compare(password, isUserExists.password) + if (!isPasswordCorrect) { + return res.status(401).json({ + success: false, + message: "invalid password" + }) + } // 4. Generate a JWT token + + const token = jwt.sign( + {id: isUserExists.id}, + process.env.JWT_SECRET, + {expiresIn: "23h"} + ) // 5. Return the user data and token + + const { password:_, ...userInfo } = isUserExists; + + + return res.status(201).json({ + success: true, + message: "user login... successfuly", + data: { + id: isUserExists.id, + isUserExists: userInfo, + token + + } + + }) } catch (error) { @@ -71,4 +176,6 @@ router.get("/me", authenticateToken, async (req, res) => { } }); +app.us + export default router; diff --git a/server.js b/server.js index a6f2c28..58f2eae 100644 --- a/server.js +++ b/server.js @@ -1,4 +1,6 @@ import express from "express"; +import dotenv from "dotenv"; +dotenv.config(); // ← anaa ku daray hada import cors from "cors"; import bodyParser from "body-parser"; diff --git a/services/taskServices.js b/services/taskServices.js index 1f55241..7a18f5e 100644 --- a/services/taskServices.js +++ b/services/taskServices.js @@ -20,7 +20,7 @@ export async function getTaskById(id, userId) { include: { subtasks: true }, }); - if (!task) { + if (!task || !userId) { throw new Error("Task not found"); }