-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
382 lines (349 loc) · 10.1 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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import express from "express";
import cors from "cors";
import mongoose from "mongoose";
import logger from "./logger.js";
import { userSchema, User } from "./models/user.js";
import { productSchema, Product } from "./models/products.js";
import jwt from "jsonwebtoken";
import dotenv from "dotenv";
import bcrypt from "bcrypt";
import nodemailer from "nodemailer";
import { ObjectId } from "mongodb";
dotenv.config();
let resetSecret;
const app = express();
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ limit: "50mb" }));
app.use(cors());
//Database connection
mongoose.connect(
"mongodb://localhost:27017/whim",
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
() => {
logger.info("Database conection successful");
console.log("Database connection successful");
}
);
//Routes-----------
//Forgot password
app.post("/forgot_password", (req, res) => {
const { email } = req.body;
User.findOne({ email: email }, (err, user) => {
//If user exists, create one time link valid for 5 minutes.
if (user) {
resetSecret = process.env.ACCESS_TOKEN_SECRET + user.password;
const payload = {
email: user.email,
id: user.id,
};
const resetToken = jwt.sign(payload, resetSecret, { expiresIn: "5m" });
//send email with reset link
const link = `http://localhost:3000/reset_password/${user.email}/${resetToken}`;
//---------------EMAIL LOGIC---------
var transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: "[email protected]",
pass: "Conestoga123@",
},
});
var mailOptions = {
from: "[email protected]",
to: user.email,
subject: "Password reset",
html: `<div><h3> Please click on the below link to reset your password <h3> <div>
<div> <a href="${link}" style="color:red">Reset Password</a> <div/><br>
<div> This link will expire in 5 minutes, if so, you may request for a new link. <div/>`,
};
try {
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.log(error);
logger.error(error);
} else {
console.log("Email sent: " + info.response);
}
});
} catch (error) {
logger.error(error);
res.send({ message: "Incorrect email" });
}
//-------------------------------------
res.send({
message: "Password reset email sent. Valid for only 5 minutes.",
});
} else {
res.send({ message: "User does not exist" });
}
});
});
//Update password
app.post("/reset_password/:email/:resetToken", (req, res) => {
const { email, resetToken } = req.params;
try {
const isTokenActive = jwt.verify(resetToken, resetSecret);
const user = User.findOne({ email: email }, async (err, user) => {
if (user) {
const newuser = new User({
name: user.name,
email: email,
password: req.body.password,
});
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
newuser.password = hashedPassword;
await User.updateOne({ email: email }, { password: hashedPassword });
} else {
res.send({ message: err });
}
});
res.send({
message: "Password updated. Please login to continue",
status: "ok",
});
} catch (error) {
logger.error(error);
res.send({ message: "Session expired, please request for a new link." });
}
});
//Login user
app.post("/login", (req, res) => {
const { email, password } = req.body;
User.findOne({ email: email }, async (err, user) => {
if (user) {
//Check if username and pwd matches
if (user && (await bcrypt.compare(password, user.password))) {
//create token
const accessToken = jwt.sign(
{ name: user.name, email: user.email },
process.env.ACCESS_TOKEN_SECRET,
{ expiresIn: "1h" }
);
//check if user has Author details
let isAuthor = false;
if (user.aboutAuthor !== "empty") {
isAuthor = true;
}
//send status to frontend
res.send({
message: "User Logged In",
token: accessToken,
name: user.name,
isAuthor: isAuthor,
email: user.email,
isSubscribed: user.isSubscribed,
});
} else {
res.send({ message: "Incorrect Password" });
}
} else {
res.send({ message: "User not found" });
}
});
});
//Register a new user
app.post("/register", (req, res) => {
const { name, email, password } = req.body;
User.findOne({ email: email }, async (err, user) => {
if (user) {
res.send({ message: "User already registered" });
} else {
const user = new User({
name: name,
email: email,
password: password,
aboutAuthor: "empty",
introAuthor: "empty",
isSubscribed: false,
profilePic: "",
posts: { postIds: {} },
});
//Password hashing
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(user.password, salt);
user.password = hashedPassword;
user.save((err) => {
if (err) {
res.send(err);
} else {
res.send({ message: "User Added" });
}
});
}
});
});
//Add a new post
app.post("/addPost", (req, res) => {
let isAuthor = "false";
const {
category,
coverImage,
title,
aboutCorse,
preRequisite,
videoLinks,
email,
} = req.body;
let authorId = "";
User.findOne({ email: email }, async (err, user) => {
if (user) {
//save user id
authorId = user._id;
//check if user is author
if (user.aboutAuthor !== "empty") {
isAuthor = "true";
}
const product = new Product({
authorId: authorId,
authorName: user.name,
authorImage: user.profilePic,
category: category,
coverImage: coverImage,
title: title,
aboutCorse: aboutCorse,
preRequisite: preRequisite,
videoLinks: videoLinks,
});
product.save((err) => {
if (err) {
res.send(err);
} else res.send({ status: "ok", isAuthor: isAuthor });
});
} else {
logger.error("error finding user inside Add New Post service call");
res.send({ message: "error finding user" });
}
});
});
//Fetch all posts
app.get("/getAllPosts", async (req, res) => {
let results = [];
results = await Product.find();
if (results) {
res.send({ message: "ok", results: results });
} else {
logger.error(
"Error in Find Product query inside Get All Post service call"
);
res.send({ message: "Error in query." });
}
});
//Fetch posts for a specific user
app.post("/getUserPosts", (req, res) => {
let results = [];
const { email } = req.body;
User.findOne({ email: email }, async (err, user) => {
if (user) {
if (user.aboutAuthor !== "empty") {
var o_id = new ObjectId(user._id);
results = await Product.find({ authorId: o_id });
if (results) {
res.send({
message: "ok",
results: results,
aboutAuthor: user.aboutAuthor,
isSubscribed: user.isSubscribed,
pic: user.profilePic,
});
} else {
res.send({ message: "You do not have any active post." });
}
} else {
res.send({ message: "incomplete profile" });
}
} else {
logger.error("error fetching user inside Get User Posts service call");
res.send({ message: "error fetching user" });
}
});
});
//Delete a post
app.post("/deletePost", (req, res) => {
const { postId } = req.body;
const o_id = new ObjectId(postId);
Product.findOne({ _id: o_id }, async (err, product) => {
if (product) {
await Product.remove({ _id: o_id });
let results = [];
results = await Product.find();
if (results) {
res.send({ message: "ok", results: results });
} else {
logger.error("Error in find product query at Delete Post service call");
res.send({ message: "Error in query.", results: null });
}
} else {
res.send({ message: err });
}
});
});
//Subscribe user
app.post("/subscribe", (req, res) => {
const { email } = req.body;
const user = User.findOne({ email: email }, async (err, user) => {
if (user) {
await User.updateOne({ email: email }, { isSubscribed: true });
res.send({
message: "user subscribed",
status: "ok",
isSubscribed: true,
});
} else {
res.send({ message: err });
}
});
});
//Stop user subscription
app.post("/unsubscribe", (req, res) => {
const { email } = req.body;
const user = User.findOne({ email: email }, async (err, user) => {
if (user) {
await User.updateOne({ email: email }, { isSubscribed: false });
res.send({
message: "user unsunscribed",
status: "ok",
});
} else {
res.send({ message: err });
}
});
});
//Save Author details
app.post("/saveAuthor", (req, res) => {
const { profilePic, intro, description, email } = req.body;
const user = User.findOne({ email: email }, async (err, user) => {
if (user) {
await User.updateOne(
{ email: email },
{ introAuthor: intro, aboutAuthor: description, profilePic: profilePic }
);
res.send({
message: "user details updated",
status: "ok",
});
} else {
res.send({ message: err });
}
});
});
//Get author details
app.post("/getAuthor", (req, res) => {
const { id } = req.body;
var o_id = new ObjectId(id);
const user = User.findOne({ _id: o_id }, (err, user) => {
if (user) {
res.send({
intro: user.introAuthor,
about: user.aboutAuthor,
message: "ok",
});
} else res.send({ message: "User not found" });
});
});
//START APP SERVER
app.listen(9032, () => {
logger.info("Backend started at port 9032");
});