-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
356 lines (304 loc) · 11.8 KB
/
Copy pathserver.js
File metadata and controls
356 lines (304 loc) · 11.8 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
const express = require('express');
const { Pool } = require('pg');
const bcrypt = require('bcryptjs');
const cors = require('cors');
const path = require('path');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.static(path.join(__dirname)));
// Database connection
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false
});
// Initialize database tables
async function initDB() {
try {
await pool.query(`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
is_creator BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS posts (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
author VARCHAR(50) NOT NULL,
user_email VARCHAR(255),
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
image TEXT,
category VARCHAR(50) DEFAULT 'general',
views INTEGER DEFAULT 0,
likes INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS replies (
id SERIAL PRIMARY KEY,
post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
author VARCHAR(50) NOT NULL,
user_email VARCHAR(255),
content TEXT NOT NULL,
image TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS reviews (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
name VARCHAR(50) NOT NULL,
user_email VARCHAR(255),
text TEXT NOT NULL,
rating INTEGER NOT NULL CHECK (rating >= 1 AND rating <= 5),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS post_likes (
id SERIAL PRIMARY KEY,
post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
UNIQUE(post_id, user_id)
)
`);
console.log('Database tables initialized');
} catch (err) {
console.error('Error initializing database:', err);
}
}
// Creator email
const CREATOR_EMAIL = 'maxwitanowski@gmail.com';
// Auth Routes
app.post('/api/auth/signup', async (req, res) => {
try {
const { name, email, password } = req.body;
// Check if user exists
const existingUser = await pool.query('SELECT * FROM users WHERE LOWER(email) = LOWER($1)', [email]);
if (existingUser.rows.length > 0) {
return res.status(400).json({ error: 'Email already registered' });
}
// Hash password
const hashedPassword = await bcrypt.hash(password, 10);
const isCreator = email.toLowerCase() === CREATOR_EMAIL.toLowerCase();
// Create user
const result = await pool.query(
'INSERT INTO users (name, email, password, is_creator) VALUES ($1, $2, $3, $4) RETURNING id, name, email, is_creator, created_at',
[name.trim(), email.toLowerCase().trim(), hashedPassword, isCreator]
);
res.json({ success: true, user: result.rows[0] });
} catch (err) {
console.error('Signup error:', err);
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/auth/signin', async (req, res) => {
try {
const { email, password } = req.body;
const result = await pool.query('SELECT * FROM users WHERE LOWER(email) = LOWER($1)', [email]);
if (result.rows.length === 0) {
return res.status(400).json({ error: 'Invalid email or password' });
}
const user = result.rows[0];
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) {
return res.status(400).json({ error: 'Invalid email or password' });
}
// Update is_creator status
user.is_creator = user.email.toLowerCase() === CREATOR_EMAIL.toLowerCase();
res.json({
success: true,
user: {
id: user.id,
name: user.name,
email: user.email,
is_creator: user.is_creator,
created_at: user.created_at
}
});
} catch (err) {
console.error('Signin error:', err);
res.status(500).json({ error: 'Server error' });
}
});
// Posts Routes
app.get('/api/posts', async (req, res) => {
try {
const { category, sort, userId } = req.query;
let query = 'SELECT * FROM posts';
const params = [];
if (category && category !== 'all') {
query += ' WHERE category = $1';
params.push(category);
}
if (sort === 'popular') {
query += ' ORDER BY likes DESC, created_at DESC';
} else if (sort === 'views') {
query += ' ORDER BY views DESC, created_at DESC';
} else {
query += ' ORDER BY created_at DESC';
}
const result = await pool.query(query, params);
// Get user's likes if userId provided
let userLikes = [];
if (userId) {
const likesResult = await pool.query('SELECT post_id FROM post_likes WHERE user_id = $1', [userId]);
userLikes = likesResult.rows.map(r => r.post_id);
}
// Get replies for each post and mark if user liked it
for (let post of result.rows) {
const replies = await pool.query('SELECT * FROM replies WHERE post_id = $1 ORDER BY created_at ASC', [post.id]);
post.replies = replies.rows;
post.userLiked = userLikes.includes(post.id);
}
res.json(result.rows);
} catch (err) {
console.error('Get posts error:', err);
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/posts', async (req, res) => {
try {
const { userId, author, userEmail, title, content, image, category } = req.body;
const result = await pool.query(
'INSERT INTO posts (user_id, author, user_email, title, content, image, category) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING *',
[userId, author, userEmail, title, content, image || null, category || 'general']
);
result.rows[0].replies = [];
res.json(result.rows[0]);
} catch (err) {
console.error('Create post error:', err);
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/posts/:id/view', async (req, res) => {
try {
await pool.query('UPDATE posts SET views = views + 1 WHERE id = $1', [req.params.id]);
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/posts/:id/like', async (req, res) => {
try {
const { userId } = req.body;
const postId = req.params.id;
// Check if already liked
const existing = await pool.query('SELECT * FROM post_likes WHERE post_id = $1 AND user_id = $2', [postId, userId]);
if (existing.rows.length > 0) {
// Unlike
await pool.query('DELETE FROM post_likes WHERE post_id = $1 AND user_id = $2', [postId, userId]);
await pool.query('UPDATE posts SET likes = likes - 1 WHERE id = $1', [postId]);
res.json({ liked: false });
} else {
// Like
await pool.query('INSERT INTO post_likes (post_id, user_id) VALUES ($1, $2)', [postId, userId]);
await pool.query('UPDATE posts SET likes = likes + 1 WHERE id = $1', [postId]);
res.json({ liked: true });
}
} catch (err) {
console.error('Like error:', err);
res.status(500).json({ error: 'Server error' });
}
});
app.delete('/api/posts/:id', async (req, res) => {
try {
const { userEmail } = req.body;
// Only creator can delete
if (userEmail.toLowerCase() !== CREATOR_EMAIL.toLowerCase()) {
return res.status(403).json({ error: 'Not authorized' });
}
await pool.query('DELETE FROM posts WHERE id = $1', [req.params.id]);
res.json({ success: true });
} catch (err) {
console.error('Delete post error:', err);
res.status(500).json({ error: 'Server error' });
}
});
// Replies Routes
app.post('/api/posts/:id/replies', async (req, res) => {
try {
const { userId, author, userEmail, content, image } = req.body;
const postId = req.params.id;
const result = await pool.query(
'INSERT INTO replies (post_id, user_id, author, user_email, content, image) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *',
[postId, userId, author, userEmail, content, image || null]
);
res.json(result.rows[0]);
} catch (err) {
console.error('Create reply error:', err);
res.status(500).json({ error: 'Server error' });
}
});
app.delete('/api/replies/:id', async (req, res) => {
try {
const { userEmail } = req.body;
// Only creator can delete
if (userEmail.toLowerCase() !== CREATOR_EMAIL.toLowerCase()) {
return res.status(403).json({ error: 'Not authorized' });
}
await pool.query('DELETE FROM replies WHERE id = $1', [req.params.id]);
res.json({ success: true });
} catch (err) {
console.error('Delete reply error:', err);
res.status(500).json({ error: 'Server error' });
}
});
// Reviews Routes
app.get('/api/reviews', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM reviews ORDER BY created_at DESC');
res.json(result.rows);
} catch (err) {
console.error('Get reviews error:', err);
res.status(500).json({ error: 'Server error' });
}
});
app.post('/api/reviews', async (req, res) => {
try {
const { userId, name, userEmail, text, rating } = req.body;
const result = await pool.query(
'INSERT INTO reviews (user_id, name, user_email, text, rating) VALUES ($1, $2, $3, $4, $5) RETURNING *',
[userId, name, userEmail, text, rating]
);
res.json(result.rows[0]);
} catch (err) {
console.error('Create review error:', err);
res.status(500).json({ error: 'Server error' });
}
});
app.delete('/api/reviews/:id', async (req, res) => {
try {
const { userEmail } = req.body;
// Only creator can delete
if (userEmail.toLowerCase() !== CREATOR_EMAIL.toLowerCase()) {
return res.status(403).json({ error: 'Not authorized' });
}
await pool.query('DELETE FROM reviews WHERE id = $1', [req.params.id]);
res.json({ success: true });
} catch (err) {
console.error('Delete review error:', err);
res.status(500).json({ error: 'Server error' });
}
});
// Serve index.html for root
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Start server
app.listen(PORT, async () => {
console.log(`Server running on port ${PORT}`);
await initDB();
});