diff --git a/middleware/auth.js b/middleware/auth.js index 7deb650..177e9f8 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -6,12 +6,44 @@ 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 token = req.headers["authorization"]?.split(" ")[1] // 2. Verify the token + + 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.userId}, + select:{ + id: true, + name: true, + email: true, + + + + } + }) // 4. If the user doesn't exist, throw an error + if(!user) { + return res.status(401).json({ + status: "fail", + message: "user isnt exist", + error: "error.message" + }) + + } // 5. Attach the user to the request object + req.user = user + + + // 6. Call the next middleware + next() diff --git a/routes/auth.js b/routes/auth.js index 7a78cfc..406e8d8 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -3,20 +3,85 @@ import bcrypt from "bcryptjs"; import jwt from "jsonwebtoken"; import prisma from "../lib/prisma.js"; import { authenticateToken } from "../middleware/auth.js"; +// import { use } from "react"; const router = express.Router(); + const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key"; // POST /api/auth/register - Register a new user router.post("/register", async (req, res) => { try { // TODO: Implement the registration logic + const {email, password, name} = req.body // 1. Validate the input - // 2. Check if the user already exists + if(!email || !password || !name){ + return res.status(201).json({ + status: "success", + message: "registered succesfully", + + }) + } + + + // 2. Check if the user already exists + + const isalreadyexists = await prisma.user.findUnique({ + where: {email: email} + }) + + + + + if(isalreadyexists) { + return res.status(400).json({ + status: "failed", + message: "this user is already exists", + error: "error.message" + }) + } + + + // 3. Hash the password + const hashedpassoword = await bcrypt.hash(password, 10) // 4. Create the user + const newuser = await prisma.user.create({ + + data: { + email, + password: hashedpassoword, + name + }, + select: { + id: true, + email: true, + password: true, + name: true + } + }) + + + + + // 5. Generate a JWT token + const token = jwt.sign( + {userId: newuser.id}, + process.env.JWT_SECRET || "secretkey", + {expiresIn: "24h"} + ) // 6. Return the user data and token + return res.status(201).json({ + status: "success", + message: "registred succesfully", + token, + user: newuser, + + + + + }) @@ -34,11 +99,58 @@ 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(401).json({ + status: "fail", + message: "input is missing all input is required", + error: error.message + }) + } // 2. Check if the user exists + const user = await prisma.user.findUnique({ + where: {email: email} + }) + + if(!user){ + return res.status(400).json({ + success: false, + message: "this user isnt exst" + }) + + + } // 3. Compare the password + const passowordcorrect = await bcrypt.compare(password, user.password) + + if(passowordcorrect == false){ + return res.status(402).json({ + success: false, + message: "invalid passowor or email" + }) + } // 4. Generate a JWT token + const token = jwt.sign( + {userId: user.id}, + process.env.JWT_SECRET || "secretkey", + {expiresIn: "24h"} + ) // 5. Return the user data and token + const {password: _, ...userinfo} = user + + + + return res.status(201).json({ + status: "success", + message: "your login is succesfull", + data: { + user: userinfo, + token + } + + + }) } catch (error) { diff --git a/routes/tasks.js b/routes/tasks.js index dca9b03..201c22b 100644 --- a/routes/tasks.js +++ b/routes/tasks.js @@ -22,7 +22,7 @@ router.use(authenticateToken); // This route handles GET requests to /api/tasks // req = request object (contains data sent by client) // res = response object (used to send data back to client) -router.get("/tasks", async (req, res) => { +router.get("/tasks", authenticateToken, async (req, res) => { try { const tasks = await getAllTasks(req.user.id); @@ -42,7 +42,7 @@ router.get("/tasks", async (req, res) => { // GET /api/tasks/:id - Get task by ID for the authenticated user // :id is a route parameter - it captures the value from the URL // Example: /api/tasks/1 will set req.params.id = "1" -router.get("/tasks/:id", async (req, res) => { +router.get("/tasks/:id", authenticateToken, async (req, res) => { try { const { id } = req.params; // Extract the ID from the URL const task = await getTaskById(id, req.user.id); @@ -69,7 +69,7 @@ router.get("/tasks/:id", async (req, res) => { // POST /api/tasks - Create new task for the authenticated user // POST requests are used to create new resources // req.body contains the data sent in the request body -router.post("/tasks", async (req, res) => { +router.post("/tasks", authenticateToken, async (req, res) => { try { const taskData = req.body; const newTask = await createTask(taskData, req.user.id); @@ -89,7 +89,7 @@ router.post("/tasks", async (req, res) => { // PUT /api/tasks/:id - Update task for the authenticated user // PUT requests are used to update existing resources // The entire resource is replaced with the new data -router.put("/tasks/:id", async (req, res) => { +router.put("/tasks/:id", authenticateToken, async (req, res) => { try { const { id } = req.params; const updateData = req.body; @@ -116,7 +116,7 @@ router.put("/tasks/:id", async (req, res) => { // DELETE /api/tasks/:id - Delete task for the authenticated user // DELETE requests are used to remove resources -router.delete("/tasks/:id", async (req, res) => { +router.delete("/tasks/:id", authenticateToken, async (req, res) => { try { const { id } = req.params; const deletedTask = await deleteTask(id, req.user.id);