-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserController.js
More file actions
277 lines (219 loc) · 7.07 KB
/
userController.js
File metadata and controls
277 lines (219 loc) · 7.07 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
const Product = require('../models/productModel');
const catchAsync = require('../middleware/catchAsyncError');
const User = require("../models/userModel");
const ErrorHandler = require('../utils/errorHandler');
const sendToken = require('../utils/jwtToken');
const sendEmail = require('../utils/sendEmail')
const crypto = require('crypto')
// Register User
exports.registerUser = catchAsync(async (req, res, next) => {
const { name, email, password } = req.body;
const user = await User.create({
name,
email,
password
})
sendToken(user, 201, res)
})
// Login User
exports.loginUser = catchAsync(async (req, res, next) => {
const { email, password } = req.body;
const user = await User.findOne({ email }).select("+password");
if (!user) {
return res.status(400).json({ message: "Invalid Credentials" });
}
const isMatch = await user.comparePassword(password);
if (!isMatch) {
return res.status(400).json({ message: "Invalid Credentials" });
}
sendToken(user, 200, res);
})
// Profile - Get User Details
exports.profile = getUserDetails = catchAsync(async (req, res, next) => {
const user = await User.findById(req.user.id);
res.status(200).json({
success: true,
user,
});
})
// Logout
exports.logout = catchAsync(async (req, res, next) => {
res.cookie("token", null, {
expires: new Date(Date.now()),
httpOnly: true
})
res.status(200).json({
success: true,
message: "Logged Out"
})
})
// Forget Password
exports.forgetPassword = catchAsync(async (req, res, next) => {
const user = await User.findOne({ email: req.body.email });
if (!user) {
return next(new ErrorHandler("User not found", 404))
}
// Get resetToken
const resetToken = user.getPasswordResetToken();
await user.save({ validateBeforeSave: false });
const resetPasswordUrl = `${req.protocol}://${req.get("host")}/api/v1/password/reset/${resetToken}`
const message = `You password reset token is: \n\n ${resetPasswordUrl} \n\n If you have not requested this email then plesae ignore it.`;
try {
await sendEmail({
email: user.email,
subject: `Buyzia Password Recovery`,
message,
})
res.status(200).json({
success: true,
message: `Email sent to ${user.email} successfully.`
})
} catch (error) {
user.resetPasswordToken = undefined;
user.resetPasswordExpire = undefined;
await user.save({ validateBeforeSave: false })
return next(new ErrorHandler(error.message, 500))
}
})
exports.resentPassword = catchAsync(async (req, res, next) => {
const resetPasswordToken = crypto
.createHash("sha256")
.update(req.params.token)
.digest("hex");
const user = await User.findOne({
resetPasswordToken,
resetPasswordExpire: { $gt: Date.now() }
})
if (!user) {
return next(new ErrorHandler("Reset Password Token is invalid or has been expired", 400))
}
if (req.body.password !== req.body.confirmPassword) {
return next(new ErrorHandler("Passwords do not match", 400));
}
user.password = req.body.password
user.resetPasswordToken = undefined
user.resetPasswordExpire = undefined
await user.save()
sendToken(user, 200, res)
})
// Update User Password
exports.updatePassword = catchAsync(async (req, res, next) => {
const user = await User.findById(req.user.id).select("+password");
const isPasswordMatch = await user.comparePassword(req.body.oldPassword);
if (!isPasswordMatch) {
return next(new ErrorHandler("Invalid Old Password, Please Try again", 400))
}
if (req.body.newPassword !== req.body.confirmPassword) {
return next(new ErrorHandler("Password doesn't match", 400))
}
user.password = req.body.newPassword
await user.save()
sendToken(user, 200, res)
})
// Update User Profile
exports.updateProfile = catchAsync(async (req, res, next) => {
const newUserData = {
name: req.body.name,
email: req.body.email,
}
// Cloudinary
const user = await User.findByIdAndUpdate(req.user.id, newUserData, {
new: true,
runValidators: true,
useFindAndModify: false
})
res.status(200).json({
success: true,
user
})
})
// Get Single User -- (Admin)
exports.getSingleUser = catchAsync(async (req, res, next) => {
const user = await User.findById(req.params.id);
if (!user) {
return next(new ErrorHandler(`User does not exist with ID: ${req.params.id}`, 404));
}
res.status(200).json({
success: true,
user,
})
})
// Create or Update the Review
exports.createProductReview = catchAsync(async (req, res, next) => {
const { rating, comment, productId } = req.body;
const review = {
user: req.user._id,
name: req.user.name,
rating: Number(rating),
comment,
};
const product = await Product.findById(productId);
if (!product) {
return next(new ErrorHandler("Product not found", 404));
}
// Check if already reviewed
const isReviewed = product.reviews.find(
(rev) => rev.user.toString() === req.user._id.toString()
);
if (isReviewed) {
// Update review
product.reviews.forEach((rev) => {
if (rev.user.toString() === req.user._id.toString()) {
rev.rating = rating;
rev.comment = comment;
}
});
} else {
// Add new review
product.reviews.push(review);
product.numOfReviews = product.reviews.length;
}
// Calculate average rating
let avg = 0;
product.reviews.forEach((rev) => {
avg += rev.rating;
});
product.rating = avg / product.reviews.length;
await product.save({ validateBeforeSave: false });
res.status(200).json({
success: true,
message: "Review added/updated successfully",
});
});
// Get all Reviews
exports.getProductReviews = catchAsync(async (req, res, next) => {
const product = await Product.findById(req.query.id);
if (!product) {
return next(new ErrorHandler("Product not found", 404))
}
res.status(200).json({
success: true,
reviews: product.reviews,
})
})
// Delete Reviews
exports.deleteReview = catchAsync(async (req, res, next) => {
const product = await Product.findById(req.query.productId);
if (!product) {
return next(new ErrorHandler("Product not found", 404));
}
const reviews = product.reviews.filter(rev => rev._id.toString() !== req.query.id)
let avg = 0;
reviews.forEach((rev) => {
avg += rev.rating;
});
const rating = avg / reviews.length;
const numOfReviews = reviews.length
await Product.findByIdAndUpdate(req.query.productId, {
reviews,
rating,
numOfReviews
}, {
new: true,
runValidators: true,
useFindAndModify: false,
})
res.status(200).json({
success: true,
})
})