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
19 changes: 16 additions & 3 deletions middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,28 @@ const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";
export const authenticateToken = async (req, res, next) => {
try {
// TODO: Implement the authentication middleware
const authHeader = req.headers["authorization"];
if (!authHeader)
return res.status(401).json({ error: "No token provided" });

// 1. Get the token from the request header

const token = authHeader.split(" ")[1];
if (!token) return res.status(401).json({ error: "Invalid token format" });
// 2. Verify the token
const decoded = jwt.verify(token, process.env.JWT_SECRET || "mySecret");
console.log("decoded payload", decoded);
// 3. Get the user from the database
const user = await prisma.user.findUnique({
where: { id: decoded.userId },
select: { id: true, name: true, email: true }, // exclude password
});
// 4. If the user doesn't exist, throw an error
if (!user) return res.status(401).json({ error: "User not found" });
// 5. Attach the user to the request object
req.user = user; // attach user to request
next();
// 6. Call the next middleware



} catch (error) {
if (error.name === "JsonWebTokenError") {
return res.status(401).json({
Expand Down
47 changes: 42 additions & 5 deletions routes/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,38 @@ const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";

// POST /api/auth/register - Register a new user
router.post("/register", async (req, res) => {
const { name, email, password } = req.body;
try {
// TODO: Implement the registration logic
// 1. Validate the input
if (!name || !email || !password)
return res.status(400).json({ error: "all the fiekds are required" });

// 2. Check if the user already exists

const existingUser = await prisma.user.findUnique({ where: { email } });
if (existingUser)
return res.status(400).json({ error: "Email already registered" });

// 3. Hash the password

const saltRound = await bcrypt.hash(password, 10);
// 4. Create the user
const user = await prisma.user.create({
data: { name, email, password: saltRound },
});

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



res.json({
user: { id: user.id, name: user.name, email: user.email },
token,
});
} catch (error) {
console.error("Registration error:", error);
res.status(500).json({
Expand All @@ -32,15 +53,31 @@ router.post("/register", async (req, res) => {

// POST /api/auth/login - Login user
router.post("/login", async (req, res) => {
const { email, password } = req.body;
try {
// TODO: Implement the login logic
// 1. Validate the input
if (!email || !password)
return res.status(400).json({ error: "Email and password required" });
// 2. Check if the user exists
const user = await prisma.user.findUnique({ where: { email } });
if (!user)
return res.status(400).json({ error: "Invalid Email or Password" });
// 3. Compare the password
const isValid = await bcrypt.compare(password, user.password);
if (!isValid)
return res.status(400).json({ error: "Invalid Email or Password" });
// 4. Generate a JWT token
const token = jwt.sign(
{ userId: user.id, email: user.email },
process.env.JWT_SECRET,
{ expiresIn: "24h" }
);
// 5. Return the user data and token


res.json({
user: { id: user.id, name: user.name, email: user.email },
token,
});
} catch (error) {
console.error("Login error:", error);
res.status(500).json({
Expand Down
2 changes: 1 addition & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { authenticateToken } from "./middleware/auth.js";

// Initialize Express app
const app = express();
const PORT = process.env.PORT || 3000;
const PORT = process.env.PORT || 4000;

// Middleware
app.use(cors()); // Enable CORS for all routes
Expand Down