-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
192 lines (166 loc) · 5.7 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
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const bcrypt = require('bcrypt');
const { MongoClient } = require('mongodb');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const forumsFilePath = path.join(__dirname, 'data', 'forums.json');
const forumIdFilePath = path.join(__dirname, 'data', 'forumId.json');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function connectToDatabase() {
try {
await client.connect();
console.log('Connected to MongoDB');
} catch (err) {
console.error('Error connecting to MongoDB:', err);
}
}
connectToDatabase();
// Define MongoDB collections for users
const db = client.db('forumDB');
const usersCollection = db.collection('users');
// Ensure data directory and file exist
if (!fs.existsSync(path.join(__dirname, 'data'))) {
fs.mkdirSync(path.join(__dirname, 'data'));
}
// Initialize forumId from file or set to 1 if file doesn't exist
let forumId = 1;
if (fs.existsSync(forumIdFilePath)) {
forumId = parseInt(fs.readFileSync(forumIdFilePath, 'utf8'));
} else {
fs.writeFileSync(forumIdFilePath, forumId.toString());
}
// Inject API_KEY into the rendered HTML
app.get('/home', (req, res) => {
res.render('home', { apiKey: process.env.API_KEY });
});
// Get all forums
app.get('/forums', (req, res) => {
fs.readFile(forumsFilePath, (err, data) => {
if (err) {
res.status(500).send('Error reading forum data.');
return;
}
res.json(JSON.parse(data));
});
});
// Post a new forum
app.post('/forums', (req, res) => {
const { title, description } = req.body;
fs.readFile(forumsFilePath, (err, data) => {
if (err) {
res.status(500).send('Error reading forum data.');
return;
}
const forums = JSON.parse(data);
const newForum = { id: forumId++, title, description, messages: [] };
forums.push(newForum);
fs.writeFile(forumsFilePath, JSON.stringify(forums, null, 2), (err) => {
if (err) {
res.status(500).send('Error saving forum data.');
return;
}
// Update forumId file with the new forumId
fs.writeFile(forumIdFilePath, forumId.toString(), (err) => {
if (err) {
console.error('Error updating forumId file:', err);
}
});
res.send('Forum created successfully.');
});
});
});
// Add a message to a forum
app.post('/forums/:id/messages', (req, res) => {
const { message } = req.body;
const { id } = req.params;
fs.readFile(forumsFilePath, 'utf8', (err, data) => {
if (err) {
res.status(500).send('Error reading forum data.');
return;
}
let forums = JSON.parse(data);
const forum = forums.find(f => f.id == id);
if (forum) {
if (!forum.messages) {
forum.messages = [];
}
forum.messages.push(message);
fs.writeFile(forumsFilePath, JSON.stringify(forums, null, 2), (err) => {
if (err) {
res.status(500).send('Error updating forum data.');
return;
}
res.send('Message added successfully.');
});
} else {
res.status(404).send('Forum not found.');
}
});
});
// Get messages of a forum
app.get('/forums/:id/messages', (req, res) => {
const { id } = req.params;
fs.readFile(forumsFilePath, 'utf8', (err, data) => {
if (err) {
res.status(500).send('Error reading forum data.');
return;
}
const forums = JSON.parse(data);
const forum = forums.find(f => f.id == id);
if (forum) {
const messages = forum.messages || [];
res.json(messages);
} else {
res.status(404).send('Forum not found.');
}
});
});
// Register endpoint
app.post('/register', async (req, res) => {
const { username, password } = req.body;
try {
// Check if username already exists
const existingUser = await usersCollection.findOne({ username });
if (existingUser) {
return res.status(400).send('Username already exists');
}
// Hash password and save user to database
const hashedPassword = await bcrypt.hash(password, 10);
await usersCollection.insertOne({ username, password: hashedPassword });
res.send('Registration successful');
} catch (err) {
console.error('Error registering user:', err);
res.status(500).send('Registration failed');
}
});
// Login endpoint
app.post('/login', async (req, res) => {
const { username, password } = req.body;
try {
// Find user by username
const user = await usersCollection.findOne({ username });
if (!user) {
return res.status(401).send('Invalid username or password');
}
// Compare passwords
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
return res.status(401).send('Invalid username or password');
}
res.send('Login successful');
} catch (err) {
console.error('Error logging in user:', err);
res.status(500).send('Login failed');
}
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}/html/index.html`);
});