-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
259 lines (212 loc) · 8.09 KB
/
index.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
require('dotenv').config();
const express = require('express');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(cors({
origin: [
'http://localhost:5173', 'https://recoverly-e17ce.web.app', 'https://recoverly-e17ce.firebaseapp.com'],
credentials: true
}));
app.use(express.json());
app.use(cookieParser());
const verifyToken = (req, res, next) => {
const token = req.cookies?.token;
// console.log(`token inside verifyToken`, token)
if(!token) {
return res.status(401).send({ message: 'Unauthorized Access' });
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if(err) {
return res.status(401).send({ message: 'Unauthorized Access' });
}
req.user = decoded;
next();
})
}
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: process.env.NODE_ENV === "production" ? "none" : "strict",
};
//localhost:5000 and localhost:5173 are treated as same site. so sameSite value must be strict in development server. in production sameSite will be none
// in development server secure will false . in production secure will be true
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.oo5u4.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0`;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
// await client.connect();
// Send a ping to confirm a successful connection
// await client.db("admin").command({ ping: 1 });
const postCollection = client.db('Recoverly').collection("posts");
const userCollection = client.db('Recoverly').collection("users");
const recoveryCollection = client.db('Recoverly').collection("recoveries");
// auth related apis
app.post('/jwt', (req, res) => {
const user = req.body;
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: '5h'});
res.cookie('token', token, cookieOptions)
.send({success: true})
})
app.post("/logout", async (req, res) => {
const user = req.body;
console.log("logging out", user);
res
.clearCookie("token", { ...cookieOptions, maxAge: 0 })
.send({ success: true });
});
// recoveries api
app.post('/recoveries', async (req, res) => {
const newRecovery = req.body;
console.log('Adding new post', newRecovery)
const result = await recoveryCollection.insertOne(newRecovery);
res.send(result);
});
app.get('/recoveries', verifyToken, async (req, res) => {
console.log(`working`,req.cookies.token)
const cursor = recoveryCollection.find();
const result = await cursor.toArray();
res.send(result);
});
// posts api
app.post('/posts', verifyToken, async (req, res) => {
const newPost = req.body;
console.log(req.cookies.token)
console.log('Adding new post', newPost)
const result = await postCollection.insertOne(newPost);
res.send(result);
});
app.get('/posts/public', async (req, res) => {
const { title, location } = req.query;
const query = {};
if (title) {
query.title = { $regex: title, $options: "i" };
}
if (location) {
query.location = { $regex: location, $options: "i" };
}
try {
const result = await postCollection.find(query).toArray();
res.send(result);
} catch (error) {
console.error("Error fetching public posts:", error);
res.status(500).send({ error: "Internal Server Error" });
}
});
app.get('/posts', verifyToken, async (req, res) => {
const query = { user: req.user?.user }; // Filter by the authenticated user
try {
const result = await postCollection.find(query).toArray();
res.send(result);
} catch (error) {
console.error("Error fetching private posts:", error);
res.status(500).send({ error: "Internal Server Error" });
}
});
app.get('/posts/:id', verifyToken, async (req, res) => {
const id = req.params.id;
console.log('idk man',req.cookies?.token)
// Validate if `id` is a valid ObjectId
if (!ObjectId.isValid(id)) {
return res.status(400).send({ error: 'Invalid post ID' });
}
const query = { _id: new ObjectId(id) };
try {
const result = await postCollection.findOne(query);
if (!result) {
return res.status(404).send({ error: 'Post not found' });
}
res.send(result);
} catch (error) {
console.error("Error retrieving post:", error);
res.status(500).send({ error: "Internal Server Error" });
}
});
app.put('/posts/:id', verifyToken, async (req, res) => {
// console.log("update", req.cookies.token)
const id = req.params.id;
const updatedPost = req.body;
// Validate if `id` is a valid ObjectId
if (!ObjectId.isValid(id)) {
return res.status(400).send({ error: 'Invalid post ID' });
}
try {
const query = { _id: new ObjectId(id) };
const update = {
$set: updatedPost,
};
const result = await postCollection.updateOne(query, update);
if (result.modifiedCount > 0) {
res.send({ success: true, message: 'Post updated successfully' });
} else if (result.matchedCount > 0) {
res.send({ success: false, message: 'No changes made to the post' });
} else {
res.status(404).send({ success: false, message: 'Post not found' });
}
} catch (error) {
console.error("Error updating post:", error);
res.status(500).send({ error: "Internal Server Error" });
}
});
app.patch('/posts/:id', async (req, res) => {
const { id } = req.params;
const { status } = req.body;
try {
const result = await postCollection.updateOne(
{ _id: new ObjectId(id) },
{ $set: { status } }
);
if (result.modifiedCount === 1) {
res.send({ success: true, message: "Post status updated successfully" });
} else {
res.status(404).send({ success: false, message: "Post not found" });
}
} catch (error) {
console.error("Error updating post status:", error);
res.status(500).send({ success: false, error: "Internal Server Error" });
}
});
app.delete('/posts/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await postCollection.deleteOne(query);
res.send(result);
});
// user apis
app.post('/users', async (req, res) => {
const newUser = req.body;
console.log('creating new user', newUser);
const result = await userCollection.insertOne(newUser);
res.send(result);
});
app.get('/users/:email', verifyToken, async (req, res) => {
const email = req.params.email;
const query = { email: email };
const user = await userCollection.findOne(query);
res.send(user);
});
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when you finish/error
// await client.close();
}
}
run().catch(console.dir);
app.get('/', (req, res) => {
res.send('Lost n Found')
});
app.listen(port, () => {
console.log(`Losing stuff at ${port}`);
})