-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
74 lines (71 loc) · 1.87 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
const express = require('express');
const mongoose = require('mongoose');
//session store in browser
const session = require('express-session');
//MongoDB URI
const MONGODB_URI = 'mongodb://localhost:27017/binar_crudv2'
//save session to mongodb
const MongoDBStore = require('connect-mongodb-session')(session);
//library security for csrf attack
const csrf = require('csurf');
//library for flash messages
const flash = require('connect-flash');
//import user model
const User = require('./models/UserCredSchema');
//import routes
const loginRoutes = require('./routes/login')
const app = express();
const csrfProtection = csrf();
//set store session to mongodb
const store = new MongoDBStore({
uri: MONGODB_URI,
collection: 'sessions'
})
app.set('view engine', 'ejs');
app.use(express.json());
app.use(express.urlencoded({extended: true}))
app.use(express.static('public'));
//middleware session
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: false,
store: store
}))
//middleware csrf
app.use(csrfProtection)
//middleware flash message
app.use(flash())
//middleware check user
app.use((req, res, next) => {
if (!req.session.user){
return next();
}
User.findById(req.session.user._id)
.then(user => {
res.locals.user = user;
next();
})
.catch(err => console.log(err));
})
//middleware for csrf token and login authentication
app.use((req, res, next) => {
res.locals.isAuthenticated = req.session.isLoggedIn;
res.locals.csrfToken = req.csrfToken();
next();
})
app.use(loginRoutes)
mongoose
.connect(MONGODB_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true
})
.then(() => {
app.listen(3000)
console.log("RUNNING")
})
.catch(err => {
console.log(err)
})