-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
105 lines (65 loc) · 2.15 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
// Require Modules
const express = require('express');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const navLinks = require('./navLinks');
require('dotenv').config()
// Database Configuration
const mongoURI = process.env.MONGODB_URI;
const db = mongoose.connection;
// Connect to Mongo
mongoose.connect(mongoURI);
// Connection Error/Success
db.on('error', (err) => console.log(err.message + ' is Mongo not running?'));
db.on('connected', () => console.log('mongo connected: ', mongoURI));
db.on('disconnected', () => console.log('mongo disconnected'));
db.on( 'open' , ()=>{
console.log('Connection made!');
});
// Controller Import
const userController = require('./controllers/user_controller.js')
const postController = require('./controllers/post_controller.js')
const authController = require('./controllers/auth_controller.js')
// App Configuration
const app = express();
const PORT = process.env.PORT || 4000
app.set('view engine', 'ejs');
// Middleware
app.use(
session({
// where to store the sessions in mongodb
store: MongoStore.create({ mongoUrl: process.env.MONGODB_URI }),
// secret key is used to sign every cookie to say its is valid
secret: "super secret",
resave: false,
saveUninitialized: false,
// configure the experation of the cookie
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7 * 2, // two weeks
},
})
);
app.use(function (req, res, next) {
res.locals.user = req.session.currentUser;
next();
});
const authRequired = function (req, res, next) {
if (req.session.currentUser) {
return next();
}
return res.redirect("/login");
};
app.use(express.static('public'))
app.use(methodOverride('_method'));
app.use('/user', userController)
app.use('/post', authRequired, postController)
app.use(navLinks);
// Here we will add the routes for login and register
app.use("/", authController);
// Home Route
app.get('/', (req, res) => {
res.render('home.ejs')
})
app.listen(PORT, () => console.log('listening on port:', PORT))