-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
486 lines (445 loc) · 16.8 KB
/
app.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
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
const express = require('express');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const path = require('path');
const app = express();
const env = require('dotenv').config()
const PORT = process.env.PORT || 3000;
const JWT_SECRET = 'your_jwt_secret';
const multer = require('multer');
const Post = require('./models/Post')
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
mongoose.connect(`mongodb+srv://zubalana0:${process.env.password}@cluster0.z7w5ka9.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0`)
.then(()=>{
console.log(`Connected to mongo DB`)
})
const userSchema = new mongoose.Schema({
firstname: { type: String, required: true },
lastName: { type: String },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
profileDescription: { type: String },
placesVisited: { type: String },
placesToVisit: { type: String },
profilePicture: { type: String },
followers: { type: [String], default: [] },
followings: { type: [String], default: [] }
});
const User = mongoose.model('User', userSchema);
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(express.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//user registraion
app.post('/auth/register', upload.single('profile-pic'), async (req, res) => {
const { firstname, lastName, email, password, profileDescription, placesVisited, placesToVisit } = req.body;
const profilePicture = req.file ? `uploads/${req.file.filename}` : null; // Ensure the path is correctly set
try {
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ message: 'User with this email already exists' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({
firstname,
lastName,
email,
profileDescription,
placesVisited,
placesToVisit,
password: hashedPassword,
profilePicture
});
await user.save();
res.status(201).json({ message: 'User created successfully' });
} catch (error) {
console.error('Error saving user:', error);
res.status(400).json({ message: error.message || 'User already exists or other error' });
}
});
//user log in
app.post('/auth/login', async (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ message: 'Email and password are required' });
}
try {
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ message: 'Invalid credentials' });
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(400).json({ message: 'Invalid credentials' });
}
const token = jwt.sign({ userId: user._id }, JWT_SECRET, { expiresIn: '72h' });
const secureFlag = process.env.NODE_ENV === 'production';
res.cookie('token', token, { httpOnly: true, secure: secureFlag });
res.status(200).json({ message: 'Logged in successfully' });
} catch (error) {
console.error('Error during login:', error);
res.status(500).json({ message: 'An error occurred during login' });
}
});
//user logout
app.post('/auth/logout', (req, res) => {
res.clearCookie('token');
res.status(200).json({ message: 'Logged out successfully' });
});
//middleware
const authMiddleware = (req, res, next) => {
const token = req.cookies.token;
if (!token) {
return res.status(401).json({ message: 'Unauthorized' });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.userId = decoded.userId;
next();
} catch (error) {
res.status(401).json({ message: 'Unauthorized' });
}
};
//follow a user
app.post('/api/follow/:id', authMiddleware, async (req, res) => {
const userIdToFollow = req.params.id;
const userId = req.userId;
try {
const userToFollow = await User.findById(userIdToFollow);
const currentUser = await User.findById(userId);
if (!userToFollow || !currentUser) {
return res.status(404).json({ message: 'User not found' });
}
if (userToFollow.followers.includes(userId)) {
return res.status(400).json({ message: 'You already follow this user' });
}
userToFollow.followers.push(userId);
currentUser.followings.push(userIdToFollow);
await userToFollow.save();
await currentUser.save();
res.status(200).json({ message: 'Successfully followed the user' });
} catch (error) {
res.status(500).json({ message: 'An error occurred while following the user', error: error.message });
}
});
//unfollow a user
app.post('/api/unfollow/:id', authMiddleware, async (req, res) => {
const userIdToUnfollow = req.params.id;
const userId = req.userId;
try {
const userToUnfollow = await User.findById(userIdToUnfollow);
const currentUser = await User.findById(userId);
if (!userToUnfollow || !currentUser) {
return res.status(404).json({ message: 'User not found' });
}
if (!userToUnfollow.followers.includes(userId)) {
return res.status(400).json({ message: 'You do not follow this user' });
}
userToUnfollow.followers.pull(userId);
currentUser.followings.pull(userIdToUnfollow);
await userToUnfollow.save();
await currentUser.save();
res.status(200).json({ message: 'Successfully unfollowed the user' });
} catch (error) {
res.status(500).json({ message: 'An error occurred while unfollowing the user', error: error.message });
}
});
//check following
app.get('/api/checkFollow/:userId', authMiddleware, async (req, res) => {
const { userId } = req.params;
try {
const currentUser = await User.findById(req.userId);
const isFollowing = currentUser.followings.includes(userId);
res.status(200).json({ isFollowing });
} catch (error) {
console.error('Error checking follow status:', error);
res.status(500).json({ message: 'Error checking follow status' });
}
});
//get the user's info
app.get('/auth/user', authMiddleware, async (req, res) => {
try {
const user = await User.findById(req.userId);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json(user);
} catch (error) {
console.error('Error fetching user data:', error);
res.status(500).json({ message: 'An error occurred while fetching user data' });
}
});
//get all the user's posts
app.get('/api/userPosts', authMiddleware, async (req, res) => {
try {
const targetUserId = req.query.userId;
const userPosts = await Post.find({ author: targetUserId }).populate('author', 'firstname lastName profilePicture');
res.status(200).json(userPosts);
} catch (err) {
res.status(500).json({ message: 'Error when getting user posts', error: err.message });
}
});
//get all the user's posts
app.get('/api/authUserPosts', authMiddleware, async (req, res) => {
try {
const targetUserId = req.userId;
const userPosts = await Post.find({ author: targetUserId }).populate('author', 'firstname lastName profilePicture');
res.status(200).json(userPosts);
} catch (err) {
res.status(500).json({ message: 'Error when getting user posts', error: err.message });
}
});
//post creation
app.post('/api/posts', authMiddleware, upload.single('post-pic'), async (req, res) => {
try {
const { title, body, hashtags } = req.body;
const pic = req.file ? req.file.path : null;
const newPost = new Post({
title,
body,
pic,
hashtags,
author: req.userId
});
await newPost.save();
res.status(201).json(newPost);
} catch (err) {
res.status(500).json({ message: 'Post creation failed', error: err.message });
}
});
//get all the posts
app.get('/api/getPosts', async (req, res) => {
try {
const posts = await Post.find().populate('author', 'firstname lastName profilePicture');
res.status(200).json(posts);
} catch (err) {
res.status(500).json({ message: 'Error when getting posts', error: err.message });
}
});
//get all the users
app.get('/api/getUser', async (req, res) => {
try {
const users = await User.find();
res.status(200).json(users);
} catch (err) {
console.error('Error when getting users:', err);
res.status(500).json({ message: 'Error when getting users', error: err.message });
}
});
//fetch multiple users by their IDs
app.post('/api/getUsersByIds', authMiddleware, async (req, res) => {
const { ids } = req.body;
try {
const users = await User.find({ _id: { $in: ids } }, 'firstname lastName profilePicture');
res.status(200).json(users);
} catch (error) {
console.error('Error fetching users:', error);
res.status(500).json({ message: 'An error occurred while fetching users' });
}
});
//edit user
app.post('/auth/user/update', authMiddleware, upload.single('profilePicture'), async (req, res) => {
try {
const updates = {
firstname: req.body.firstname,
lastName: req.body.lastName,
email: req.body.email,
profileDescription: req.body.profileDescription,
placesVisited: req.body.placesVisited,
placesToVisit: req.body.placesToVisit
};
if (req.file) {
updates.profilePicture = `uploads/${req.file.filename}`;
}
const user = await User.findByIdAndUpdate(req.userId, updates, { new: true });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json(user);
} catch (error) {
console.error('Error updating user data:', error);
res.status(500).json({ message: 'An error occurred while updating user data' });
}
});
//get a specific post by ID
app.get('/api/userPosts/:id', authMiddleware, async (req, res) => {
const postId = req.params.id;
try {
const post = await Post.findById(postId).populate('author', 'firstname lastName profilePicture');
if (!post) {
return res.status(404).json({ message: 'Post not found' });
}
res.status(200).json(post);
} catch (error) {
console.error('Error fetching post data:', error);
res.status(500).json({ message: 'An error occurred while fetching post data' });
}
});
//edit post
app.post('/api/userPosts/:id', authMiddleware, upload.single('postPicture'), async (req, res) => {
const postId = req.params.id;
const updates = {
title: req.body.title,
body: req.body.body,
hashtags: req.body.hashtags
};
if (req.file) {
updates.pic = `uploads/${req.file.filename}`;
}
try {
const post = await Post.findByIdAndUpdate(postId, updates, { new: true });
if (!post) {
return res.status(404).json({ message: 'Post not found' });
}
res.status(200).json(post);
} catch (error) {
console.error('Error updating post data:', error);
res.status(500).json({ message: 'An error occurred while updating post data' });
}
});
//like post
app.post('/api/likePost', authMiddleware, (req, res) => {
const { postId } = req.body;
Post.findByIdAndUpdate(postId, { $addToSet: { likes: req.userId } }, { new: true })
.then(post => {
res.json({ likesCount: post.likes.length, userLiked: true });
})
.catch(err => res.status(500).send('Error liking the post.'));
});
//unlike post
app.post('/api/unlikePost', authMiddleware, (req, res) => {
const { postId } = req.body;
Post.findByIdAndUpdate(postId, { $pull: { likes: req.userId } }, { new: true })
.then(post => {
res.json({ likesCount: post.likes.length, userLiked: false });
})
.catch(err => res.status(500).send('Error unliking the post.'));
});
//get user liked posts
app.get('/api/userLikedPosts/:userId', (req, res) => {
const userId = req.params.userId;
Post.find({ likes: userId })
.populate('author', 'firstname lastName profilePicture')
.exec((err, likedPosts) => {
if (err) return res.status(500).send(err);
res.status(200).json(likedPosts);
});
});
//auth
app.get('/auth', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'auth.html'));
});
//main
app.get('/', (req, res)=>{
res.sendFile(__dirname, 'public', 'index.html')
})
//user
app.get('/user', authMiddleware, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'user.html'));
});
//get user info by ID
app.get('/auth/user/:id', authMiddleware, async (req, res) => {
try {
const userId = req.params.id;
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.status(200).json(user);
} catch (error) {
console.error('Error fetching user data:', error);
res.status(500).json({ message: 'An error occurred while fetching user data' });
}
});
//logout
app.post('/auth/logout', (req, res) => {
res.clearCookie('token');
res.status(200).json({ message: 'Logged out successfully' });
});
//post deleting
app.delete('/api/deletePost/:id', authMiddleware, async (req, res) => {
const postId = req.params.id;
try {
const post = await Post.findById(postId);
if (!post) {
return res.status(404).json({ message: 'Post not found' });
}
if (post.author.toString() !== req.userId) {
return res.status(403).json({ message: 'Unauthorized to delete this post' });
}
await Post.findByIdAndDelete(postId);
res.status(200).json({ message: 'Post deleted successfully' });
} catch (error) {
res.status(500).json({ message: 'An error occurred while deleting the post', error: error.message });
}
});
//user deleting
app.delete('/api/deleteUser/:id', async (req, res) => {
const userId = req.params.id;
try {
const user = await User.findById(userId);
await User.findByIdAndDelete(user);
res.status(200).json({ message: 'User deleted successfully' });
} catch (error) {
res.status(500).json({ message: 'An error occurred while deleting the user', error: error.message });
}
});
//post deleting (admin)
app.delete('/api/deletePostAdmin/:id', async (req, res) => {
const postId = req.params.id;
try {
const post = await Post.findById(postId);
if (!post) {
return res.status(404).json({ message: 'Post not found' });
}
if (post.author.toString() !== req.userId) {
return res.status(403).json({ message: 'Unauthorized to delete this post' });
}
await Post.findByIdAndDelete(postId);
res.status(200).json({ message: 'Post deleted successfully' });
} catch (error) {
res.status(500).json({ message: 'An error occurred while deleting the post', error: error.message });
}
});
//followers removing
app.delete('/api/removeFollower/:id', authMiddleware, async (req, res) => {
const followerId = req.params.id;
const userId = req.userId;
try {
const user = await User.findById(userId);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
if (!user.followers.includes(followerId)) {
return res.status(400).json({ message: 'This user is not a follower' });
}
user.followers.pull(followerId);
await user.save();
const followerUser = await User.findById(followerId);
if (followerUser) {
followerUser.followings.pull(userId);
await followerUser.save();
}
res.status(200).json({ message: 'Follower removed successfully' });
} catch (error) {
res.status(500).json({ message: 'An error occurred while removing follower', error: error.message });
}
});
//admin
app.get('/admin', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});
app.listen(PORT, ()=>{
console.log(`Server works on PORT: ${PORT}`)
})