-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
306 lines (269 loc) · 8.88 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
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
passport = require("passport");
MicrosoftStrategy = require("passport-microsoft").Strategy;
morgan = require("morgan");
methodOverride = require("method-override");
session = require("express-session");
const User = require("./models/user");
const Payment = require("./models/payment")
const cartItems = require("./mock_data/cartItems")
var MICROSOFT_GRAPH_CLIENT_ID = process.env.CLIENT_ID;
var MICROSOFT_GRAPH_CLIENT_SECRET = process.env.CLIENT_SECRET;
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing. However, since this example does not
// have a database of user records, the complete Microsoft graph profile is
// serialized and deserialized.
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((obj, done) => {
done(null, obj);
});
passport.use(
new MicrosoftStrategy(
{
clientID: MICROSOFT_GRAPH_CLIENT_ID,
clientSecret: MICROSOFT_GRAPH_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/microsoft/callback",
scope: ["user.read"],
},
function (accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(() => {
// To keep the example simple, the user's Microsoft Graph profile is returned to
// represent the logged-in user. In a typical application, you would want
// to associate the Microsoft account with a user record in your database,
// and return that user instead.
return done(null, profile);
});
}
)
);
const app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
mongoose.set("strictQuery", true);
app.use(morgan("dev"));
// app.use(bodyParser.json());
app.use(methodOverride());
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
})
);
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(process.env.DB_URL).then(() => {
console.log("DB connection established");
});
app.get("/", async (req, res) => {
res.render("account");
});
// Route for cart page
app.get('/cart', (req, res) => {
res.render('cart', {
cartItems: cartItems,
});
});
// Increment quantity of cart item
app.get('/cart/increment/:id', (req, res) => {
const id = parseInt(req.params.id);
cartItems.forEach((item) => {
if (item.id === id) {
item.count++;
}
});
res.redirect('/cart');
});
// Decrement quantity of cart item
app.get('/cart/decrement/:id', (req, res) => {
const id = parseInt(req.params.id);
cartItems.forEach((item) => {
if (item.id === id) {
item.count--;
if (item.count < 1) {
const index = cartItems.indexOf(item);
cartItems.splice(index, 1);
}
}
});
res.redirect('/cart');
});
app.get("/login", (req, res) => {
res.render("login");
});
app.get("/register", (req, res) => {
res.render("register");
});
app.post("/login", async (req, res) => {
try {
console.log(req.body);
const { email, password } = req.body;
const user = await User.findOne({ email: email.toLowerCase() });
// console.log(password, user.password);
if (user && password === user.password) {
/*
res.status(201).json({
userDetails: {
username: user.username,
email: user.email,
},
});
*/
res.redirect("/");
} else {
return res
.status(400)
.send("Invalid creditials, please try again.");
}
} catch (err) {
console.log(err);
return res.status(500).send("Something went wrong. Please try again.");
}
});
app.post("/register", async (req, res) => {
try {
console.log(req.body);
const { username, password, email } = req.body;
// check if email is already registered
const userExists = await User.findOne({ email: email.toLowerCase() });
if (userExists) {
return res.status(409).send("Email already in use.");
}
// Create user to the database
const user = await User.create({
username: username,
email: email.toLowerCase(),
password: password,
});
/*
// sending success response status
return res.status(201).send({
userDetails: {
username: user.username,
email: user.email,
},
});
*/
res.redirect('/')
} catch (err) {
// Catching, logging, and sending error response status
console.log(err);
return res.status(500).send("Error Occured, Please Try Again!");
}
});
app.get("/payment", (req, res) => {
res.render("payment");
});
app.post("/payment", async (req, res) => {
try {
console.log(req.body);
const { card_type, cc_no, ex_date, sec_code, street, city, state } = req.body;
// check if card is already registered
var cardExists = null
if (cc_no != null){
cardExists = await Payment.findOne({
creditCardNumber: cc_no.toLowerCase()
});
}
if (cardExists) {
return res.status(409).send("Email already in use.");
}
// Create user to the database
const payment = await Payment.create({
cardType: card_type.toLowerCase(),
creditCardNumber: cc_no.toLowerCase(),
expiryDate: ex_date,
securityCode: sec_code,
street: street,
city: city,
state: state,
});
console.log(payment)
res.redirect('/cart')
// sending success response status
/*
return res.status(201).send({
paymentDetails: {
cardType: card_type.toLowerCase(),
creditCardNumber: cc_no.toLowerCase(),
expiryDate: ex_date,
securityCode: sec_code,
street: street,
city: city,
state: state,
},
});
*/
} catch (err) {
// Catching, logging, and sending error response status
console.log(err);
return res.status(500).send("Error Occured, Please Try Again!");
}
})
// GET /auth/microsoft
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in Microsoft Graph authentication will involve
// redirecting the user to the common Microsoft login endpoint. After authorization, Microsoft
// will redirect the user back to this application at /auth/microsoft/callback
app.get(
"/auth/microsoft",
passport.authenticate("microsoft", {
// Optionally add any authentication params here
// prompt: 'select_account'
}),
// eslint-disable-next-line no-unused-vars
(req, res) => {
// The request will be redirected to Microsoft for authentication, so this
// function will not be called.
}
);
// GET /auth/microsoft/callback
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.get(
"/auth/microsoft/callback",
passport.authenticate("microsoft", { failureRedirect: "/login" }),
(req, res) => {
res.redirect("/");
}
);
app.get("/logout", (req, res, next) => {
req.logout((err) => {
if (err) {
return next(err);
}
res.redirect("/login");
});
});
let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}
app.listen(port, () => {
console.log("Server started on port successfully");
});
// Simple route middleware to ensure user is authenticated.
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent login session),
// the request will proceed. Otherwise, the user will be redirected to the
// login page.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
else res.redirect("/login");
}