-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
241 lines (209 loc) · 7.25 KB
/
Copy pathapp.js
File metadata and controls
241 lines (209 loc) · 7.25 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
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
require('dotenv').config();
const Sentry = require('@sentry/node');
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV || 'development',
tracesSampleRate: process.env.NODE_ENV === 'production' ? 0.2 : 1.0
});
const express = require('express');
const helmet = require('helmet');
const session = require('express-session');
const pgSession = require('connect-pg-simple')(session);
const { Pool } = require('pg');
const app = express();
const path = require('path');
const axios = require('axios');
const logger = require('./config/logger');
const supabase = require('./config/database');
// Import routes
const authRoutes = require('./routes/auth');
const portfolioRoutes = require('./routes/portfolio');
const apiRoutes = require('./routes/api');
// In-memory cache to store API data
const cache = {
coins: null,
lastFetch: 0,
};
// Cache duration: 5 minutes in milliseconds
const CACHE_DURATION = 5 * 60 * 1000;
// Security headers
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", "cdn.jsdelivr.net", "cdnjs.cloudflare.com"],
styleSrc: ["'self'", "'unsafe-inline'", "fonts.googleapis.com", "cdnjs.cloudflare.com"],
fontSrc: ["'self'", "fonts.gstatic.com", "cdnjs.cloudflare.com"],
imgSrc: ["'self'", "data:", "assets.coingecko.com", "coin-images.coingecko.com"],
connectSrc: ["'self'", "api.coingecko.com"]
}
}
}));
// Trust reverse proxy (Vercel, Heroku, etc.) so req.secure reflects HTTPS correctly.
// Without this, express-session skips Set-Cookie when cookie.secure=true,
// because Express sees internal HTTP and thinks the connection is not secure.
app.set('trust proxy', 1);
// Middleware
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Session middleware — uses PostgreSQL store in production, in-memory for tests
const sessionConfig = {
secret: process.env.SESSION_SECRET || 'fallback-secret-key',
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production',
httpOnly: true,
maxAge: 7 * 24 * 60 * 60 * 1000
}
};
if (process.env.DATABASE_URL) {
const pgPool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false }
});
sessionConfig.store = new pgSession({
pool: pgPool,
tableName: 'sessions',
createTableIfMissing: true
});
}
app.use(session(sessionConfig));
// Make user available to all views
app.use((req, res, next) => {
res.locals.user = req.session.user || null;
next();
});
// Routes
app.use('/auth', authRoutes);
app.use('/portfolio', portfolioRoutes);
app.use('/api', apiRoutes);
// Home page
app.get('/', async (req, res) => {
try {
const now = Date.now();
if (cache.coins && (now - cache.lastFetch < CACHE_DURATION)) {
logger.info('Serving homepage data from cache');
return res.render('index', { coins: cache.coins });
}
logger.info('Fetching fresh homepage data from CoinGecko API');
const response = await axios.get('https://api.coingecko.com/api/v3/coins/markets', {
params: {
vs_currency: 'usd',
order: 'market_cap_desc',
per_page: 12,
page: 1,
sparkline: false,
price_change_percentage: '24h'
},
});
const coins = response.data || [];
cache.coins = coins;
cache.lastFetch = now;
return res.render('index', { coins });
} catch (error) {
logger.error(`Homepage CoinGecko fetch failed: ${error.message}`);
if (cache.coins) {
logger.warn('CoinGecko API error — serving stale cache for homepage');
return res.render('index', { coins: cache.coins });
}
return res.status(500).send('Internal Server Error');
}
});
app.get('/dashboard', async (req, res) => {
try {
const now = Date.now();
let coins = [];
if (cache.coins && (now - cache.lastFetch < CACHE_DURATION)) {
coins = cache.coins;
} else {
const response = await axios.get('https://api.coingecko.com/api/v3/coins/markets', {
params: { vs_currency: 'usd', order: 'market_cap_desc', per_page: 10, page: 1, sparkline: false }
});
coins = response.data || [];
cache.coins = coins;
cache.lastFetch = now;
}
let watchlist = [];
if (req.session.user) {
const { data } = await supabase
.from('watchlist')
.select('*')
.eq('user_id', req.session.user.id)
.order('added_at', { ascending: true });
watchlist = data || [];
if (watchlist.length > 0) {
// Build price map from already-fetched top 10 coins
const topPrices = {};
coins.forEach(c => {
topPrices[c.id] = {
current_price: c.current_price,
price_change_percentage_24h: c.price_change_percentage_24h
};
});
// Fetch prices for watchlist coins not in top 10
const missing = watchlist
.filter(w => !topPrices[w.coin_id])
.map(w => w.coin_id);
let extraPrices = {};
if (missing.length > 0) {
try {
const priceRes = await axios.get('https://api.coingecko.com/api/v3/simple/price', {
params: {
ids: missing.join(','),
vs_currencies: 'usd',
include_24hr_change: true
}
});
Object.entries(priceRes.data).forEach(([id, val]) => {
extraPrices[id] = {
current_price: val.usd,
price_change_percentage_24h: val.usd_24h_change
};
});
} catch (e) {
logger.warn('Watchlist supplemental price fetch failed: ' + e.message);
}
}
// Merge prices into watchlist rows
watchlist = watchlist.map(w => {
const p = topPrices[w.coin_id] || extraPrices[w.coin_id] || {};
return Object.assign({}, w, {
current_price: p.current_price != null ? p.current_price : null,
price_change_percentage_24h: p.price_change_percentage_24h != null ? p.price_change_percentage_24h : null
});
});
}
}
res.render('dashboard', { coins, watchlist });
} catch (error) {
logger.error(`Dashboard fetch failed: ${error.message}`);
res.render('dashboard', { coins: [], watchlist: [] });
}
});
app.get("/graphs", (req, res) => {
res.render("graphs");
});
app.get('/home', (req, res) => {
res.redirect('/');
});
app.get('/news', (req, res) => {
res.redirect('https://coinmarketcap.com/headlines/news/');
});
app.get('/about', (req, res) => {
res.render('partials/about');
});
app.get('/markets', (req, res) => {
res.render('partials/markets');
});
Sentry.setupExpressErrorHandler(app);
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
logger.info(`Server running at http://localhost:${PORT}`);
});
}
module.exports = app;