diff --git a/middleware/auth.js b/middleware/auth.js index 7deb650..b0084a2 100644 --- a/middleware/auth.js +++ b/middleware/auth.js @@ -6,15 +6,28 @@ const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key"; export const authenticateToken = async (req, res, next) => { try { // TODO: Implement the authentication middleware + const authHeader = req.headers["authorization"]; + if (!authHeader) + return res.status(401).json({ error: "No token provided" }); + // 1. Get the token from the request header + + const token = authHeader.split(" ")[1]; + if (!token) return res.status(401).json({ error: "Invalid token format" }); // 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 }, // exclude password + }); // 4. If the user doesn't exist, throw an error + if (!user) return res.status(401).json({ error: "User not found" }); // 5. Attach the user to the request object + req.user = user; // attach user to request + next(); // 6. Call the next middleware - - - } catch (error) { if (error.name === "JsonWebTokenError") { return res.status(401).json({ diff --git a/routes/auth.js b/routes/auth.js index 7a78cfc..de2d4f0 100644 --- a/routes/auth.js +++ b/routes/auth.js @@ -9,17 +9,38 @@ const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key"; // POST /api/auth/register - Register a new user router.post("/register", async (req, res) => { + const { name, email, password } = req.body; try { // TODO: Implement the registration logic // 1. Validate the input + if (!name || !email || !password) + return res.status(400).json({ error: "all the fiekds are required" }); + // 2. Check if the user already exists + + const existingUser = await prisma.user.findUnique({ where: { email } }); + if (existingUser) + return res.status(400).json({ error: "Email already registered" }); + // 3. Hash the password + + const saltRound = await bcrypt.hash(password, 10); // 4. Create the user + const user = await prisma.user.create({ + data: { name, email, password: saltRound }, + }); + // 5. Generate a JWT token + const token = jwt.sign( + { userId: user.id, email: user.email }, + process.env.JWT_SECRET, + { expiresIn: "24h" } + ); // 6. Return the user data and token - - - + res.json({ + user: { id: user.id, name: user.name, email: user.email }, + token, + }); } catch (error) { console.error("Registration error:", error); res.status(500).json({ @@ -32,15 +53,31 @@ router.post("/register", async (req, res) => { // POST /api/auth/login - Login user router.post("/login", async (req, res) => { + const { email, password } = req.body; try { // TODO: Implement the login logic // 1. Validate the input + if (!email || !password) + return res.status(400).json({ error: "Email and password required" }); // 2. Check if the user exists + const user = await prisma.user.findUnique({ where: { email } }); + if (!user) + return res.status(400).json({ error: "Invalid Email or Password" }); // 3. Compare the password + const isValid = await bcrypt.compare(password, user.password); + if (!isValid) + return res.status(400).json({ error: "Invalid Email or Password" }); // 4. Generate a JWT token + const token = jwt.sign( + { userId: user.id, email: user.email }, + process.env.JWT_SECRET, + { expiresIn: "24h" } + ); // 5. Return the user data and token - - + res.json({ + user: { id: user.id, name: user.name, email: user.email }, + token, + }); } catch (error) { console.error("Login error:", error); res.status(500).json({ diff --git a/server.js b/server.js index a6f2c28..7c161e5 100644 --- a/server.js +++ b/server.js @@ -9,7 +9,7 @@ import { authenticateToken } from "./middleware/auth.js"; // Initialize Express app const app = express(); -const PORT = process.env.PORT || 3000; +const PORT = process.env.PORT || 4000; // Middleware app.use(cors()); // Enable CORS for all routes