diff --git a/middleware/auth.js b/middleware/auth.js index 7deb650..0fb6c47 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -7,14 +7,49 @@ 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"]; + console.log("Auth header from client:", req.headers["authorization"]); + + const token = authHeader && authHeader.split(" ")[1]; + if(!token){ + return res.status(401).json({ + success: false, + message: "Access token required", + }) + + } // 2. Verify the token + const decoded = jwt.verify(token, process.env.JWT_SECRET || "mysecret"); + console.log("Decoded payload:", decoded); + + + // 3. Get the user from the database + const user = await prisma.user.findUnique({ + where: { id: decoded.userId }, + select: { + id: true, + name: true, + email: true, + password: true, + createdAt: true, + updatedAt: true, + }, +}); + // 4. If the user doesn't exist, throw an error + 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() + // console.log("Authorization header:", req.headers["authorization"]); - - } catch (error) { if (error.name === "JsonWebTokenError") { return res.status(401).json({ @@ -22,6 +57,7 @@ export const authenticateToken = async (req, res, next) => { message: "Invalid token", }); } + console.log("JWT Error:", error); if (error.name === "TokenExpiredError") { return res.status(401).json({ diff --git a/routes/auth.js b/routes/auth.js index 7a78cfc..28af482 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -10,14 +10,61 @@ 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 + // TODO: Implement the registration + // logic + const{name,email,password}= req.body // 1. Validate the input + if(!name || !email || !password){ + return res.status(400).json({ + success:false, + message: "name,email and password are required", + }) + } // 2. Check if the user already exists + const existingstudent= await prisma.user.findUnique({ + where:{email} + }) + if (existingstudent){ + return res.status(400).json({ + success: false, + message: "student with this email already exists", + }) + } // 3. Hash the password - // 4. Create the user + const saltRound = 10; + const hashedPassword = await bcrypt.hash(password, saltRound); + + + // 4. Create the usereb + const newuser = await prisma.user.create({ + data:{ + name, + email, + password:hashedPassword, + + }, + select: { + id: true, + name:true, + email: true, + createdAt:true + } + }) // 5. Generate a JWT token + const token=jwt.sign( + {userId:newuser.id }, + process.env.JWT_SECRET|| "mysecret", + {expiresIn:"24h"} + ) // 6. Return the user data and token - + res.status(201).json({ + success:true, + message: "student registered successfully", + data:{ + user:newuser, + token + } + }) } catch (error) { @@ -35,11 +82,49 @@ 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(404).json({ + success: false, + message: "User not found", + }); + } // 3. Compare the password + const isPasswordValid =await bcrypt.compare(password, user.password) + if(!isPasswordValid){ + return res.status(401).json ({ + success:false, + message: "sorry, your password is wrong" + }) + } // 4. Generate a JWT token + const token = jwt.sign( + {userId: user.id, email: email}, + process.env.JWT_SECRET || "mysecret", + {expiresIn: "24h"} + ) // 5. Return the user data and token - + const { password: _, ...userData} = user; + + res.json({ + success: true, + message: "login successful", + data:{ + user:userData, + token, + } + }) } catch (error) { console.error("Login error:", error);