forked from vikingeducation/assignment_mad_lib_api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
249 lines (208 loc) · 6.11 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
const express = require("express");
const app = express();
// ----------------------------------------
// Body Parser
// ----------------------------------------
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
// ----------------------------------------
// Sessions/Cookies
// ----------------------------------------
const cookieSession = require("cookie-session");
app.use(
cookieSession({
name: "session",
keys: [process.env.SESSION_SECRET || "asdf1234567890qwer"]
})
);
app.use((req, res, next) => {
app.locals.session = req.session;
next();
});
// ----------------------------------------
// Method Override
// ----------------------------------------
const methodOverride = require("method-override");
const getPostSupport = require("express-method-override-get-post-support");
app.use(
methodOverride(
getPostSupport.callback,
getPostSupport.options // GET POST
)
);
// ----------------------------------------
// Referrer
// ----------------------------------------
app.use((req, res, next) => {
req.session.backUrl = req.header("Referer") || "/";
next();
});
// ----------------------------------------
// Logging
// ----------------------------------------
const morgan = require("morgan");
const morganToolkit = require("morgan-toolkit")(morgan);
// Use morgan middleware with
// custom format
if (process.env.NODE_ENV !== "test") {
app.use(morganToolkit());
}
// ----------------------------------------
// Mongoose
// ----------------------------------------
const mongoose = require("mongoose");
app.use((req, res, next) => {
if (mongoose.connection.readyState) {
next();
} else {
require("./mongo")().then(() => next());
}
});
// ----------------------------------------
// Services
// ----------------------------------------
// Require passport, strategies and User model
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const BearerStrategy = require("passport-http-bearer").Strategy;
const User = require("./models").User;
// Initialize passport
app.use(passport.initialize());
app.use(passport.session());
// Create local strategy
const localStrategy = new LocalStrategy(
{
// Set username field to email
// to match form
usernameField: "email"
},
(email, password, done) => {
// Find user by email
User.findOne({ email: email })
.then(user => {
// The user is valid if the password is valid
const isValid = user.validatePassword(password);
// If the user is valid pass the user
// to the done callback
// Else pass false
return done(null, isValid ? user : false);
})
.catch(e => done(null, false));
}
);
// Create the token bearer strategy
const bearerStrategy = new BearerStrategy((token, done) => {
// Find the user by token
User.findOne({ token: token })
.then(user => {
// Pass the user if found else false
return done(null, user || false);
})
.catch(e => done(null, false));
});
// Use the strategy middlewares
passport.use(localStrategy);
passport.use(bearerStrategy);
// Serialize and deserialize the user
// with the user ID
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => {
// Find the user in the database
User.findById(id)
.then(user => done(null, user))
.catch(e => done(null, false));
});
// ----------------------------------------
// Session Helper Middlewares
// ----------------------------------------
// Set up middleware to allow/disallow login/logout
const loggedInOnly = (req, res, next) => {
return req.user ? next() : res.redirect("/login");
};
const loggedOutOnly = (req, res, next) => {
return !req.user ? next() : res.redirect("/");
};
// ----------------------------------------
// Routes
// ----------------------------------------
// Show login only if logged out
app.get("/login", loggedOutOnly, (req, res) => {
res.render("login/login");
});
// Allow logout via GET and DELETE
const onLogout = (req, res) => {
// Passport convenience method to logout
req.logout();
// Ensure always redirecting as GET
req.method = "GET";
res.redirect("/login");
};
app.get("/logout", loggedInOnly, onLogout);
app.delete("/logout", loggedInOnly, onLogout);
// Create session with passport
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true
})
);
// Pass logged in/out middlewares to users router
const loginRouter = require("./routers/login")({
loggedInOnly,
loggedOutOnly
});
app.use("/", loginRouter);
const madLibRouter = require("./routers/madLib");
app.use("/api/v1", madLibRouter);
// Setup API router
// const furiousSpinoffsRouter = require('./routers/furious_spinoffs');
// app.use('/api/v1', furiousSpinoffsRouter);
// ----------------------------------------
// Template Engine
// ----------------------------------------
const expressHandlebars = require("express-handlebars");
const hbs = expressHandlebars.create({
partialsDir: "views/",
defaultLayout: "application"
});
app.engine("handlebars", hbs.engine);
app.set("view engine", "handlebars");
// ----------------------------------------
// Server
// ----------------------------------------
const port = process.env.PORT || process.argv[2] || 4000;
const host = "localhost";
let args;
process.env.NODE_ENV === "production" ? (args = [port]) : (args = [port, host]);
args.push(() => {
console.log(`Listening: http://${host}:${port}\n`);
});
// If we're running this file directly
// start up the server
if (require.main === module) {
app.listen.apply(app, args);
}
// ----------------------------------------
// Error Handling
// ----------------------------------------
app.use("/api", (err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
if (err.stack) {
err = err.stack;
}
res.status(500).json({ error: err });
});
app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
if (err.stack) {
err = err.stack;
}
res.status(500).render("errors/500", { error: err });
});
module.exports = app;