forked from Workintech/mini-twitter-x-mock-api-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.mjs
442 lines (360 loc) · 9.81 KB
/
server.mjs
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import express from "express";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import { nanoid } from "nanoid";
// Import the tweets data in required format
// import tweets.json from data/tweets.json and init server with that seed data
import tweetsData from "./data/tweets.json" assert { type: "json" };
const app = express();
const PORT = process.env.PORT || 3001;
// Middleware to parse JSON requests
app.use(express.json());
// In-memory data storage
const users = [];
const tokens = [];
function initializePredefinedUsers() {
const predefinedUsers = [
{
id: nanoid(5),
username: "Ephraim21",
password: "l_dxA27E49g6pIy",
email: "[email protected]",
},
{
id: nanoid(5),
username: "Lloyd27",
password: "IESEqL_B87wrgR5",
email: "[email protected]",
},
{
id: nanoid(5),
username: "Tatum_Schneider",
password: "oaZSxaOPcQfzhF6",
email: "[email protected]",
},
];
predefinedUsers.forEach(async (user) => {
// Hash the password
const hashedPassword = await bcrypt.hash(user.password, 10);
const token = jwt.sign({ id: user.id }, "SECRET_KEY", {
expiresIn: "12h",
// Generate and store the token
});
tokens.push(token);
// Store the user with hashed password
const updatedUser = {
...user,
hashedPassword,
token,
};
users.push(updatedUser);
console.log("Predefined user:", updatedUser);
});
console.log("Predefined users initialized successfully.");
}
// Initialize predefined users
initializePredefinedUsers();
console.log("Predefined users:", users);
// ----------------------
// Sample Route
// ----------------------
// Sample route to test the server
app.get("/", (req, res) => {
res.send("Hello, Workintech Student! Mini Twitter X API Server is running");
});
// Register endpoint
app.post("/profile/register", async (req, res) => {
const { username, password, email } = req.body;
// Check if user already exists
const existingUser = users.find(
(user) => user.username === username || user.email === email
);
if (existingUser) {
return res
.status(400)
.json({ status: "error", message: "Username or email already exists." });
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = {
id: nanoid(5),
username,
email,
password,
hashedPassword,
};
users.push(newUser);
res.json({
status: "success",
message: "User registered successfully.",
data: {
id: newUser.username,
username: newUser.username,
email: newUser.email,
},
});
});
// Login endpoint
app.post("/profile/login", async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const user = users.find((u) => u.username === username);
if (!user || !(await bcrypt.compare(password, user.hashedPassword))) {
return res
.status(400)
.json({ status: "error", message: "Invalid username or password." });
}
const token = jwt.sign({ id: user.id }, "SECRET_KEY", {
expiresIn: "12h",
});
tokens.push(token);
res.json({
status: "success",
message: "Login successful.",
token,
});
});
// Logout endpoint
app.post("/profile/logout", (req, res) => {
const { token } = req.body;
const index = tokens.indexOf(token);
if (index === -1) {
return res.status(400).json({ status: "error", message: "Invalid token." });
}
tokens.splice(index, 1);
res.json({
status: "success",
message: "Logged out successfully.",
});
});
//----------------------
// Tweet Routes
//----------------------
// Middleware to authenticate token
const authenticateToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
/* console.log(
"request Token",
tokens,
`${token?.slice(0, 5)}...${token?.slice(token?.length - 5)}, ${token}`
); */
if (!token)
return res
.status(401)
.json({ status: "error", message: "Token not provided." });
jwt.verify(token, "SECRET_KEY", (err, user) => {
if (err)
return res
.status(403)
.json({ status: "error", message: "Invalid token." });
req.user = user;
next();
});
};
// In-memory data storage
const tweets = [...tweetsData];
// Get all tweets
app.post("/tweet", authenticateToken, (req, res) => {
const { content } = req.body;
const newTweet = {
id: nanoid(5),
userId: req.user.username,
content,
likes: 0,
retweets: 0,
replies: [],
};
tweets.push(newTweet);
res.json({
status: "success",
message: "Tweet posted successfully.",
data: newTweet,
});
});
// get all tweets
app.get("/tweet", authenticateToken, (req, res) => {
res.json({
status: "success",
message: "Tweets retrieved successfully.",
data: tweets,
});
});
// Get a single tweet
app.get("/tweet/:id", authenticateToken, (req, res) => {
const tweetId = req.params.id;
console.log(tweetId);
const tweet = tweets.find((t) => t.id === tweetId.toString());
if (!tweet) {
return res
.status(404)
.json({ status: "error", message: "Tweet not found." });
}
res.json({
status: "success",
message: "Tweet retrieved successfully.",
data: tweet,
});
});
// Edit a tweet
app.put("/tweet/:id", authenticateToken, (req, res) => {
const tweetId = req.params.id;
const { content } = req.body;
const tweet = tweets.find((t) => t.id === tweetId);
if (!tweet) {
return res
.status(404)
.json({ status: "error", message: "Tweet not found." });
}
tweet.content = content;
res.json({
status: "success",
message: "Tweet updated successfully.",
data: tweet,
});
});
// Delete a tweet
app.delete("/tweet/:id", authenticateToken, (req, res) => {
const tweetId = req.params.id;
const tweet = tweets.find((t) => t.id === tweetId);
if (!tweet) {
return res
.status(404)
.json({ status: "error", message: "Tweet not found." });
// Check if the user is the owner of the tweet
if (tweet.username !== req.user.username) {
return res.status(403).json({
status: "error",
message: "You are not authorized to delete this tweet.",
});
}
}
const index = tweets.indexOf(tweet);
tweets.splice(index, 1);
res.json({
status: "success",
message: "Tweet deleted successfully.",
});
});
// Like a tweet
app.post("/tweet/like/:id", authenticateToken, (req, res) => {
const tweetId = req.params.id;
const tweet = tweets.find((t) => t.id === tweetId);
if (!tweet) {
return res
.status(404)
.json({ status: "error", message: "Tweet not found." });
}
tweet.likes = tweet.likes + 1;
res.json({
status: "success",
message: "Tweet liked successfully.",
});
});
// Unlike a tweet
app.delete("/tweet/like/:id", authenticateToken, (req, res) => {
const tweetId = req.params.id;
const tweet = tweets.find((t) => t.id === tweetId);
if (!tweet) {
return res
.status(404)
.json({ status: "error", message: "Tweet not found." });
}
tweet.likes = tweet.likes > 0 ? tweet.likes - 1 : 0;
res.json({
status: "success",
message: "Tweet unliked successfully.",
});
});
// Reply to a tweet
app.post("/tweet/reply/:id", authenticateToken, (req, res) => {
const tweetId = req.params.id;
const { content, username } = req.body;
const tweet = tweets.find((t) => t.id === tweetId);
if (!tweet) {
return res
.status(404)
.json({ status: "error", message: "Tweet not found." });
}
// Create a new tweet for the reply
const reply = {
id: `${tweetId}__${nanoid(5)}`,
content,
likes: 0,
retweets: 0,
username,
};
tweet.replies.push(reply);
tweets.push(reply);
res.json({
status: "success",
message: "Tweet replied successfully.",
});
});
// Delete a reply
app.delete("/tweet/reply/:replyid", authenticateToken, (req, res) => {
const replyId = req.params.replyid;
const tweetId = req.params.replyid.split("__")[0];
const tweet = tweets.find((t) => t.id === tweetId);
if (!tweet) {
return res
.status(404)
.json({ status: "error", message: "Tweet not found." });
}
const reply = tweet.replies.find((r) => r.id === replyId);
if (!reply) {
return res
.status(404)
.json({ status: "error", message: "Reply not found." });
}
tweet.replies = tweet.replies.filter((r) => r.id !== replyId);
res.json({
status: "success",
message: "Reply deleted successfully.",
});
});
// Retweet a tweet
app.post("/tweet/retweet/:id", authenticateToken, (req, res) => {
const tweetId = req.params.id;
const { username } = req.body;
console.log(tweetId, username);
const originalTweet = tweets.find((t) => t.id === tweetId);
if (!originalTweet) {
return res
.status(404)
.json({ status: "error", message: "Tweet not found." });
}
// Check if the user has already retweeted
const userRetweet = tweets.find(
(t) => t.retweetedFrom === tweetId && t.username === username
);
if (userRetweet) {
return res.status(400).json({
id: userRetweet.id,
status: "error",
message: "User has already retweeted this tweet.",
});
}
originalTweet.retweets += 1;
// Create a new tweet for the retweet
const retweet = {
id: nanoid(5),
content: originalTweet.content, // Copying content from original tweet
likes: 0,
retweets: 0,
replies: [],
username, // The user who retweeted
retweetedFrom: originalTweet.id, // Reference to the original tweet
};
tweets.push(retweet);
res.json({
status: "success",
message: "Tweet retweeted successfully.",
});
});
// Start the server
app.listen(PORT, () => {
console.log(
`Mini Twitter X API Server is running on http://localhost:${PORT}`
);
});