-
Notifications
You must be signed in to change notification settings - Fork 1
/
indexjsCopy.js
311 lines (255 loc) · 8.65 KB
/
indexjsCopy.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
//using Express
const express = require('express');
const cors = require('cors');
const { default: mongoose } = require('mongoose');
require('dotenv').config();
const User = require('./models/User');
const Post = require('./models/Post');
const Category = require('./models/Category');
const bcrypt = require('bcryptjs');
const app = express();
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const multer = require('multer');
const uploadMiddleware = multer({
dest: 'uploads/',
limits: { fileSize: 40 * 1024 * 1024, },
});
//to rename file
const fs = require('fs');
// to encrypt password
const salt = bcrypt.genSaltSync(10);
// for jwt
const secret = process.env.SECRET;
app.use(cors({ credentials: true, origin: 'http://localhost:3000' }));
app.use(express.json());
app.use(cookieParser());
app.use('/uploads', express.static(__dirname + '/uploads')); //this method serves files (like images, stylesheets, scripts, etc.) directly to the client without needing to create explicit routes for each file. Instead, you define a single route that serves static files from a designated directory.
//connecting MongoDB
const mongodbURI = process.env.MONGODB_URI;
mongoose.connect(mongodbURI);
//register
app.post('/register', async (req, res) => {
const { username, password } = req.body;
//creating user
try {
//if username is unique, it will register a new user
const userDoc = await User.create({
username,
password: bcrypt.hashSync(password, salt),
});
res.json(userDoc);
} catch (e) {
//if user is not unique, exception
res.status(400).json(e);
}
});
//login
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const userDoc = await User.findOne({ username });
const passOk = bcrypt.compareSync(password, userDoc.password);
// Session / token
if (passOk) {
//logged in (response with json web token)
//creating token
jwt.sign({ username, id: userDoc._id }, secret, {}, (err, token) => {
if (err) throw err;
res.cookie('token', token).json({
id: userDoc._id,
username,
});
});
//in the above callback function, we get and error if there's an error and a token if no error
} else {
res.status(400).json('Wrong credentials.')
}
});
//profile
app.get('/profile', (req, res) => {
// getting token
const { token } = req.cookies;
jwt.verify(token, secret, {}, (err, info) => {
if (err) throw err;
res.json(info);
});
});
//logout
app.post('/logout', (req, res) => {
res.cookie('token', '').json('ok');
});
// create post
app.post('/post', uploadMiddleware.single('file'), async (req, res) => {
//to upload the file from req body, we will use Multer (a middleware used to handle files upload)
const { originalname, path } = req.file;
const parts = originalname.split('.');
const ext = parts[parts.length - 1];
const newPath = path + '.' + ext;
fs.renameSync(path, newPath);
//creating post in DB
//getting token so that we can get the user Id
const { token } = req.cookies;
jwt.verify(token, secret, {}, async (err, info) => {
if (err) throw err;
const { title, summary, category, content } = req.body;
const categoryDoc = await Category.findOne({ category_title: category });
if (!categoryDoc) {
return res.status(400).json('Category not found');
}
const postDoc = await Post.create({
title,
summary,
category: categoryDoc._id,
content,
coverImg: newPath,
author: info.id,
});
res.json(postDoc);
});
});
//display posts
app.get('/post', async (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = 10; // Adjust as needed
const skip = (page - 1) * limit;
const posts = await Post.find()
.populate('author', ['username'])
.sort({ createdAt: -1 })
.skip(skip)
.limit(limit)
.lean();
res.json(posts);
});
//single post page
app.get('/post/:id', async (req, res) => {
const { id } = req.params;
const postDoc = await Post.findById(id).populate('author', ['username']).populate('category', ['category_title']);
res.json(postDoc);
});
// navigation menu category listing
app.get('/category', async (req, res) => {
try {
const categories = await Category.find();
res.json(categories);
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
// Fetch category title by ID
app.get('/category/:categoryId', async (req, res) => {
const categoryId = req.params.categoryId;
try {
const category = await Category.findById(categoryId);
if (!category) {
return res.status(404).json('Category not found');
}
res.json(category.category_title);
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
// Fetch category posts
app.get('/:categoryId/posts', async (req, res) => {
const { categoryId } = req.params;
try {
const posts = await Post.find({ category: categoryId })
.populate('author', ['username'])
.populate('category', ['category_title']) // Populate the 'category' field
.lean();
if (!posts) {
return res.status(404).json('No posts found for this category');
}
res.json(posts);
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
// display profile's posts
app.get('/:userID/userPosts', async (req, res) => {
const userID = req.params.userID;
console.log('Requested userID:', userID);
try {
const posts = await Post.find({ author: userID })
.populate('author', ['username'])
.sort({ createdAt: -1 })
.lean();
res.json(posts);
} catch (error) {
console.error('Error fetching posts:', error);
res.status(500).json('Internal Server Error Oops!');
}
});
// display author posts
app.get('/profile/:authorID', async (req, res) => {
const authorID = req.params.authorID;
console.log('Requested authorID:', authorID);
try {
const posts = await Post.find({ author: authorID })
.populate('author', ['username'])
.sort({ createdAt: -1 })
.lean();
res.json(posts);
} catch (error) {
console.error('Error fetching posts:', error);
res.status(500).json('Internal Server Error Oops!');
}
})
// Editing Post
app.put('/post', uploadMiddleware.single('file'), async (req, res) => {
let newPath = null;
if (req.file) {
const { originalname, path } = req.file;
const parts = originalname.split('.');
const ext = parts[parts.length - 1];
newPath = path + '.' + ext;
fs.renameSync(path, newPath);
}
const { token } = req.cookies;
jwt.verify(token, secret, {}, async (err, info) => {
if (err) throw err;
const { id, title, summary, category, content } = req.body;
const postDoc = await Post.findById(id);
const isAuthor = JSON.stringify(postDoc.author) === JSON.stringify(info.id);
if (!isAuthor) {
return res.status(400).json('You are not the Author');
}
// Update the document fields
postDoc.title = title;
postDoc.summary = summary;
postDoc.category = category;
postDoc.content = content;
if (newPath) {
postDoc.coverImg = newPath;
}
// Save the updated document
await postDoc.save();
res.json(postDoc);
});
});
// delete post
app.delete('/post/:id', async (req, res) => {
const postId = req.params.id;
const { token } = req.cookies;
try {
jwt.verify(token, secret, {}, async (err, info) => {
if (err) throw err;
const postDoc = await Post.findById(postId);
if (!postDoc) {
return res.status(404).json('Post not found');
}
const isAuthor = JSON.stringify(postDoc.author) === JSON.stringify(info.id);
if (!isAuthor) {
return res.status(400).json('You are not the Author');
}
await Post.findByIdAndRemove(postId);
res.json('Post deleted successfully');
});
} catch (error) {
console.error('Error:', error);
res.status(500).json('Internal Server Error');
}
});
app.listen(4000);