-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
74 lines (59 loc) · 2.06 KB
/
Copy pathindex.js
File metadata and controls
74 lines (59 loc) · 2.06 KB
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
const express = require('express');
const cors = require('cors');
const path = require('path');
const session = require('express-session');
require('dotenv').config();
const app = express();
// Trust proxy for correct secure cookie handling behind reverse proxies (e.g., Nginx, cloud)
app.set('trust proxy', 1);
// Set view engine to EJS
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'public/views'));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Session middleware
app.use(session({
secret: process.env.JWT_SECRET || 'keyboard cat',
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production', // Only secure in production (HTTPS)
sameSite: 'lax' // Helps with cross-site issues
}
}));
// Auth middleware
function ensureSignedIn(req, res, next) {
if (req.session && req.session.user) {
return next();
}
// If API, send 401. If page, redirect to login
if (req.path.startsWith('/api/')) {
return res.status(401).json({ error: 'Not signed in' });
}
res.redirect('/');
}
// Serve static files from 'public'
app.use('/public', express.static(path.join(__dirname, 'public')));
// Route `/` renders index.ejs
app.get('/', (req, res) => {
res.render('index');
});
// Route `/dashboard` renders dashboard.ejs (protected)
app.get('/dashboard', ensureSignedIn, (req, res) => {
res.render('dashboard', { username: req.session.user });
});
// Settings page (protected)
app.get('/settings', ensureSignedIn, (req, res) => {
res.render('settings', { username: req.session.user });
});
// Auth routes (login sets session)
app.use('/api/auth', require('./routes/auth'));
// Events API (protected)
app.use('/api/events', ensureSignedIn, require('./routes/events'));
// Settings API (protected)
app.use('/api/settings', ensureSignedIn, require('./routes/settings'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
// Start the event watcher (runs in the same process)
require('./utils/eventWatcher');