-
Notifications
You must be signed in to change notification settings - Fork 86
/
app.js
316 lines (271 loc) · 7.98 KB
/
app.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
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const findOrCreate = require("mongoose-findorcreate");
const LocalStrategy = require("passport-local").Strategy;
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const FacebookStrategy = require("passport-facebook").Strategy;
const app = express();
app.use(express.static("public"));
app.use(express.json());
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
session({
secret: "Our little secret.",
resave: false,
saveUninitialized: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
mongoose.set('strictQuery', false);
const userSchema = new mongoose.Schema({
username: String,
password: String,
googleId: String,
facebookId: String,
secret: [
{
title: { type: String, required: true },
upvote: { type: Number, default: 0 },
downvote: { type: Number, default: 0 },
}
],
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: `${process.env.PUBLIC_BASENAME}auth/google/secrets`,
},
function (accessToken, refreshToken, profile, cb) {
User.findOne({ googleId: profile.id }, (err, existingUser) => {
if (err) {
return cb(err);
}
if (existingUser) {
console.log("User already exists, return the existing user");
return cb(null, existingUser);
}
console.log("User does not exist, create a new one")
const newUser = new User({ googleId: profile.id, username: profile.displayName });
console.log("id" + newUser.googleId);
console.log("username" + newUser.username);
newUser.save((err, user) => {
if (err) {
console.error('Error saving new user:', err);
return cb(err, null);
}
console.log('New User saved successfully:', user);
return cb(null, user);
});
});
}
)
);
passport.use(
new FacebookStrategy(
{
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FACEBOOK_APP_SECRET,
callbackURL: `${process.env.PUBLIC_BASENAME}auth/facebook/secrets`,
},
function (accessToken, refreshToken, profile, cb) {
User.findOne({ facebookId: profile.id }, (err, existingUser) => {
if (err) {
return cb(err);
}
if (existingUser) {
console.log("User already exists, return the existing user");
return cb(null, existingUser);
}
console.log("User does not exist, create a new one")
const newUser = new User({ facebookId: profile.id, username: profile.displayName });
console.log("id" + newUser.facebookId);
console.log("username" + newUser.username);
newUser.save((err, user) => {
if (err) {
console.error('Error saving new user:', err);
return cb(err, null);
}
console.log('New User saved successfully:', user);
return cb(null, user);
});
});
}
)
);
app.get("/", function (req, res) {
res.render("home");
});
app.get(
"/auth/google",
passport.authenticate("google", { scope: ["profile"] })
);
app.get(
"/auth/google/secrets",
passport.authenticate("google", { failureRedirect: "/login" }),
function (req, res) {
res.redirect("/secrets");
}
);
app.get("/auth/facebook", passport.authenticate("facebook"));
app.get(
"/auth/facebook/secrets",
passport.authenticate("facebook", { failureRedirect: "/login" }),
function (req, res) {
res.redirect("/secrets");
}
);
app.get("/login", function (req, res) {
res.render("login");
});
app.get("/about", function (req, res) {
res.render("about");
});
app.get("/contact", function (req, res) {
res.render("contact");
});
app.get("/register", function (req, res) {
res.render("register");
});
app.get("/privacy", function (req, res) {
res.render("privacy");
});
app.post("/register", function (req, res) {
User.register(
{ username: req.body.username },
req.body.password,
function (err, user) {
if (err) {
console.log(err);
res.render("register", { error: err.message });
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/login");
});
}
}
);
});
app.post("/login", function (req, res, next) {
passport.authenticate("local", function (err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.render("login", { error: info.message });
}
req.logIn(user, function (err) {
if (err) {
return next(err);
}
return res.redirect("/secrets");
});
})(req, res, next);
});
app.get("/secrets", function (req, res) {
User.find({ secret: { $ne: null } }, function (err, foundUsers) {
if (err) {
console.log(err);
} else {
if (foundUsers) {
res.render("secrets", {
usersWithSecrets: foundUsers,
upvoted: false,
downvoted: false,
});
}
}
});
});
app.get("/submit-secret-form", function (req, res) {
if (req.isAuthenticated()) {
res.render("secret-form");
} else {
res.redirect("/login");
}
});
app.post("/submit-secret-form", function (req, res) {
const submittedSecret = req.body.secret;
User.findById(req.user.id, function (err, foundUser) {
if (err) {
console.log(err);
} else {
if (foundUser) {
foundUser.secret.push({ title: submittedSecret });
foundUser.save(function (err) {
if (err) {
console.log(err)
} else {
res.redirect("/secrets");
}
});
}
}
});
});
app.get("/logout", function (req, res) {
req.logout(function (err) {
if (err) {
console.error('Error during logout:', err);
return res.redirect("/");
}
res.redirect("/");
});
});
app.post('/api/votes', async (req, res) => {
try {
const { upvoteCount, downvoteCount, index, username } = req.body;
const user = await User.findOne({ username });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
if (index < 0 || index >= user.secret.length) {
return res.status(400).json({ error: 'Invalid secret index' });
}
user.secret[index].upvote = upvoteCount;
user.secret[index].downvote = downvoteCount;
await user.save();
res.json({ message: 'Vote updated successfully', user });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('*', (req, res) => {
res.status(404).render("404-page");
});
app.listen(process.env.PORT, () => {
mongoose
.connect(process.env.MONGO_SERVER, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Database connected successfully");
})
.catch((error) => {
console.log("DB connection failed", process.env.MONGO_SERVER);
});
console.log(`Server is running on ${process.env.PORT}`);
});