Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,39 @@
import jwt from "jsonwebtoken";
import prisma from "../lib/prisma.js";
import { User } from "lucide-react";

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"];

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 || "ttdtdtgulgytfdsassdfgkliop" );
// 3. Get the user from the database
const user= await User.FindById(decoded.id);

// 4. If the user doesn't exist, throw an error
if(!user) {
return res.status(404).json({
success:false,
message:"User not found",
});
}
// 5. Attach the user to the request object
req.task = decoded;
// 6. Call the next middleware
next();



Expand Down
68 changes: 68 additions & 0 deletions routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,43 @@ router.post("/register", async (req, res) => {
// 4. Create the user
// 5. Generate a JWT token
// 6. Return the user data and token

// 1. Validate input
if (!name || !email || !password) {
return res.status(400).json({ success: false, message: "All fields are required" });
}

// 2. Check if the user already exists
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ success: false, message: "User already exists" });
}

// 3. Hash the password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

// 4. Create the user
const user = await User.create({
name,
email,
password: hashedPassword,
});

// 5. Generate a JWT token
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });

// 6. Return the user data and token
res.status(201).json({
success: true,
message: "User registered successfully",
user: {
id: user._id,
name: user.name,
email: user.email,
},
token,
});

} catch (error) {
console.error("Registration error:", error);
Expand All @@ -39,6 +74,39 @@ router.post("/login", async (req, res) => {
// 3. Compare the password
// 4. Generate a JWT token
// 5. Return the user data and token
// 1. Validate input
if (!email || !password) {
return res.status(400).json({ success: false, message: "All fields are required" });
}

// 2. Check if user exists
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ success: false, message: "Invalid credentials" });
}

// 3. Compare password
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({ success: false, message: "Invalid credentials" });
}

// 4. Generate JWT token
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });

// 5. Return user data and token
res.status(200).json({
success: true,
message: "Login successful",
user: {
id: user._id,
name: user.name,
email: user.email,
},
token,
});




} catch (error) {
Expand Down