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 303168d commit 33a0642
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
const express = require('express');
const app = express();
const dotenv = require('dotenv');
dotenv.config();
const booksRouter = require('./books');
const cors = require('cors');
app.use(cors());
dotenv.config();
const allowedOrigins = ['https://peterwalker.xyz'];

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();
}
});

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

// Store your API key securely in an environment variable
const API_KEY = process.env.API_KEY || 'API_KEY not defined';

// Middleware to log requests to the terminal
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});

// Route for the root URL '/'
app.get('/', (req, res) => {
res.send('Hi from api.peterwalker.xyz');
Expand All @@ -34,12 +40,6 @@ if (isProduction) {
const https = require('https');
const fs = require('fs');

app.use(
cors({
origin: 'https://peterwalker.xyz',
}),
);

const options = {
key: fs.readFileSync(
'/etc/letsencrypt/live/api.peterwalker.xyz/privkey.pem',
Expand Down

0 comments on commit 33a0642

Please sign in to comment.