-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.js
191 lines (166 loc) · 5.6 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
require("dotenv").config();
const mongoose = require("mongoose");
const express = require("express");
const session = require("express-session");
const MongoStore = require('connect-mongo');
const helmet = require('helmet');
const csurf = require('csurf');
const User = require('./models/User');
const authRoutes = require("./routes/authRoutes");
const apiRoutes = require('./routes/apiRoutes');
const abTestRoutes = require('./routes/abTestRoutes');
const userRoutes = require('./routes/userRoutes');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const { redirectToLoginIfNotAuthenticated } = require('./routes/middleware/authMiddleware');
if (!process.env.DATABASE_URL || !process.env.SESSION_SECRET) {
console.error("Error: config environment variables not set. Please create/edit .env configuration file.");
process.exit(-1);
}
const app = express();
const port = process.env.PORT || 3000;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
const corsOptionsDelegate = async function (req, callback) {
let corsOptions;
if (req.path === '/api/tests/config' || req.path === '/api/tests/impression' || req.path === '/api/tests/track') {
const apiKey = req.method === 'OPTIONS' ? req.headers['access-control-request-headers'].split(',').find(header => header.trim().toLowerCase() === 'x-api-key') : (req.query.apiKey || (req.body && req.body.apiKey));
try {
if (req.method === 'OPTIONS') {
corsOptions = {
origin: true,
credentials: true,
methods: ['POST', 'GET', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'x-api-key', 'authorization'] // Add 'authorization' here
};
} else {
const user = await User.findOne({ apiKey });
if (user && user.allowedOrigins.includes(req.header('Origin'))) {
corsOptions = { origin: true, credentials: true };
} else {
corsOptions = { origin: false };
}
}
} catch (err) {
console.error(`Error during CORS configuration: ${err}`);
corsOptions = { origin: false };
}
} else {
corsOptions = { origin: false };
}
callback(null, corsOptions);
};
app.use(cors(corsOptionsDelegate));
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'", 'https://cdn.jsdelivr.net'],
styleSrc: ["'self'", "'unsafe-inline'", 'https:'],
imgSrc: ["'self'", 'data:', 'https:'],
connectSrc: ["'self'", 'wss:', 'https:', 'http:'],
fontSrc: ["'self'", 'https:', 'data:'],
mediaSrc: ["'self'"],
frameSrc: ["'self'"],
workerSrc: ["'self'", 'blob:'],
childSrc: ["'self'"],
formAction: ["'self'"],
upgradeInsecureRequests: [],
},
},
}));
app.use('/loader.js', (req, res, next) => {
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
next();
});
app.set("view engine", "ejs");
app.get('/loader.js', (req, res) => {
fs.readFile(path.join(__dirname, 'public', 'loader.js'), 'utf8', (err, data) => {
if (err) {
console.error('Error reading loader.js file:', err);
return res.status(500).send('Error serving loader script.');
}
const updatedData = data.replace('%%SERVER_URL%%', `https://${req.get('host')}`);
res.type('application/javascript').send(updatedData);
});
});
app.use(express.static("public"));
mongoose
.connect(process.env.DATABASE_URL)
.then(() => {
console.log("Database connected successfully");
})
.catch((err) => {
console.error(`Database connection error: ${err.message}`);
console.error(err.stack);
process.exit(1);
});
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: process.env.DATABASE_URL }),
cookie: { secure: false, httpOnly: true, sameSite: 'lax' }
}),
);
app.use(function (req, res, next) {
if (req.path === '/api/tests/track' || req.path === '/api/tests/config' || req.path === '/loader.js' || (req.path === '/api/tests/impression' && req.method === 'POST')) {
return next();
}
csurf()(req, res, next);
});
app.use(function (req, res, next) {
if (req.csrfToken) {
res.locals.csrfToken = req.csrfToken();
}
next();
});
app.on("error", (error) => {
console.error(`Server error: ${error.message}`);
console.error(error.stack);
});
app.use((req, res, next) => {
const sess = req.session;
res.locals.session = sess;
if (!sess.views) {
sess.views = 1;
console.log("Session created at: ", new Date().toISOString());
} else {
sess.views++;
console.log(
`Session accessed again at: ${new Date().toISOString()}, Views: ${sess.views}, User ID: ${sess.userId || '(unauthenticated)'}`
);
}
next();
});
app.use(authRoutes);
app.use('/api/tests/track', async (req, res, next) => {
const apiKey = req.body.apiKey;
if (!apiKey) {
return res.status(401).send('API Key is required');
}
const user = await User.findOne({ apiKey });
if (!user) {
return res.status(401).send('Invalid API Key');
}
next();
});
app.use(apiRoutes);
app.use(abTestRoutes);
app.use(userRoutes);
app.get("/", redirectToLoginIfNotAuthenticated, (req, res) => {
res.redirect("/tests/management");
});
app.use((req, res, next) => {
res.status(404).send("Page not found.");
});
app.use((err, req, res, next) => {
console.error(`Unhandled application error: ${err.message}`);
console.error(err.stack);
res.status(500).send("There was an error serving your request.");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});