-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
253 lines (214 loc) · 7.63 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
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*
app.js -- This creates an Express webserver with login/register/logout authentication
*/
// *********************************************************** //
// Loading packages to support the server
// *********************************************************** //
// First we load in all of the packages we need for the server...
const createError = require('http-errors'); // to handle the server errors
const express = require('express');
const path = require('path'); // to refer to local paths
const cookieParser = require('cookie-parser'); // to handle cookies
const session = require('express-session'); // to handle sessions using cookies
const debug = require('debug')('personalapp:server');
const layouts = require('express-ejs-layouts');
const axios = require('axios');
// *********************************************************** //
// Loading models
// *********************************************************** //
const SchoolList = require('./models/SchoolList');
const College = require('./models/College');
// *********************************************************** //
// Loading JSON datasets
// *********************************************************** //
const colleges = require('./public/data/colleges.json');
// *********************************************************** //
// Connecting to the database
// *********************************************************** //
const mongoose = require('mongoose');
const mongodb_URI = process.env.mongodb_URI
mongoose.connect(mongodb_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// fix deprecation warnings
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('we are connected!!!');
});
// *********************************************************** //
// Initializing the Express server
// This code is run once when the app is started and it creates
// a server that respond to requests by sending responses
// *********************************************************** //
const app = express();
// Here we specify that we will be using EJS as our view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// this allows us to use page layout for the views
// so we don't have to repeat the headers and footers on every page ...
// the layout is in views/layout.ejs
app.use(layouts);
// Here we process the requests so they are easy to handle
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
// Here we specify that static files will be in the public folder
app.use(express.static(path.join(__dirname, 'public')));
// Here we enable session handling using cookies
app.use(
session({
secret: 'zzbbyanana789sdfa8f9ds8f90ds87f8d9s789fds', // this ought to be hidden in process.env.SECRET
resave: false,
saveUninitialized: false,
})
);
// *********************************************************** //
// Defining the routes the Express server will respond to
// *********************************************************** //
// here is the code which handles all /login /signin /logout routes
const auth = require('./routes/auth');
const {deflateSync} = require('zlib');
app.use(auth);
// middleware to test is the user is logged in, and if not, send them to the login page
const isLoggedIn = (req, res, next) => {
if (res.locals.loggedIn) {
next();
} else res.redirect('/login');
};
// specify that the server should render the views/index.ejs page for the root path
// and the index.ejs code will be wrapped in the views/layouts.ejs code which provides
// the headers and footers for all webpages generated by this app
app.get('/', (req, res, next) => {
res.render('index');
});
app.get('/about', (req, res, next) => {
res.render('about');
});
/* ************************
Loading (or reloading) the data into a collection
************************ */
// this route loads in the courses into the Course collection
// or updates the courses if it is not a new collection
app.get('/upsertDB', async (req, res, next) => {
for (college of colleges) {
const {unitID, name, state, websiteAddress, city} = college;
await College.findOneAndUpdate({unitID, name, state, websiteAddress, city}, college, {
upsert: true,
});
}
const num = await College.find({}).count();
res.send('data uploaded: ' + num);
});
app.post(
'/colleges/byName',
async (req, res, next) => {
const {name} = req.body;
const colleges = await College.find({name : {$regex: `${name}`, $options: 'i'}});
res.locals.colleges = colleges;
res.render('collegelist');
}
);
app.use(isLoggedIn);
app.get(
'/addCollege/:collegeId',
async (req, res, next) => {
try {
const collegeId = req.params.collegeId;
const userId = res.locals.user._id;
// check to make sure it's not already loaded
const lookup = await SchoolList.find({collegeId, userId});
if (lookup.length == 0) {
const schoolList = new SchoolList({collegeId, userId});
await schoolList.save();
}
res.redirect('/schoolList/show');
} catch (e) {
next(e);
}
}
);
app.get(
'/schoolList/show',
async (req, res, next) => {
try {
const userId = res.locals.user._id;
const collegeIds = (await SchoolList.find({userId}))
.map(x => x.collegeId);
res.locals.colleges = await College.find({_id: {$in: collegeIds}});
res.render('schoollist');
} catch (e) {
next(e);
}
}
);
app.get(
'/schoolList/remove/:collegeId',
async (req, res, next) => {
console.log(req.params.collegeId)
try {
await SchoolList.remove({
userId: res.locals.user._id,
collegeId: req.params.collegeId,
});
res.redirect('/schoolList/show');
} catch (e) {
next(e);
}
}
);
// here we catch 404 errors and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// this processes any errors generated by the previous routes
// notice that the function has four parameters which is how Express indicates it is an error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// *********************************************************** //
// Starting up the server!
// *********************************************************** //
//Here we set the port to use between 1024 and 65535 (2^16-1)
const port = process.env.PORT || "5000";
console.log('connecting on port '+port)
app.set('port', port);
// and now we startup the server listening on that port
const http = require('http');
const server = http.createServer(app);
server.listen(port);
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
debug('Listening on ' + bind);
}
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
server.on('error', onError);
server.on('listening', onListening);
module.exports = app;