-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
262 lines (238 loc) · 6.07 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
/**
* Setup and initialization.
*/
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 GoogleStrategy = require("passport-google-oauth20").Strategy;
const LocalStrategy = require("passport-local").Strategy;
const findOrCreate = require("mongoose-findorcreate");
const app = express();
app.set("view engine", "ejs");
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(express.static("public"));
app.use(
session({
secret: process.env.SECRET_KEY,
resave: false,
saveUninitialized: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
/**
* MongoDB and mongoose setup, including schema and models
* for User.
*
* Setup Passport.js for hashing, salting passwords
* and implementing cookies and sessions.
*
* Setup Google OAuth2.0 for allowing users to register
* and login with a Google Account.
*
* Setup Local Strategy, so that users can login with an
* account setup with the app.
*/
mongoose.connect(process.env.MONGODB_SRV_ADDRESS, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.set("useCreateIndex", true);
const userSchema = new mongoose.Schema({
googleId: String,
email: String,
password: String,
secret: String,
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_OAUTH_CLIENT_ID,
clientSecret: process.env.GOOGLE_OAUTH_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_OAUTH_CALLBACK_URL,
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo",
},
(accessToken, refreshToken, profile, cb) => {
User.findOrCreate({ googleId: profile.id }, (err, user) => {
return cb(err, user);
});
}
)
);
passport.use(
new LocalStrategy((username, password, done) => {
User.findOne({ username: username }, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: "User could not be authenticated.",
});
}
return done(null, user);
});
})
);
/**
* GET method for / route.
*
* Renders the home page.
*/
app.get("/", (req, res) => {
res.render("home");
});
/**
* GET method for /auth/google route.
*
* Uses Passport.js to authenticate through Google.
* Redirects to a Google page for authentication.
*/
app.get(
"/auth/google",
passport.authenticate("google", { scope: ["email", "profile"] })
);
/**
* GET method for /auth/google/secrets route, which is the
* callback function when user has been authenticated with Google.
*
* If authentication failed, redirect to login page, else
* redirect to secrets page.
*/
app.get(
"/auth/google/secrets",
passport.authenticate("google", { failureRedirect: "/login" }),
(req, res) => {
res.redirect("/secrets");
}
);
/**
* GET method for /login route.
*
* Renders the login page.
*/
app.get("/login", (req, res) => {
res.render("login");
});
/**
* POST method for /login route.
*
* Checks if the submitted username/email and password matches a user in the db.
* If no match, returns to login page, else renders the secrets page.
*/
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/secrets",
failureRedirect: "/login",
failureFlash: true,
})
);
/**
* GET method for /register route.
*
* Renders the register page.
*/
app.get("/register", (req, res) => {
res.render("register");
});
/**
* POST method for /register route.
*
* Registers a user with the submitted username/email and password.
* Renders the secrets page once registration has finished.
* Redirects to register page if there is an error.
*/
app.post("/register", (req, res) => {
User.register(
{ username: req.body.username },
req.body.password,
(err, user) => {
if (err) res.redirect("/register");
else
passport.authenticate("local")(req, res, () => {
res.redirect("/secrets");
});
}
);
});
/**
* GET method for the /secrets route.
*
* Renders secrets page. User must be authenticated to view.
* Secrets page shows all of the user's secrets.
* Redirects to login page, if user is not authenticated.
*/
app.get("/secrets", (req, res) => {
if (req.isAuthenticated()) {
User.find({ secret: { $ne: null } }, (err, foundUsers) => {
if (err) res.redirect("/login");
else res.render("secrets", { usersWithSecrets: foundUsers });
});
} else res.redirect("/login");
});
/**
* GET method for the /submit route.
*
* Renders the submit page, if user is authenticated.
* Redirects to login page, if user is not authenticated.
*/
app.get("/submit", (req, res) => {
if (req.isAuthenticated()) res.render("submit");
else res.redirect("/login");
});
/**
* POST method for /submit route.
*
* Adds the secret the user has submitted to their secret field.
* Redirects to submit page, if there is an error.
* If successful, redirects to secrets page, where new secret
* will be displayed.
*/
app.post("/submit", (req, res) => {
User.findById(req.user.id, (err, user) => {
if (user) {
user.secret = req.body.secret;
user.save(() => {
res.redirect("/secrets");
});
} else res.redirect("/submit");
});
});
/**
* GET method for /logout route.
*
* Logs user out (removes authentication - cookie and session),
* and redirects to home page.
*/
app.get("/logout", (req, res) => {
req.logout();
res.redirect("/");
});
/**
* Start up server to listen on port 3000.
*/
app.listen(process.env.PORT || 3000, () => {
console.log("Server started on port 3000");
});