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
33 changes: 33 additions & 0 deletions middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,44 @@ 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: "Access token required",
});
}
// 2. Verify the token
const decoded = jwt.verify(
token,
process.env.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,
name: true,
email: 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();



Expand Down
90 changes: 88 additions & 2 deletions routes/auth.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import express from "express";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";

import prisma from "../lib/prisma.js";
import { authenticateToken } from "../middleware/auth.js";

Expand All @@ -12,14 +13,56 @@ router.post("/register", async (req, res) => {
try {
// TODO: Implement the registration logic
// 1. Validate the input
const { name, email, password } = req.body;
console.log(req.body)

if (!name || !email || !password) {
return res.status(400).json({
status: "failed",
message: "You are missing required fields",
});
}

// 2. Check if the user already exists
const alreadyExist = await prisma.user.findUnique({
where: { email: email },
});

if (alreadyExist) {
return res.status(400).json({
status: "failed",
message: "This user already exists in the database",
});
}


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


// 4. Create the user
// 5. Generate a JWT token
// 6. Return the user data and token
const newUser = await prisma.user.create({
data: {
name,
email,
password: hashedPassword,
},
select: {
id: true,
name: true,
email: true,
},
});



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

} catch (error) {
console.error("Registration error:", error);
res.status(500).json({
Expand All @@ -35,10 +78,53 @@ 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({
status: "failed",
message: "Missing email or password",
});
}
// 2. Check if the user exists
const user = await prisma.user.findUnique({
where: { email },
});

if (!user) {
return res.status(400).json({
status: "failed",
message: "Email does not exist",
});
}

// 3. Compare the password
const isPasswordCorrect = await bcrypt.compare(password, user.password);

if (!isPasswordCorrect) {
return res.status(401).json({
success: false,
message: "Your password is incorrect",
});
}

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


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


} catch (error) {
Expand Down