-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
72 lines (64 loc) · 2.67 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
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const csrf = require('csurf');
const flash = require('connect-flash');
const User = require('./Models/UserM');
const adminRoutes = require('./Routes/Admin');
const shopRoutes = require('./Routes/Shop');
const authRoutes = require('./Routes/Auth');
const errorController = require('./Controllers/404CTRL');
// defining sessions store collection in mongoDB
let Store = new MongoDBStore({
uri: 'mongodb+srv://shehab-fekry:[email protected]/Shop',
collection: 'sessions',
})
const server = express();
server.set('view engine', 'ejs')
server.set('views', 'Views')
// parsing all incoming requists
server.use(bodyParser.urlencoded({extended: false}))
// granting access to public
server.use(express.static(path.join(__dirname, 'Public')))
// initializing new session
// with the following middleware setup... the session knows its store place in mongoDB and will only be saved there
// modification means (session.isLoggedin = value) or [session.save() , session.destroy()] is called
// req.session is provided
server.use(session({secret: 'my secret', resave: false, saveUninitialized: false, store: Store}))
// csrf middleware is used to prevent csrf attacks on every rendered view with a POST requist form
// a hidden input with name (_csrf) and value (csrfToken) is added to every form
// every initialized session has its own random csrf
// req.csrfToken() is provided
server.use(csrf())
server.use((req, res, next) => {
res.locals.csrfToken = req.csrfToken();
next()
})
// flash middleware used to store a message in the session temporary for error messages and
// then delete it directly after being used
// req.falsh() is provided
server.use(flash())
// the user can be stored in sessions (req.session.user) but his schema functions aren't stored there (only data)
// in order to activate these functions we use (req.user) which will be responsable for his behaviors
server.use((req, res, next)=>{
if(!req.session.user) // if not logged in
return next()
User.findById(req.session.user._id)
.then(user => {
req.user = user;
next()
})
.catch(err => console.log(err))
})
server.use('/admin', adminRoutes)
server.use(shopRoutes)
server.use(authRoutes)
server.use(errorController.error)
mongoose.connect('mongodb+srv://shehab-fekry:[email protected]/Shop?retryWrites=true&w=majority')
.then(result => {
server.listen(3000)
})
.catch(err => console.log(err))