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
35 changes: 32 additions & 3 deletions middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,43 @@ 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];

//check the token
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");

// 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
// 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
106 changes: 101 additions & 5 deletions routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,65 @@ const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";
router.post("/register", async (req, res) => {
try {
// 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 existingUser = await prisma.user.findUnique({
where: { email },
});

if (existingUser) {
return res.status(400).json({
success: false,
message: "User with this email already exists",
});
}

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

// 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,
password: true,
createdAt: true,
},
});

// 5. Generate a JWT token
const token = jwt.sign(
{ userId: newUser.id },
process.env.JWT_SECRET || "mysecret",
{ expiresIn: "24" }
);

// 6. Return the user data and token

res.status(201).json({
success: true,
message: "User registered successfully",
data: {
user: newUser,
token: token,
},
});
} catch (error) {
console.error("Registration error:", error);
res.status(500).json({
Expand All @@ -33,14 +83,60 @@ router.post("/register", async (req, res) => {
// POST /api/auth/login - Login user
router.post("/login", async (req, res) => {
try {
// TODO: Implement the login logic
// TODO: Implement th login logic
const { email, password } = req.body;

// 1. Validate the input
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 isUserPasswordValid = await bcrypt.compare(password, user.password)

if(!isUserPasswordValid){
return res.status(401).json({
success: false,
message: "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"}
)

// return user info and token, but don't include password
const { password: _, ...userData} = user;

// 5. Return the user data and token


res.status(200).json({
success: true,
message: "Loggin successful",
data: {
user: userData,
token,
}
})


} catch (error) {
console.error("Login error:", error);
res.status(500).json({
Expand Down
2 changes: 1 addition & 1 deletion routes/tasks.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ router.use(authenticateToken);
// This route handles GET requests to /api/tasks
// req = request object (contains data sent by client)
// res = response object (used to send data back to client)
router.get("/tasks", async (req, res) => {
router.get("/tasks", authenticateToken, async (req, res) => {
try {
const tasks = await getAllTasks(req.user.id);

Expand Down