-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
119 lines (104 loc) · 2.53 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
'use strict';
const express = require('express');
const session = require('express-session');
const mongoose = require("mongoose");
const mongoDBsession = require('connect-mongodb-session')(session);
const csrf = require('csurf');
const bodyparser = require('body-parser');
const dir = require('./helper/dir');
const User = require('./model/User');
let flash = require('connect-flash');
/**
* Importing required files to work with expressjs
* such as Routes or other data that may need
*
*/
const routeAdmin = require('./routes/AdminRoute');
const UserRoute = require('./routes/UserRoute');
const routeUser = require('./routes/ShopRoute');
const conn = 'mongodb://localhost:27017/myshop';
/**
* Initiating express
* @type {*|Express}
*/
const app = express();
/**
* Initiating session store
*/
const store = new mongoDBsession({
uri: conn,
collection: 'sessions',
});
/**
* Setting up Template Engine EJS and body parser to parse the
* incoming data
*/
app.set('view engine', 'ejs');
app.set('views', 'views');
/**
* using body parser to get data that
* the application may come acroos
*/
app.use(bodyparser.urlencoded({extended: false}));
app.use(session({
secret: 'SEC2SEC8RE$TSE2CR$ET24$ML/KJMLlE$JJJ',
resave: false,
saveUninitialized: false,
store: store
}));
app.use((req, res, next) => {
if (req.session.isLoggedIn) {
User.findById(req.session.userId)
.then((user) => {
req.user = user;
// console.log(req.session);
next();
})
} else {
next()
}
})
app.use(flash());
app.use((req, res, next) => {
res.locals.message = req.flash()
next()
})
let csrfProtection = csrf(undefined);
app.use(csrfProtection, );
app.use((req, res, next) => {
req.session.isLoggedIn ? res.locals.isLoggedIn = true : res.locals.isLoggedIn = false
res.locals.csrfTokens = req.csrfToken()
next()
})
/**
* serve static files
*/
app.use(express.static(dir(['static'])));
/**
* Using the routes from different places
*/
app.use('/admin', routeAdmin);
app.use(routeUser);
app.use(UserRoute);
/**
* Testing
*/
app.get('/cart', (req, res, next) => {
res.render('cart', {
data: {
title: 'cart'
}
});
});
app.use((req, res, next) => {
res.render('error404', {data: {error: 404, name: 'Error404 on the way'}});
});
/**
* starting the server with mongoose
*/
mongoose.connect(conn, {useNewUrlParser: true, useUnifiedTopology: true})
.then(r => {
app.listen(8000, () => {
console.log(`Server started on port http://localhost:8000`);
});
}).catch(err => console.log(err));