-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.js
358 lines (341 loc) · 12 KB
/
user.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
import { createError } from "../error.js";
import User from "../Models/User.js";
import Video from "../Models/Video.js";
import Photo from "../Models/Photo.js";
import Token from "../Models/Token.js";
import ResetToken from '../Models/ResetToken.js'
import sendEmail from "../sendEmail.js";
import emailTemplate from '../emailTemplate.js'
import crypto from 'crypto'
import bcrypt from "bcryptjs";
//in this page only mongodb crud operation is used
export const getUserForSignup = async (req, res, next) => {
try {
const user = await User.find({ name: req.body.name });
if (user.length > 0 ) res.status(200).json(true);
if (user.length <= 0) res.status(200).json(false);
} catch (error) {
console.log(error)
res.status(200, false)
}
}
export const getUserForSignupEmail = async (req, res, next) => {
try {
const user = await User.find({ email: req.body.email });
if (user.length > 0 ) res.status(200).json(true);
if (user.length <= 0) res.status(200).json(false);
} catch (error) {
console.log(error)
res.status(200, false)
}
}
export const update = async (req, res, next) => {
if (req.params.id === req.user.id) {
try {
const updatedUser = await User.findByIdAndUpdate(
req.params.id,
{
$set: req.body, //updating user
},
{ new: true } //this will show the updated user
);
res.status(200).json(updatedUser); //sending updated data to user
} catch (err) {
next(err);
}
} else {
return next(createError(403, "You can update only your account!"));
}
};
export const deleteUser = async (req, res, next) => {
try {
await User.findByIdAndDelete(req.params.id);
const photos = await Photo.find({ userId: req.params.id });
photos.deleteMany();
const videos = await Video.find({ userId: req.params.id });
videos.deleteMany();
res.status(200).json("User has been deleted.");
} catch (err) {
next(err);
}
};
export const getUser = async (req, res, next) => {
try {
const user = await User.findById(req.params.id);
var { password, ...others } = user._doc;
res.status(200).json(others);
} catch (err) {
next(err);
}
}
export const subscribe = async (req, res, next) => {
try {
await User.findByIdAndUpdate(req.user.id, {//getting user id to update its array
$push: { subscribedUsers: req.params.id }, //pushing the channel user id in subscribed array so that we can get which channel is subscibed by user //by using mongodb push operation
});
await User.findByIdAndUpdate(req.params.id, {
$inc: { subscribers: 1 },//updating subscriber count in channel id account //by using mongodb increment operation
});
res.status(200).json("Subscription successfull.")
} catch (err) {
next(err);
}
};
export const unsubscribe = async (req, res, next) => {
try {
try {
await User.findByIdAndUpdate(req.user.id, {
$pull: { subscribedUsers: req.params.id }, //pulling the channel user id in subscribed array so that we can get which channel is unsubscibed by user //by using mongodb pull operation
});
await User.findByIdAndUpdate(req.params.id, {
$inc: { subscribers: -1 }, //decreasing subscriber count
});
res.status(200).json("Unsubscription successfull.")
} catch (err) {
next(err);
}
} catch (err) {
next(err);
}
};
export const videoLike = async (req, res, next) => {
const id = req.user.id;
const videoId = req.params.videoId;
try {
await Video.findByIdAndUpdate(videoId, {
$addToSet: { likes: id }, //add to set so that a user can like a video only once
$pull: { dislikes: id } //removing id from dislike if a person likes video
})
res.status(200).json("The video has been liked.")
} catch (err) {
next(err);
}
}
export const videoDislike = async (req, res, next) => {
const id = req.user.id;
const videoId = req.params.videoId;
try {
await Video.findByIdAndUpdate(videoId, {
$addToSet: { dislikes: id },
$pull: { likes: id }
})
res.status(200).json("The video has been disliked.")
} catch (err) {
next(err);
}
}
export const videounLike = async (req, res, next) => {
const id = req.user.id;
const videoId = req.params.videoId;
try {
await Video.findByIdAndUpdate(videoId, {
$pull: { likes: id } //removing id from dislike if a person likes video
})
res.status(200).json("The video has been unliked.")
} catch (err) {
next(err);
}
}
export const videounDislike = async (req, res, next) => {
const id = req.user.id;
const videoId = req.params.videoId;
try {
await Video.findByIdAndUpdate(videoId, {
$pull: { dislikes: id }
})
res.status(200).json("The video has been undisliked.")
} catch (err) {
next(err);
}
}
export const photoLike = async (req, res, next) => {
const id = req.user.id;
const photoId = req.params.photoId;
try {
await Photo.findByIdAndUpdate(photoId, {
$addToSet: { likes: id }, //add to set so that a user can like a video only once
$pull: { dislikes: id } //removing id from dislike if a person likes video
})
res.status(200).json("The photo has been liked.")
} catch (err) {
next(err);
}
}
export const photounLike = async (req, res, next) => {
const id = req.user.id;
const photoId = req.params.photoId;
try {
await Photo.findByIdAndUpdate(photoId, {
$pull: { likes: id } //removing id from dislike if a person likes video
})
res.status(200).json("The photo has been liked.")
} catch (err) {
next(err);
}
}
export const photoDislike = async (req, res, next) => {
const id = req.user.id;
const photoId = req.params.photoId;
try {
await Video.findByIdAndUpdate(photoId, {
$addToSet: { dislikes: id },
$pull: { likes: id }
})
res.status(200).json("The photo has been disliked.")
} catch (err) {
next(err);
}
}
export const photounDislike = async (req, res, next) => {
const id = req.user.id;
const photoId = req.params.photoId;
try {
await Video.findByIdAndUpdate(photoId, {
$pull: { dislikes: id }
})
res.status(200).json("The photo has been disliked.")
} catch (err) {
next(err);
}
}
export const videosave = async (req, res, next) => {
try {
const video = await Video.findById(req.params.id);
await User.findByIdAndUpdate(req.user.id, {//getting user id to update its array
$addToSet: { videosaved: video._id }, //pushing the channel user id in subscribed array so that we can get which channel is subscibed by user //by using mongodb push operation
});
res.status(200).json("Video added")
} catch (err) {
next(err);
}
};
export const videoremove = async (req, res, next) => {
try {
const video = await Video.findById(req.params.id);
await User.findByIdAndUpdate(req.user.id, {//getting user id to update its array
$pull: { videosaved: video._id }, //pushing the channel user id in subscribed array so that we can get which channel is subscibed by user //by using mongodb push operation
});
res.status(200).json("Video removed")
} catch (err) {
next(err);
}
};
export const photosave = async (req, res, next) => {
try {
const photo = await Photo.findById(req.params.id);
await User.findByIdAndUpdate(req.user.id, {//getting user id to update its array
$addToSet: { photosaved: photo._id }, //pushing the channel user id in subscribed array so that we can get which channel is subscibed by user //by using mongodb push operation
});
res.status(200).json("Photo added")
} catch (err) {
next(err);
}
};
export const photoremove = async (req, res, next) => {
try {
try {
const photo = await Photo.findById(req.params.id);
await User.findByIdAndUpdate(req.user.id, {//getting user id to update its array
$pull: { photosaved: photo._id }, //pushing the channel user id in subscribed array so that we can get which channel is subscibed by user //by using mongodb push operation
});
res.status(200).json("Photo removed")
} catch (err) {
next(err);
}
} catch (err) {
next(err)
}
};
export const videohistory = async (req, res, next) => {
try {
const video = await Video.findById(req.params.id);
await User.findByIdAndUpdate(req.user.id, {//getting user id to update its array
$addToSet: { historyVideo: video._id }, //pushing the channel user id in subscribed array so that we can get which channel is subscibed by user //by using mongodb push operation
});
res.status(200).json("Video added to history")
} catch (err) {
next(err);
}
};
export const photohistory = async (req, res, next) => {
try {
const photo = await Photo.findById(req.params.id);
await User.findByIdAndUpdate(req.user.id, {//getting user id to update its array
$addToSet: { historyPhoto: photo._id }, //pushing the channel user id in subscribed array so that we can get which channel is subscibed by user //by using mongodb push operation
});
res.status(200).json("Photo added")
} catch (err) {
next(err);
}
};
export const verifyEmail = async (req, res, next) => {
try {
const user = await User.findOne({ _id: req.params.id });
if (!user) return res.status(400).send({ message: "Invalid link" }); //if no such user exist
const token = await Token.findOne({
userId: user._id,
token: req.params.token,
});
if (!token) return res.status(400).send({ message: "Invalid link" }); //if token not exist
await User.findByIdAndUpdate(user._id, { verified: true });
res.status(200).send({ message: "Email verified successfully" });
} catch (error) {
res.status(500).send({ message: "Internal Server Error" });
}
}
export const resetPasswordEmail = async (req, res, next) => {
try {
const user = await User.findOne({ name: req.body.name });
if (!user) return next(createError(404, "User not found!"));
let resetToken = await ResetToken.findOne({ userId: user._id });
if (resetToken === undefined || resetToken === null) {
resetToken = await new ResetToken({
userId: user._id,
resetToken: crypto.randomBytes(32).toString("hex"),
}).save();
}
const url = `${process.env.BASE_URL}users/${user._id}/reset/${resetToken.resetToken}`;
await sendEmail(user.email, "Recovery email", emailTemplate(url, "Change Your Password", user.Normalname, "Welcome back to IIITU Snapshots, change your paasword", "Change Password", "If you didn't want to change password for IIITU Snapshot, you can safely ignore this email."))
return res
.status(200)
.send({ message: "An Email sent to your account please reset your password for catching up " });
}
catch (error) {
// console.log(error);
next(error);
}
}
export const resetPasswordVerify = async (req, res, next) => {
try {
const user = await User.findOne({ _id: req.params.id });
// console.log(user);
if (!user) return res.status(400).send({ message: "Invalid link" }); //if no such user exist
const resetToken = await ResetToken.findOne({
userId: user._id,
resetToken: req.params.resetToken,
});
if (!resetToken) return res.status(400).send({ message: "Invalid link" }); //if token not exist
res.status(200).json("updated"); //sending updated data to user
} catch (error) {
next(error);
// console.log(error)
}
}
export const resetPassword = async (req, res, next) => {
try {
const user = await User.findOne({ _id: req.params.id });
if (!user) return res.status(400).send({ message: "Invalid link" }); //if no such user exist
const resetToken = await ResetToken.findOne({
userId: user._id,
resetToken: req.params.resetToken,
});
if (!resetToken) return res.status(400).send({ message: "Invalid link" }); //if token not exist
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(req.body.password, salt);
const updatedPwd = await User.findByIdAndUpdate(user._id, { password: hash });
res.status(200).json(updatedPwd); //sending updated data to user
} catch (error) {
next(error);
// console.log(error)
}
}