-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.mjs
296 lines (214 loc) · 6.95 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
import express from "express"
import path from 'path';
import cors from 'cors';
import mongoose from "mongoose"
import cookieParser from "cookie-parser";
import authApis from './routes/auth.mjs'
import productApis from './routes/product.mjs';
import jwt from 'jsonwebtoken';
import {
stringToHash,
varifyHash,
} from "bcrypt-inzi"
import { userModel,otpModel,tweetModel } from './routes/dbmodels.mjs'
import sgMail from "@sendgrid/mail"
const SECRET = process.env.SECRET || "mySecret"
const app = express()
const port = process.env.PORT || 3000
const mongodbURI = process.env.mongodbURI || "mongodb+srv://admin:admin123@cluster0.vpuj8pq.mongodb.net/mydatabase?retryWrites=true&w=majority"
mongoose.connect(mongodbURI);
app.use(express.json());
app.use(cookieParser())
app.use(cors({
origin: ['http://localhost:3001', '*'],
credentials: true
}));
app.use('/api/v1', authApis)
app.use('/api/v1',(req, res, next) => {
console.log("req.cookies: ", req.cookies);
if (!req?.cookies?.Token) {
res.status(401).send({
message: "include http-only credentials with every request"
})
return;
}
jwt.verify(req.cookies.Token, SECRET, function (err, decodedData) {
if (!err) {
console.log("decodedData: ", decodedData);
const nowDate = new Date().getTime() / 1000;
if (decodedData.exp < nowDate) {
res.status(401);
res.cookie('Token', '', {
maxAge: 1,
httpOnly: true
});
res.send({ message: "token expired" })
} else {
console.log("token approved");
req.body.token = decodedData
next();
}
} else {
res.status(401).send("invalid token")
}
});
})
app.use("/api/v1",productApis)
const getUser = async (req, res) => {
let _id = "";
if (req.params.id) {
_id = req.params.id
} else {
_id = req.body.token._id
}
try {
const user = await userModel.findOne({ _id: _id }, "email firstName lastName -_id profileImage createdOn password coverPhoto").exec()
if (!user) {
res.status(404).send({})
return;
} else {
res.status(200).send(user)
}
} catch (error) {
console.log("error: ", error);
res.status(500).send({
message: "something went wrong on server",
});
}
}
app.get('/api/v1/profile', getUser)
app.get('/api/v1/profile/:id', getUser)
app.post('/api/v1/change-password', async (req, res) => {
try {
const body = req.body;
const currentPassword = body.currentPassword;
const newPassword = body.password;
const _id = req.body.token._id
// check if user exist
const user = await userModel.findOne(
{ _id: _id },
"password",
).exec()
if (!user) throw new Error("User not found")
const isMatched = await varifyHash(currentPassword, user.password)
if (!isMatched) throw new Error("Invalid Password")
const newHash = await stringToHash(newPassword);
await userModel.updateOne({ _id: _id }, { password: newHash }).exec()
// success
res.send({
message: "password changed success",
});
return;
} catch (error) {
console.log("error: ", error);
res.status(500).send(error.message)
}
})
app.post("/api/v1/updateProfileImg", async (req, res) =>{
try{
const body = req.body;
const _id = req.body.token._id;
const profileImage = body.profileImage
const email = req.body.token.email
const user = await userModel.findOne(
{ _id: _id },
"profileImage",
).exec()
const userTweets = await userModel.findOne(
{ _id: _id },
"profilePhoto",
).exec()
if (!user && !userTweets) throw new Error("User not found")
await userModel.updateOne({ _id: _id }, { profileImage: profileImage }).exec()
await tweetModel.updateMany({ email: email }, { profilePhoto: profileImage }).exec()
res.send({
message: "profile image changed success",
});
return;
}
catch (error) {
console.log("error: ", error);
res.status(500).send(error.message)
}
})
app.post("/api/v1/uploadCoverPhoto", async (req, res) =>{
try{
const body = req.body;
const _id = req.body.token._id;
const coverPhoto = body.coverPhoto
const user = await userModel.findOne(
{ _id: _id },
"coverPhoto",
).exec()
if (!user) throw new Error("User not found")
await userModel.updateOne({ _id: _id }, { coverPhoto: coverPhoto }).exec()
res.send({
message: "cover image changed success",
});
return;
}
catch (error) {
console.log("error: ", error);
res.status(500).send(error.message)
}
})
app.put("/api/v1/deleteCoverPhoto", async (req, res) =>{
try{
const body = req.body;
const _id = req.body.token._id;
const user = await userModel.findOne(
{ _id: _id },
).exec()
if (!user){
throw new Error("User not found")
}
else{
let data = await userModel.findByIdAndUpdate(_id,
{
coverPhoto: "",
},
{ new: true }
).exec();
console.log('updated: ', data);
res.send({
message: "cover image remove success",
});
}
return;
}
catch (error) {
console.log("error: ", error);
res.status(500).send(error.message)
}
})
app.delete('/api/v1/deleteAccount/:deleteAccountEmail', (req, res) => {
const email = req.params.deleteAccountEmail
userModel.deleteOne({
email: email,
owner: new mongoose.Types.ObjectId(req.body.token._id)
}, (err, deletedData) => {
console.log("deleted: ", deletedData);
if (!err) {
if (deletedData.deletedCount !== 0) {
res.send({
message: "Account has been deleted successfully",
})
} else {
res.status(404);
res.send({
message: "No Account found with this email: " + email,
});
}
} else {
res.status(500).send({
message: "server error"
})
}
});
})
const __dirname = path.resolve();
app.use('/', express.static(path.join(__dirname, './product/build')))
app.use('*', express.static(path.join(__dirname, './product/build')))
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})