-
Notifications
You must be signed in to change notification settings - Fork 1
/
blog.js
357 lines (318 loc) · 7.94 KB
/
blog.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
import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import bcrypt from "bcrypt";
import passport from "passport";
import { Strategy } from "passport-local";
import GoogleStrategy from "passport-google-oauth20";
import session from "express-session";
import NodeCache from "node-cache";
import dotenv from "dotenv";
const cache = new NodeCache();
const blogSchema = new mongoose.Schema({
id: String,
blogTitle: String,
blogContent: String,
authorId: String,
subscribedUserId: String,
activeSubscriber: Boolean,
});
const userSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
email: String,
password: String,
googleId: String,
role: { type: String, enum: ["user", "specialUser"], default: "user" },
});
const Blog = mongoose.model("Blog", blogSchema);
const User = mongoose.model("User", userSchema);
const app = express();
dotenv.config();
mongoose.connect("mongodb://0.0.0.0:27017/Blogs");
/*
const db=mongoose.connection;
db.on('error',console.error.bind(console,'MongoDB connection error'))
db.once('open',()=>{
console.log('MongoDB connected');
})
const cache = new NodeCache();
*/
app.use(
session({
secret: "Do not tell anyone",
resave: false,
saveUninitialized: true,
})
);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(passport.initialize());
app.use(passport.session());
app.get("/", (req, res) => {
res.render("home.ejs");
});
app.get("/login", (req, res) => {
res.render("login.ejs");
});
app.get("/register", (req, res) => {
res.render("register.ejs");
});
app.get("/logout", (req, res) => {
req.logout(function (err) {
if (err) {
return next(err);
}
res.redirect("/");
});
});
/*app.get("/secrets",async function(req, res){
let foundUsers= await User.find({"secret": {$ne: null}})
if (foundUsers) {
console.log(foundUsers);
res.render("secrets.ejs", {usersWithSecrets: foundUsers});
}
}
)
*/
app.get(
"/auth/google",
passport.authenticate("google", {
scope: ["profile", "email"],
})
);
app.get(
"/auth/google/getBlogs",
passport.authenticate("google", {
successRedirect: "/getBlogs",
failureRedirect: "/login",
})
);
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/secrets",
failureRedirect: "/login",
})
);
app.post("/register", async (req, res) => {
const email = req.body.username;
const password = req.body.password;
const role = req.body.role;
try {
const user = await User.findOne({ email });
if (user) {
res.redirect("/login");
} else {
const hash = bcrypt.hash(password, process.env.SALTROUNDS);
const newUser = new User({
_id: new mongoose.Types.ObjectId(),
email,
password: hash,
role,
});
await newUser.save();
req.login(newUser, (err) => {
if (err) {
console.error("Error during login:", err);
} else {
res.redirect("/secrets");
}
});
}
} catch (err) {
console.log(err);
}
});
app.get("/submit", function (req, res) {
console.log(req.user, "submitUser");
if (req.isAuthenticated()) {
res.render("submit.ejs");
} else {
res.redirect("/login");
}
});
app.post("/submit", async function (req, res) {
if (req.isAuthenticated()) {
console.log(req.body);
console.log(req.user, "user");
console.log(req.body.secret, "secret");
try {
if (req.body && req.body.secret) {
let updatedUser = await User.findOneAndUpdate(
{ googleId: req.user.googleId },
{ $set: { feedback: req.body.secret } },
{ new: true }
);
console.log(updatedUser, "updatedUser");
res.send("feedback updated");
} else {
res
.status(400)
.json({ error: "Bad Request. Missing secret in request body." });
}
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal Server Error" });
}
} else {
res.status(401).json({ error: "Unauthorized" });
}
});
passport.use(
"local",
new Strategy(async function verify(email, password, cb) {
try {
const user = await User.findOne({ email: email });
if (user) {
const storedHashedPassword = user.password;
const valid = bcrypt.compare(password, storedHashedPassword);
if (valid) {
return cb(null, user);
} else {
return cb(null, false);
}
} else {
return cb("User not found");
}
} catch (err) {
console.log(err, "local error");
}
})
);
passport.use(
"google",
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/getBlogs",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo",
},
async (accessToken, refreshToken, profile, cb) => {
try {
console.log(accessToken);
console.log(profile);
const user = await User.findOne({ email: profile.email });
if (!user) {
const newUser = new User({
email: profile.email,
googleId: profile.id,
});
await newUser.save();
return cb(null, newUser);
} else {
return cb(null, user);
}
} catch (err) {
return cb(err);
}
}
)
);
passport.serializeUser((user, cb) => {
cb(null, user._id);
});
passport.deserializeUser(async (id, cb) => {
try {
const user = await User.findById(id);
cb(null, user);
} catch (err) {
cb(err);
}
});
app.post("/api/blogs/insert", async (req, res) => {
try {
const {
id,
blogTitle,
blogContent,
authorId,
subscribedUserId,
activeSubscriber,
} = req.body;
if (req.body) {
const newblog = new Blog({
id,
blogTitle,
blogContent,
authorId,
subscribedUserId,
activeSubscriber,
});
await newblog.save();
res.send("done and dusted");
}
} catch (error) {
res.status(500).json({ error: "Internal Server Error" });
}
});
app.get("/getBlogs", async (req, res) => {
try {
const authorId = "001";
const cachedData = cache.get(authorId);
if (cachedData) {
console.log("Retriving data from cache itself", cachedData);
return res.json(cachedData);
}
const aggregationPipeline = [
{
$match: {
activeSubscriber: true,
},
},
{
$group: {
_id: "$authorId",
totalBlogs: { $sum: 1 },
blogTitle: { $first: "$blogTitle" },
avgBlogLength: { $avg: { $strLenCP: "$blogContent" } },
},
},
{
$sort: {
totalBlogs: -1,
},
},
{
$project: {
_id: 0,
authorId: "$_id",
totalBlogs: 1,
blogTitle: 1,
avgBlogLength: 1,
},
},
];
const aggregateData = await Blog.aggregate(aggregationPipeline).exec();
cache.set(authorId, aggregateData, 60);
res.json(aggregateData);
} catch (error) {
console.log(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.delete("/api/blogs/deleteOne", async (req, res) => {
try {
if (req.body) {
await Blog.deleteOne(req.body);
}
res.json("deleted");
} catch (error) {
console.error("Error fetching notes:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.put("/api/blogs/updateOne/:id", async (req, res) => {
try {
if (req.body) {
await Blog.findOneAndUpdate({ authorId: req.params.id }, req.body);
}
res.json("updated");
} catch (error) {
console.error("Error fetching notes:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.listen(3000, () => {
console.log(`Server running on port ${3000}`);
});