-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
231 lines (201 loc) · 8.25 KB
/
server.js
File metadata and controls
231 lines (201 loc) · 8.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
const express = require('express');
const bcrypt = require('bcrypt');
const cors = require('cors');
const session = require('express-session');
const pool = require('./db');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const app = express();
const port = 3000;
const uploadDir = 'public/uploads';
if (!fs.existsSync(uploadDir)){
fs.mkdirSync(uploadDir, { recursive: true });
}
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, uploadDir);
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
// --- CORS Setup (MUST be before session) ---
app.use(cors({
origin: 'http://localhost:3000',
credentials: true
}));
app.use(express.json());
// --- Session Middleware Setup (MUST be after CORS) ---
app.use(session({
secret: 'weds-deed-edas-rgff-rgvf',
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000,
sameSite: 'lax'
}
}));
// Serve static files with cache control for HTML
app.use(express.static('public', {
setHeaders: (res, path) => {
if (path.endsWith('.html')) {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
}
}
}));
// --- Middleware to prevent caching ---
function noCache(req, res, next) {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, private');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
next();
}
// --- Auth Routes ---
app.post('/api/register', async (req, res) => {
try {
const { username, password } = req.body;
const userCheck = await pool.query('SELECT * FROM users WHERE username = $1', [username]);
if (userCheck.rows.length > 0) {
return res.status(400).json({ success: false, message: 'Username already exists' });
}
const saltRounds = 10;
const passwordHash = await bcrypt.hash(password, saltRounds);
const newUser = await pool.query(
'INSERT INTO users (username, password_hash) VALUES ($1, $2) RETURNING id, username',
[username, passwordHash]
);
console.log(`[SERVER] User registered: ${newUser.rows[0].username}`);
res.status(201).json({ success: true, message: 'User registered successfully', user: newUser.rows[0] });
} catch (err) {
console.error('[SERVER] Register Error:', err.message);
res.status(500).json({ success: false, message: 'Server error during registration' });
}
});
app.post('/api/login', async (req, res) => {
try {
const { username, password } = req.body;
const result = await pool.query('SELECT * FROM users WHERE username = $1', [username]);
const user = result.rows[0];
if (!user) {
return res.status(401).json({ success: false, message: 'Invalid username or password' });
}
const isMatch = await bcrypt.compare(password, user.password_hash);
if (isMatch) {
req.session.user = { id: user.id, username: user.username };
console.log(`[SERVER] User logged in: ${user.username}`);
res.json({ success: true, message: 'Login successful!', user: { id: user.id, username: user.username } });
} else {
res.status(401).json({ success: false, message: 'Invalid username or password' });
}
} catch (err) {
console.error('[SERVER] Login Error:', err.message);
res.status(500).json({ success: false, message: 'Server error during login' });
}
});
app.post('/api/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
return res.status(500).json({ success: false, message: 'Could not log out.' });
}
res.clearCookie('connect.sid');
console.log('[SERVER] User logged out.');
res.json({ success: true, message: 'Logged out successfully.' });
});
});
app.get('/api/session', noCache, (req, res) => {
if (req.session.user) {
res.json({ success: true, user: req.session.user });
} else {
res.status(401).json({ success: false, message: 'Not authenticated' });
}
});
// --- Product Routes ---
app.get('/api/products', noCache, async (req, res) => {
try {
const allProducts = await pool.query('SELECT * FROM products_sold ORDER BY date_sold DESC, product_id DESC');
res.json(allProducts.rows);
} catch (err) {
console.error('[SERVER] Get Products Error:', err.message);
res.status(500).json({ success: false, message: 'Server error fetching products' });
}
});
app.post('/api/products', noCache, upload.single('productImage'), async (req, res) => {
try {
const { productId, productName, quantity, manufacturer, dateSold, unitPrice } = req.body;
const imagePath = req.file ? path.join('uploads', req.file.filename).replace(/\\/g, '/') : null;
if (!productId || !productName || !quantity || !dateSold || !unitPrice) {
return res.status(400).json({ success: false, message: 'Please provide all required fields.' });
}
const newProduct = await pool.query(
`INSERT INTO products_sold (product_id, product_name, quantity, manufacturer, date_sold, unit_price, image_path)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING *`,
[productId, productName, quantity, manufacturer, dateSold, unitPrice, imagePath]
);
console.log(`[SERVER] New product added: ${newProduct.rows[0].product_name}`);
res.status(201).json({ success: true, message: 'Product added successfully', product: newProduct.rows[0] });
} catch (err) {
console.error('[SERVER] Add Product Error:', err.message);
res.status(500).json({ success: false, message: 'Server error while adding product' });
}
});
app.put('/api/products/:id', noCache, upload.single('productImage'), async (req, res) => {
try {
const { id } = req.params;
const { productName, quantity, manufacturer, dateSold, unitPrice } = req.body;
let imagePath = req.body.existingImagePath || null;
if (req.file) {
imagePath = path.join('uploads', req.file.filename).replace(/\\/g, '/');
}
const updateProduct = await pool.query(
`UPDATE products_sold
SET product_name = $1, quantity = $2, manufacturer = $3, date_sold = $4, unit_price = $5, image_path = $6
WHERE product_id = $7
RETURNING *`,
[productName, quantity, manufacturer, dateSold, unitPrice, imagePath, id]
);
if (updateProduct.rows.length === 0) {
return res.status(404).json({ success: false, message: 'Product not found.' });
}
console.log(`[SERVER] Product updated: ${updateProduct.rows[0].product_name}`);
res.json({ success: true, message: 'Product updated successfully', product: updateProduct.rows[0] });
} catch (err) {
console.error('[SERVER] Update Product Error:', err.message);
res.status(500).json({ success: false, message: 'Server error while updating product' });
}
});
app.delete('/api/products/:id', noCache, async (req, res) => {
try {
const { id } = req.params;
const productResult = await pool.query('SELECT image_path FROM products_sold WHERE product_id = $1', [id]);
if (productResult.rows.length === 0) {
return res.status(404).json({ success: false, message: 'Product not found.' });
}
const imagePath = productResult.rows[0].image_path;
const deleteOp = await pool.query('DELETE FROM products_sold WHERE product_id = $1 RETURNING product_name', [id]);
if (imagePath) {
const fullImagePath = path.join(__dirname, 'public', imagePath);
fs.unlink(fullImagePath, (err) => {
if (err) {
console.error(`[SERVER] Failed to delete image file: ${fullImagePath}`, err);
} else {
console.log(`[SERVER] Deleted image file: ${fullImagePath}`);
}
});
}
console.log(`[SERVER] Product deleted: ${deleteOp.rows[0].product_name}`);
res.json({ success: true, message: 'Product deleted successfully.' });
} catch (err) {
console.error('[SERVER] Delete Product Error:', err.message);
res.status(500).json({ success: false, message: 'Server error while deleting product' });
}
});
app.listen(port, () => {
console.log(`[SERVER] Server is running on http://localhost:${port}`);
});