Skip to content

Commit

Permalink
add stricter cors
Browse files Browse the repository at this point in the history
  • Loading branch information
petertimwalker committed May 28, 2024
1 parent 33a0642 commit 488f5f7
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,29 @@ const booksRouter = require('./books');
const cors = require('cors');
const allowedOrigins = ['https://peterwalker.xyz'];

// Middleware to check origin and reject if not allowed
app.use((req, res, next) => {
const origin = req.headers.origin;
console.log(
`${req.method} ${req.url}: ${allowedOrigins.indexOf(origin) !== -1}`,
);
if (allowedOrigins.indexOf(origin) === -1) {
res.status(403).send('Access forbidden: Origin not allowed');
} else {
next();
console.log(`Request origin: ${origin}`);
if (allowedOrigins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
next();
});

// CORS configuration
app.use(cors({
origin: (origin, callback) => {
if (!origin) {
return callback(new Error('Origin not specified'), false);
}
if (allowedOrigins.indexOf(origin) === -1) {
return callback(new Error('Not allowed by CORS'), false);
}
return callback(null, true);
}
}));

const isProduction = process.env.NODE_ENV === 'production';
const PORT = isProduction ? 443 : 3001;

Expand Down

0 comments on commit 488f5f7

Please sign in to comment.