-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
165 lines (107 loc) · 5.23 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
/**
* Import external modules or libaraies into Node.js application.
*/
const express = require('express')
// const { config, engine } = require('express-edge')
const ejs = require('ejs')
const edge = require('edge.js')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
const fileUpload = require('express-fileupload')
const expressSession = require("express-session")
const connectMongo = require('connect-mongo')
const connectFlash = require('connect-flash')
const cloudinary = require('cloudinary')
const storePost = require('./middleware/storePost')
const auth = require('./middleware/auth')
const redirectIfAuthenticated = require('./middleware/redirectIfAuthenticated')
const createPostController = require('./controllers/createPost')
const homePageController = require('./controllers/homePage')
const storePostController = require('./controllers/storePost')
const getPostController = require('./controllers/getPost')
const aboutPageController = require('./controllers/aboutPage')
const createUserController = require('./controllers/createUser')
const storeUserController = require('./controllers/storeUser')
const loginController = require('./controllers/#')
const loginUserController = require('./controllers/#User')
const logoutController = require('./controllers/logout')
// connect to mongodb database 'nice-blog', if this database is not exists, it will automatically creates for us.
const db_uri = 'mongodb+srv://cty549868165:mongo87730168@cluster0.gswfabd.mongodb.net/?retryWrites=true&w=majority'
// const db_uri = 'mongodb://localhost/nice-blog'
async function connect() {
try{
await mongoose.connect(db_uri)
console.log("Connected to MongoDB")
} catch(error){
console.log(`ERROR CONEECTION: ${error}`)
}
}
connect()
/**
* Apply Express middlewares
*/
const app = new express()
// a middleware that provides a way to store and retrieve flash message(short-lived message), e.g. used for showing successful login message.
app.use(connectFlash())
// This middleware will create a session ID for user at server-side and also send an associated session ID (called cookie) to client-side
app.use(expressSession({
// necessary: encrypted the cookies
secret: 'secret',
// necessary, because the default value of 'resave' and 'saveUninitialized' has been deprecated
resave: true,
saveUninitialized: true,
// use a specific store we have provided
// with this configuration, it won't create or connect to mongo database we have created and connected again
store: connectMongo.create({
// pass the connection instance
mongoUrl: db_uri,
collection: 'sessions' // default name
})
}))
// all additional resources (e.g. images, css, js) should be searched in '/public' directory
app.use(express.static('public'))
// Configure Edge
// config({ cache: process.env.NODE_ENV === 'production' });
// Automatically set view engine and adds dot notation to app.render
// app.set('view', `${__dirname}/views`);
app.set('view engine', 'ejs')
// Help us accept and parse JSON data from the client side(browser)
app.use(bodyParser.json())
// Basic setup that we need to be able to pass data from client side and understand it in NodeJS application.
// A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body).
// This object will contain key-value pairs, where the value can be a string or array (when extended is false), or any type (when extended is true).
// This parser accepts only UTF-8 encoding of the body
app.use(bodyParser.urlencoded({ extended: true }))
// express package that allow processing file uploading
app.use(fileUpload())
// '*' means on all requests, this middleware should be executed.
app.use('*', (req, res, next) => {
// edge.global('auth', req.session.userId) is not supported any more
// in general, the app.locals object in Express is used to store application-level variables
// and values that are available to all templates and routes within an Express application.
// variable name: auth ; value : req.session.userId
app.locals.auth = req.session.userId
next()
})
// cloudinary
cloudinary.config({
api_key: '345398277491559',
api_secret: 'AxFDDc8Fi8AgMCy8AMWiHUHLylE',
cloud_name: 'dpuigzwhs'
})
app.get('/', homePageController)
app.get('/about', aboutPageController)
app.get('/post/:id', getPostController)
// 'auth' is the middleware that would be executed before controller being called.
app.get('/posts/new', auth, createPostController)
app.get('/auth/#', redirectIfAuthenticated, loginController)
app.get('/auth/register', redirectIfAuthenticated, createUserController)
app.get('/auth/logout', logoutController)
// 'storePost' & 'auth' are the middlewares that would be executed before controller being called.
app.post('/posts/store',auth, storePostController)
app.post('/users/register', redirectIfAuthenticated, storeUserController)
app.post('/users/#', redirectIfAuthenticated, loginUserController)
// if all routes above are not match with request from client
app.use((req, res) => res.render('notfound'))
const port = process.env.PORT || 4000
app.listen(port, () =>{ console.log(`App is listening port ${port} now.`) })