-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
421 lines (363 loc) · 11.7 KB
/
index.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
const express = require('express');
var path = require('path');
const mongoose = require('mongoose');
const session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var mongodb = require('mongodb');
//encrypting the password
const bcrypt = require('bcryptjs');
const { ensureAuthenticated } = require('./config/auth');
//order model
var Order = require('./models/order');
//passport config
require('./config/passport')(passport);
//User model
const User = require('./models/User');
//requiring product model
var Product = require('./models/products');
const app = express();
//adding static files like css
app.use('/css',express.static('css'));
//Express Session
app.use(session({
secret: 'mysupersecret',
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection}),
cookie: {maxAge: 180*60*1000}
}));
//connect-flash. Flash needs session hence should be below session. Flash messages weree earlier not displayed because they were place above session and also instead of connect flash wrong library was required.
app.use(flash());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
//static files from public folder
app.use(express.static(__dirname + '/public'));
//User model
var Product = require('./models/products');
var Cart = require('./models/cart');
//connect to mongodb
mongoose.set('useUnifiedTopology', true);
mongoose.connect('mongodb://localhost/addToCart',{ useNewUrlParser: true}).then(() => console.log('connected')).catch((err)=>console.log('err'));
//ejs
app.set('view engine' , 'ejs');
//body-parser
app.use(express.urlencoded({ extended: false}));
var urlencodedParser = bodyParser.urlencoded({ extended: false});
//Global vars
app.use((req,res,next) => {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
app.use(function(req,res,next){
res.locals.session = req.session;
next();
});
//global variable loggedin for all the views
app.use(function(req, res, next) {
res.locals.loggedIn = req.isAuthenticated();
res.locals.session = req.session;
next();
});
//routes
app.get('/index',function(req,res){
var successMsg = req.flash('success')[0];
Product.find(function(err,docs){
var productChunks = [];
var chunkSize = 3;
for(var i = 0; i<docs.length; i = i+chunkSize){
productChunks.push(docs.slice(i, i+chunkSize));
}
res.render('index', {products: productChunks, successMsg: successMsg, noMsg: !successMsg });
});
});
app.get('/automobile',function(req,res){
Product.find(function(err,docs){
var productChunks = [];
var chunkSize = 3;
for(var i = 0; i<docs.length; i = i+chunkSize){
productChunks.push(docs.slice(i, i+chunkSize));
}
res.render('AutomobileTest', {products: productChunks});
});
});
app.get('/fashion',function(req,res){
Product.find(function(err,docs){
var productChunks = [];
var chunkSize = 3;
for(var i = 0; i<docs.length; i = i+chunkSize){
productChunks.push(docs.slice(i, i+chunkSize));
}
res.render('FashionTest', {products: productChunks});
});
});
app.get('/home',function(req,res){
Product.find(function(err,docs){
var productChunks = [];
var chunkSize = 3;
for(var i = 0; i<docs.length; i = i+chunkSize){
productChunks.push(docs.slice(i, i+chunkSize));
}
res.render('HomeTest', {products: productChunks});
});
});
app.get('/sports',function(req,res){
Product.find(function(err,docs){
var productChunks = [];
var chunkSize = 3;
for(var i = 0; i<docs.length; i = i+chunkSize){
productChunks.push(docs.slice(i, i+chunkSize));
}
res.render('SportsTest', {products: productChunks});
});
});
app.get('/beauty',function(req,res){
Product.find(function(err,docs){
var productChunks = [];
var chunkSize = 3;
for(var i = 0; i<docs.length; i = i+chunkSize){
productChunks.push(docs.slice(i, i+chunkSize));
}
res.render('BeautyTest', {products: productChunks});
});
});
app.get('/',function(req,res){
var successMsg = req.flash('success')[0];
Product.find(function(err,docs){
var productChunks = [];
var chunkSize = 3;
for(var i = 0; i<docs.length; i = i+chunkSize){
productChunks.push(docs.slice(i, i+chunkSize));
}
res.render('landingpage2', {products: productChunks, successMsg: successMsg, noMsg: !successMsg });
});
});
app.get('/admin' ,function(req,res){
res.render('admin');
});
app.post('/admin', urlencodedParser, (req,res) =>{
const{imagePath,
product_id,
title,
description,
manufacturer,
price,
category } = req.body;
const newProduct = new Product({
imagePath,
product_id,
title,
description,
manufacturer,
price,
category
});
console.log(newProduct);
//save user
newProduct.save()
.then(user=>{
req.flash('success_msg', 'Product saved successfully');
res.redirect('/admin');
})
.catch(err => console.log(err));
});
app.get('/addTocart/:id', function(req,res){
var productId = req.params.id;
var cart = new Cart(req.session.cart ? req.session.cart : {} );
Product.findById(productId, function(err, product){
if(err){
return res.redirect('/');
}
cart.add(product, product.id);
req.session.cart = cart;
console.log(req.session.cart);
res.redirect('/');
});
});
app.get('/reduce/:id',function(req,res,next){
var productId = req.params.id;
var cart = new Cart(req.session.cart ? req.session.cart : {} );
cart.reduceByOne(productId);
req.session.cart = cart;
res.redirect('addtocart');
});
app.get('/remove/:id',function(req,res,next){
var productId = req.params.id;
var cart = new Cart(req.session.cart ? req.session.cart : {} );
cart.removeItem(productId);
req.session.cart = cart;
res.redirect('addtocart');
});
app.get('/shoppingCart/', function(req,res,next){
if(!req.session.cart){
return res.render('emptyCart');
}
var cart = new Cart(req.session.cart);
res.render('addtocart', {products: cart.generateArray(),totalPrice: cart.totalPrice});
});
app.get('/checkout', isLoggedIn, function(req,res,next){
if(!req.session.cart){
return res.redirect('/');
}
var cart = new Cart(req.session.cart);
var errMsg = req.flash('error')[0];
res.render('checkout', {products: cart.generateArray(),totalPrice: cart.totalPrice, errMsg: errMsg, noError: !errMsg});
});
app.post('/checkout', isLoggedIn, function(req,res,next){
if(!req.session.cart){
return res.redirect('addtocart');
}
var cart = new Cart(req.session.cart);
var stripe = require('stripe')('sk_test_nyrMppk4c6wXK9vWBNnNk7NW00DEyxm8RD');
// `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token
stripe.charges.create(
{
amount: cart.totalPrice * 100,
currency: 'inr',
source: req.body.stripeToken,
description: 'My First Test Charge',
},
function(err, charge) {
var order = new Order({
user: req.user,
cart: req.session.cart,
name: req.body.name,
address: req.body.address,
paymentId: charge.id
});
order.save(function(err, result) {
if(err)
{
req.flash('error', err.message);
return res.redirect('/checkout');
}
});
if(err){
req.flash('error', err.message);
return res.redirect('/checkout');
}
req.flash('success', 'Successfully bought product!!');
req.session.cart = null;
res.redirect('/');
console.log('Successfully bought product!!');
});
});
app.get('/login',notLoggedIn,function(req,res){
res.render('login.ejs');
});
app.get('/signup', notLoggedIn,function(req,res){
res.render('signup');
});
app.get('/profile', isLoggedIn, function(req, res, next) {
Order.find({'user': req.user}, function(err, orders) {
if(err)
{
res.write('error');
}
var cart;
orders.forEach(function(order) {
var cart = new Cart(order.cart);
order.items = cart.generateArray();
});
res.render('profile', { orders: orders });
});
});
app.post('/signup',(req,res) =>{
const{username,
email,
password,
password2 } = req.body;
let errors = [];
//check required field
if(!username || !email || !password || !password2){
errors.push({msg:'Please fill in all fields'});
}
//check password match
if(password !== password2){
errors.push({msg:'Passwords do not match'});
}
//check password length
if(password.length < 6){
errors.push({msg:'Password shoud be atleast 6 characters'});
}
if(errors.length > 0){
res.render('signup', { errors,
username,
email,
password,
password2
});
}
else{
//when validation is passed
//checking if user already registered
User.findOne({ email:email })
.then(user =>{
if(user){
errors.push({msg: 'Email already registered'})
res.render('signup', { errors,username,email,password,password2
});
} else{
const newUser = new User({
username,
email,
password
});
console.log(newUser);
//hashing the password
bcrypt.genSalt(10,(err,salt)=> bcrypt.hash(newUser.password, salt, (err,hash) => {
if(err) throw err;
//set password to hashed
newUser.password = hash;
//save user
newUser.save()
.then(user=>{
req.flash('success_msg', 'You are now registered and can login');
res.redirect('/login');
})
.catch(err => console.log(err));
}))
}
})
}
});
//Login Handle Post
app.post('/login',(req,res,next)=>{
passport.authenticate('local',{
successRedirect:'/',
failureRedirect:'/login',
failureFlash:true,
})(req,res,next);
});
//logout handle
app.get('/logout',isLoggedIn,(req,res)=>{
req.logout();
req.flash('success_msg','You are logged out.');
res.redirect('/');
})
function isLoggedIn(req, res, next)
{
if(req.isAuthenticated())
return next();
res.redirect('/login');
}
function notLoggedIn(req, res, next)
{
if(!req.isAuthenticated())
return next();
res.redirect('/');
}
let port = process.env.PORT;
if (port == null || port == "") {
port = 6969;
}
app.listen(port);
console.log('listening to magic port 6969');