-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
243 lines (216 loc) · 7.4 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
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
242
243
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const NodeCache = require('node-cache');
const https = require('https');
const fs = require('fs');
const app = express();
app.use(cors({
origin: '*',
methods: ['GET', 'POST', 'DELETE', 'UPDATE', 'PUT', 'PATCH'],
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(bodyParser.json());
const JWT_SECRET = 'BJH03C89x2BNJ3Ie'; // Replace with a secure, randomly generated key
const pool = mysql.createPool({
host: 'localhost',
user: 'advokati_shortcuts',
password: 'advokati_shortcuts',
database: 'advokati_shortcuts',
connectionLimit: 10
});
const shortcutCache = new NodeCache({ stdTTL: 86400, checkperiod: 3600 }); // Cache for 24 hours, check every hour
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) {
console.log('No token provided');
return res.sendStatus(401);
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
console.log('Token verification failed:', err);
return res.sendStatus(403);
}
req.user = user;
next();
});
}
// Enhanced login endpoint with better error handling and logging
app.post('/login', async (req, res) => {
console.log('Login request received:', {
username: req.body?.username ? '(provided)' : '(missing)',
password: req.body?.password ? '(provided)' : '(missing)',
headers: req.headers
});
try {
// Input validation
const { username, password } = req.body;
if (!username || !password) {
console.log('Missing credentials:', { username: !!username, password: !!password });
return res.status(400).json({
error: 'Username and password are required',
details: 'Both fields must be provided'
});
}
// Database query with timeout
const query = 'SELECT * FROM users WHERE username = ?';
const queryPromise = new Promise((resolve, reject) => {
pool.query(query, [username], (err, results) => {
if (err) {
console.error('Database query error:', err);
reject(new Error('Database error'));
return;
}
resolve(results);
});
});
// Add timeout to query
const results = await Promise.race([
queryPromise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Database timeout')), 5000)
)
]);
console.log('Query completed. Results found:', results.length > 0);
if (results.length === 0) {
console.log('No user found for username:', username);
return res.status(401).json({
error: 'Invalid credentials',
details: 'User not found'
});
}
const user = results[0];
// Password validation with timeout
const validationPromise = bcrypt.compare(password, user.password);
const isValidPassword = await Promise.race([
validationPromise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Password validation timeout')), 5000)
)
]);
console.log('Password validation completed:', isValidPassword);
if (!isValidPassword) {
return res.status(401).json({
error: 'Invalid credentials',
details: 'Incorrect password'
});
}
// Generate JWT
const token = jwt.sign({
id: user.id,
username: user.username,
iat: Math.floor(Date.now() / 1000)
}, JWT_SECRET, {
expiresIn: '24h'
});
// Send successful response
console.log('Login successful for user:', username);
res.json({
token,
user_id: user.id,
message: 'Login successful'
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({
error: 'Internal server error',
details: error.message
});
}
});
app.post('/addShortcut', authenticateToken, (req, res) => {
const { user_id, shortcut, expansion } = req.body;
console.log('Received addShortcut request:', { user_id, shortcut, expansion });
const query = 'INSERT INTO shortcuts (user_id, shortcut, expansion) VALUES (?, ?, ?)';
pool.query(query, [user_id, shortcut, expansion], (err, result) => {
if (err) {
console.error('Database error:', err);
res.status(500).json({ error: err.message });
} else {
console.log('Shortcut added successfully');
shortcutCache.del(`shortcuts_${user_id}`); // Invalidate cache
res.json({ message: 'Shortcut added successfully', id: result.insertId });
}
});
});
app.get('/getShortcuts/:user_id', authenticateToken, (req, res) => {
const { user_id } = req.params;
const cacheKey = `shortcuts_${user_id}`;
const cachedShortcuts = shortcutCache.get(cacheKey);
if (cachedShortcuts) {
return res.json(cachedShortcuts);
}
console.log('Received request for shortcuts, user_id:', user_id);
const query = 'SELECT id, shortcut, expansion FROM shortcuts WHERE user_id = ?';
pool.query(query, [user_id], (err, results) => {
if (err) {
console.error('Database error:', err);
res.status(500).json({ error: err.message });
} else {
console.log('Sending shortcuts:', results);
shortcutCache.set(cacheKey, results, 86400); // Cache for 24 hours
res.json(results);
}
});
});
app.put('/updateShortcut', authenticateToken, (req, res) => {
const { id, user_id, shortcut, expansion } = req.body;
console.log('Received updateShortcut request:', { id, user_id, shortcut, expansion });
const query = 'UPDATE shortcuts SET shortcut = ?, expansion = ? WHERE id = ? AND user_id = ?';
pool.query(query, [shortcut, expansion, id, user_id], (err, result) => {
if (err) {
console.error('Database error:', err);
res.status(500).json({ error: err.message });
} else {
console.log('Shortcut updated successfully');
shortcutCache.del(`shortcuts_${user_id}`); // Invalidate cache
res.json({ message: 'Shortcut updated successfully' });
}
});
});
app.delete('/deleteShortcut/:id', authenticateToken, (req, res) => {
const { id } = req.params;
const { user_id } = req.query;
console.log('Received deleteShortcut request:', { id, user_id });
const query = 'DELETE FROM shortcuts WHERE id = ? AND user_id = ?';
pool.query(query, [id, user_id], (err, result) => {
if (err) {
console.error('Database error:', err);
res.status(500).json({ error: err.message });
} else {
console.log('Shortcut deleted successfully');
shortcutCache.del(`shortcuts_${user_id}`); // Invalidate cache
res.json({ message: 'Shortcut deleted successfully' });
}
});
});
app.post('/verifyToken', authenticateToken, (req, res) => {
res.sendStatus(200);
});
const PORT = process.env.PORT || 3222;
const options = {
key: fs.readFileSync('key.key'),
cert: fs.readFileSync('crt.crt'),
ca: [
fs.readFileSync('chain.pem'),
fs.readFileSync('isrgrootx1.pem'),
fs.readFileSync('r10.pem')
]
};
https.createServer(options, app).listen(PORT, () => {
console.log(`HTTPS Server running on port ${PORT}`);
});
// Check database connection
pool.getConnection((err, connection) => {
if (err) {
console.error('Error connecting to the database:', err);
return;
}
console.log('Successfully connected to the database');
connection.release();
});