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: 32 additions & 1 deletion week-5/backend/db/index.js
Original file line number Diff line number Diff line change
@@ -1 +1,32 @@
// start writing from here
// start writing from here
import mongoose from 'mongoose';
import dotenv from 'dotenv';

dotenv.config();

const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI);
console.log('MongoDB connected successfully');
} catch (error) {
console.error('MongoDB connection failed:', error.message);
process.exit(1);
}
};

export default connectDB;

const userSchema = new mongoose.Schema({
username: { type: String, required: true , unique: true },
password: { type: String, required: true },
}, { timestamps: true });

const todoSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
title: { type: String, required: true },
completed: { type: Boolean, default: false },
}, { timestamps: true });

export const User = mongoose.model('User', userSchema);
export const Todo = mongoose.model('Todo', todoSchema);

31 changes: 30 additions & 1 deletion week-5/backend/index.js
Original file line number Diff line number Diff line change
@@ -1 +1,30 @@
// start writing from here
// start writing from here
import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import connectDB from './db/index.js';
import userRoutes from './routes/user.js';
import todoRoutes from './routes/todo.js';

dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.json());
app.use(cors({
origin: 'http://localhost:64128', // your frontend origin
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true
}));

connectDB();

app.get('/', (req, res) => {
res.send('Welcome to the Todo API');
});

app.use('/api/user', userRoutes);
app.use('/api/todo', todoRoutes);


app.listen(PORT, () => console.log('Server running on port 3000'));
32 changes: 31 additions & 1 deletion week-5/backend/middleware/user.js
Original file line number Diff line number Diff line change
@@ -1 +1,31 @@
// start writing from here
// start writing from here
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';

dotenv.config();
const SECRET = process.env.JWT_SECRET || 'default_secret';

/**
* Middleware to verify JWT token and authenticate user
*/
export const authenticateJwt = (req, res, next) => {
const authHeader = req.headers.authorization;

// ✅ 1. Check if Authorization header exists
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ message: 'Authorization header missing or malformed' });
}

const token = authHeader.split(' ')[1];

// ✅ 2. Verify the token
try {
const decoded = jwt.verify(token, SECRET);
req.userId = decoded.userId; // attach the decoded userId to the request
next();
} catch (error) {
return res.status(403).json({ message: 'Invalid or expired token' });
}
};

export { SECRET };
Loading