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
30 changes: 27 additions & 3 deletions middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,38 @@ 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];
if (!token) {
return res.status(401).json({
success: false,
message: "No token provided",
});
}
// 2. Verify the token
const decoded = jwt.verify(token, JWT_SECRET || "your-secret-key");

// 3. Get the user from the database
const user = await prisma.user.findUnique({
where: { id: decoded.userId },
select: {
id: true,
email: true,
name: true,
createdAt: true,
},
});
// 4. If the user doesn't exist, throw an error
if (!user) {
return res.status(401).json({
success: false,
message: "User not found",
});
}
// 5. Attach the user to the request object
// 6. Call the next middleware
req.user = user;



// 6. Call the next middleware
next();
} catch (error) {
if (error.name === "JsonWebTokenError") {
return res.status(401).json({
Expand Down
84 changes: 79 additions & 5 deletions routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,55 @@ router.post("/register", async (req, res) => {
try {
// TODO: Implement the registration logic
// 1. Validate the input
const { name, email, password } = req.body;
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 existingUser = await prisma.user.findUnique({
where: { email },
});
if (existingUser) {
return res.status(400).json({
success: false,
message: "User already exists",
});
}
// 3. Hash the password
const saltRounds = 12;
const hashedPassword = await bcrypt.hash(password, saltRounds);

// 4. Create the user
const newUser = await prisma.user.create({
data: {
name,
email,
password: hashedPassword,
},
select: {
id: true,
email: true,
name: true,
createdAt: true,
},
});

// 5. Generate a JWT token
const token = jwt.sign({ userId: newUser.id }, JWT_SECRET, {
expiresIn: "24h",
});
// 6. Return the user data and token



res.status(201).json({
success: true,
message: "User registered successfully",
data: {
user: newUser,
token,
},
});
} catch (error) {
console.error("Registration error:", error);
res.status(500).json({
Expand All @@ -35,12 +76,45 @@ 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(401).json({
success: false,
message: "Invalid email or password",
});
}
// 3. Compare the password
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({
success: false,
message: "Invalid email or password",
});
}
// 4. Generate a JWT token
const token = jwt.sign({ userId: user.id }, JWT_SECRET, {
expiresIn: "24h",
});
// 5. Return the user data and token


const { password: _, ...userWithoutPassword } = user; // Exclude password from response
res.json({
success: true,
message: "Login successful",
data: {
user: userWithoutPassword,
token,
},
});
} catch (error) {
console.error("Login error:", error);
res.status(500).json({
Expand Down