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
4 changes: 3 additions & 1 deletion lib/prisma.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { PrismaClient } from "@prisma/client";
import pkg from "@prisma/client";

const { PrismaClient } = pkg;

// Create a global variable to store the Prisma client instance
// This prevents multiple instances during development with hot reload
Expand Down
45 changes: 43 additions & 2 deletions middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,60 @@
import jwt from "jsonwebtoken";
import prisma from "../lib/prisma.js";

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;
if(!authHeader || !authHeader.startsWith("Bearer ")){
return res.status(401).json({
success: false,
message: "access token required",

})
}
const token = authHeader && authHeader.split(" ")[1];

// 2. Verify the token

if (!token) {
return res.status(401).json({
success: false,
message: "access token required"
})
}
const decodeToken = jwt.verify(
token,
process.env.JWT_SECRET
)
// 3. Get the user from the database
const user = await prisma.user.findUnique ({
where: {
id: decodeToken.id
}
})
// 4. If the user doesn't exist, throw an error
if(!user ) {
return res.status(401).json({
success: false,
message: "this user not found",




})



}
// 5. Attach the user to the request object
req.user = user
// 6. Call the next middleware


next()

} catch (error) {
if (error.name === "JsonWebTokenError") {
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,16 @@
"author": "Duraan",
"license": "MIT",
"dependencies": {
"@prisma/client": "^5.7.1",
"@prisma/client": "^5.22.0",
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^17.2.3",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2"
},
"devDependencies": {
"nodemon": "^3.0.1",
"prisma": "^5.7.1"
"prisma": "^5.22.0"
}
}
113 changes: 110 additions & 3 deletions routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,62 @@ import prisma from "../lib/prisma.js";
import { authenticateToken } from "../middleware/auth.js";

const router = express.Router();
const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";
const JWT_SECRET = process.env.JWT_SECRET || "yfwelweofweour-secresfnkgskrt-keyefefefnkaefae";

// POST /api/auth/register - Register a new user
// POST /api/auth/register - a new user
router.post("/register", async (req, res) => {
try {
// TODO: Implement the registration logic

//extract data from the req.body

const {name, email, password} = req.body
// 1. Validate the input
1
if (!name || !email || !password) {
return res.status(400).json({
success: false,
message: "missed required fields"
})
}
// 2. Check if the user already exists

const isAlreadyExistsUser = await prisma.user.findUnique({
where: {email}
})

if (isAlreadyExistsUser ) {
return res.status(400).json({
success: false,
message: "user already exists"
})
}
// 3. Hash the password

const hashedPassword = await bcrypt.hash(password, 10)
// 4. Create the user

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

const token = jwt.sign(
{userId: newUser.id},
process.env.JWT_SECRET || "yfwelweofweour-secresfnkgskrt-keyefefefnkaefae",
{expiresIn: "1h"}
)
// 6. Return the user data and token

return res.status(201).json({
success: true,
user: newUser,
message: "user registered successfully",
token

})



} catch (error) {
Expand All @@ -34,11 +77,73 @@ router.post("/register", async (req, res) => {
router.post("/login", async (req, res) => {
try {
// TODO: Implement the login logic
// 1. Validate the input

// 1. extract data from the req.body and Validate the input

const {email, password} = req.body

if (!email || !password) {
return res.status(400).json({
success: false,
message: "missed required fields, please check your email or password is accurate"
})
}
// 2. Check if the user exists


const isUserExists = await prisma.user.findUnique({
where: {email},
select: {
id: true,
email: true,
name: true,
password: true,
createdAt: true,
updatedAt: true,
}
})




if (!isUserExists) {
return res.status(400).json({
success: false,
message: "email does not registered signUp now"
})
}
// 3. Compare the password

const isPasswordCorrect = await bcrypt.compare(password, isUserExists.password)
if (!isPasswordCorrect) {
return res.status(401).json({
success: false,
message: "invalid password"
})
}
// 4. Generate a JWT token

const token = jwt.sign(
{id: isUserExists.id},
process.env.JWT_SECRET,
{expiresIn: "23h"}
)
// 5. Return the user data and token

const { password:_, ...userInfo } = isUserExists;


return res.status(201).json({
success: true,
message: "user login... successfuly",
data: {
id: isUserExists.id,
isUserExists: userInfo,
token

}

})


} catch (error) {
Expand Down Expand Up @@ -71,4 +176,6 @@ router.get("/me", authenticateToken, async (req, res) => {
}
});

app.us

export default router;
2 changes: 2 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import express from "express";
import dotenv from "dotenv";
dotenv.config(); // ← anaa ku daray hada
import cors from "cors";
import bodyParser from "body-parser";

Expand Down
2 changes: 1 addition & 1 deletion services/taskServices.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export async function getTaskById(id, userId) {
include: { subtasks: true },
});

if (!task) {
if (!task || !userId) {
throw new Error("Task not found");
}

Expand Down