-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
288 lines (249 loc) · 9.19 KB
/
index.js
File metadata and controls
288 lines (249 loc) · 9.19 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
require('dotenv').config()
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
// Schema
const User = require('./Models/User');
const Post = require('./Models/Post');
const bcrypt = require('bcryptjs');
const salt = bcrypt.genSaltSync(10);
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
// Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files.
const multer = require('multer');
const uploadMiddleWare = multer({ dest: 'uploads/' })
// To change file extension to webp (file system)
const fs = require('fs'); // fs was not working
const sharp = require('sharp');
const { log, info } = require('console');
const PORT = process.env.port || 4000;
const MONGODB_URL = process.env.mongodb_url
const secret = process.env.secret;
const Base_Url = process.env.BASE_URL;
// console.log("Base", Base_Url);
const app = express();
// As we are using credentials
app.use( cors( {
origin: Base_Url,
credentials: true,
}));
app.use(express.json());
// We are using cookies to get to know if user is login
// If user is logged in we will show him his profile
app.use(cookieParser());
app.use('/uploads', express.static(__dirname + '/uploads'));
app.post('/register', async (req, res) => {
const {username, password} = req.body;
try{
// Create a new User
const userDocs = await User.create( {
username,
password :bcrypt.hashSync(password, salt),
} );
res.json( userDocs );
} catch (error){
res.status(400).json(error);
}
});
app.post('/login', async (req, res) => {
try{
const {username, password} = req.body;
// Create a new User
const userDoc = await User.findOne({
username: username,
})
if (!userDoc) {
// Handle the case where the user is not found
return res.status(400).json('User not found');
}
const passOk = bcrypt.compareSync(password, userDoc.password);
// res.json( passOk );
if (passOk){
jwt.sign( {username, id: userDoc._id}, secret, {}, (err, token) =>{
// console.log("UserId Login ", userDoc._id);
if (err) {
console.error('Login: Error:', err);
return res.status(401).json({ message: 'Login Jwt sign failed' });
};
res.cookie('token', token, { httpOnly: true, sameSite: 'None', secure: true }).json({
id: userDoc._id,
username,
});
});
}
else {
res.status(400).json('wrong credentials');
}
} catch (error){
res.status(400).json(error);
}
});
// We will take the cookie and show profile
app.get('/profile', (req, res) => {
const {token} = req.cookies;
if (!token) {
return res.status(401).json({ message: 'JWT must be provided' });
}
jwt.verify(token, secret, {}, (err, info) => {
if (err) {
console.error('JWT Verification Error:', err);
return res.status(401).json({ message: 'JWT verification failed' });
};
res.json(info);
});
});
// Here we are updating the cookie to null
app.post('/logout', (req, res) => {
res.cookie('token', '').json('ok');
});
// Route to create post
app.post('/post', uploadMiddleWare.single('file'), async (req, res) => {
// console.log('Received token at Create Post:', req.cookies.token); // Log the token
try {
// const {title, summary, content} = req.body;
// if (!req.file) {
// return res.status(400).json({ message: 'No file uploaded' });
// }
// We cant view the file bcoz it is either binary or uses an unsupported text encoding.
// We will change it to webp
const { originalname, path } = req.file;
const parts = originalname.split('.');
const ext = parts[parts.length - 1];
const newPath = path + '.webp';
// Use sharp to convert the image to WebP format
sharp(path)
.webp() // Convert to WebP format
.toFile(newPath, async (err, info) => {
if (err) {
console.error('Error converting to WebP:', err);
return res.status(500).send({ message: 'Error converting image' });
}
// Remove the original image file
fs.unlink(path, (err) => {
if (err) {
console.error('Error file:', err);
} else {
console.log('successfully.');
}
});
});
const {token} = req.cookies;
if (!token) {
return res.status(401).json({ message: 'Create Post :JWT must be provided' });
}
jwt.verify(token, secret, {}, async (err, info) => {
if (err) {
console.error('JWT Verification Error:', err);
return res.status(401).json({ message: 'Post Route:JWT verification failed' });
}
const { title, summary, content } = req.body;
// Create the Post document with the WebP path
const postDoc = await Post.create({
title,
summary,
content,
cover: newPath,
author: info.id,
});
res.json(postDoc);
});
} catch (error) {
console.error('Error:', error.message);
res.status(500).send({ message: error.message });
}
});
app.get('/post', async (req, res) => {
const postsData = await Post.find()
.populate('author', ['username'])
.sort({createdAt: -1})
.limit(20);
res.json(postsData);
});
app.get('/post/:id', async (req, res) =>{
const {id} = req.params;
try {
const postDoc = await Post.findById(id).populate('author', ['username']);
res.json(postDoc);
} catch (error) {
console.error('Error:', error.message);
res.status(500).send({ message: error.message });
}
})
// Route to Update the data
app.put('/post', uploadMiddleWare.single('file'), async(req, res) => {
// console.log('Received token at Update Post:', req.cookies.token); // Log the token
let newPath = null;
if(req.file){
const { originalname, path } = req.file;
const parts = originalname.split('.');
const ext = parts[parts.length - 1];
newPath = path + '.webp';
// Use sharp to convert the image to WebP format
sharp(path)
.webp() // Convert to WebP format
.toFile(newPath, async (err, info) => {
if (err) {
console.error('Error converting to WebP:', err);
return res.status(500).send({ message: 'Error converting image' });
}
// Remove the original image file
fs.unlinkSync(path);
});
}
const {token} = req.cookies;
// console.log('Update Token:', token); // Log the token
if (!token) {
return res.status(401).json({ message: 'Update Route:JWT must be provided' });
}
jwt.verify(token, secret, {}, async (err, info) => {
if (err) {
console.error('JWT Verification Error at Update Path:', err);
return res.status(401).json({ message: 'JWT verification failed at Update Route' });
}
try{
const { id, title, summary, 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');
}
await postDoc.updateOne({
title,
summary,
content,
cover: newPath ? newPath : postDoc.cover,
});
// res.json(postDoc);
res.json({ message: 'Post updated successfully', post: postDoc });
}catch (error) {
console.error('Error:', error.message);
res.status(500).json({ message: error.message });
}
});
});
app.delete('/post/:id', async (req, res) => {
try {
const {id} = req.params;
// console.log(id);
const result = await Post.findByIdAndDelete(id);
if( !result ) {
return res.status(404).json( {message: 'No post found'});
}
return res.status(200).send( {message : 'Post deleted successfully'});
} catch (error) {
console.log(error);
res.status(500).send({message : error.message})
}
})
mongoose
.connect(MONGODB_URL)
.then( () => {
console.log("App connected to database ");
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
})
})
.catch( (error) => {
console.log(error);
})
//