Skip to content

Commit

Permalink
feat(security): implement CSRF protection middleware using csurf and …
Browse files Browse the repository at this point in the history
…add rate limiting to authentication routes using express-rate-limit
  • Loading branch information
harmeetsingh11 committed Jan 13, 2025
1 parent f2a3209 commit c92db5c
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,42 @@ const authRouter = require('./router/authRoute.js');
const databaseconnect = require('./config/databaseConfig.js');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const csrf = require('csurf');
const rateLimit = require('express-rate-limit');

// connect to db
// Initialize CSRF Protection
const csrfProtect = csrf({ cookie: true });

// Define a rate limiter
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.',
});

// Connect to DB
databaseconnect();

app.use(express.json()); // Built-in middleware
app.use(cookieParser()); // Third-party middleware
// Middleware
app.use(express.json());
app.use(cookieParser());
app.use(cors({ origin: [process.env.CLIENT_URL], credentials: true }));

app.use(cors({ origin: [process.env.CLIENT_URL], credentials: true })); //Third-party middleware
// Expose CSRF token to client
app.get('/csrf-token', csrfProtect, (req, res) => {
res.json({ csrfToken: req.csrfToken() });
});

// Auth router
app.use('/api/auth', authRouter);
// Auth routes
app.use('/api/auth', csrfProtect, limiter, authRouter);

// app.use('/', (req, res) => {
// res.status(200).json({ data: 'JWTauth server ;)' });
// });
// Global error handler
app.use((err, req, res, next) => {
if (err.code === 'EBADCSRFTOKEN') {
res.status(403).json({ error: 'Invalid CSRF token' });
} else {
res.status(500).json({ error: 'Something went wrong' });
}
});

module.exports = app;

0 comments on commit c92db5c

Please sign in to comment.