-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
207 lines (170 loc) · 5.45 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
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
const path = require('path');
const fs = require('fs');
// Load environment variables securely
require("dotenv").config({ path: "./config.env" });
// MongoDB setup
const mongoose = require('mongoose');
// Read MongoDB URI and database name from environment variables
const mongoURI = process.env.MONGO_URI;
const mongoDB = process.env.MONGO_DB;
const express = require('express');
const session = require('express-session');
const passport = require('./passport'); // Require the passport module
const authRoutes = require('./routes/auth'); // Require the authentication routes module
const projectRoutes = require('./routes/project'); // Require the project routes module
const assistantRoutes = require('./routes/assistant');
const assessmentsRoutes = require('./routes/assessment');
const { loadProject } = require('./middleware/project');
const loadAssessments = require('./lib/loadAssessments');
const { initializeScheduledJobs } = require('./controllers/hubspot');
//const { getHubspotProfile, updateToolStatistics } = require('./controllers/hubspot');
const app = express();
const port = process.env.PORT || 3080;
app.set('view engine', 'ejs');
// Connect to MongoDB
mongoose.connect(mongoURI, { dbName: mongoDB });
const db = mongoose.connection;
// Check MongoDB connection
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', function() {
console.log("Connected to MongoDB database");
loadAssessments();
});
// Middleware for logging
const logger = require('morgan');
app.use(logger('dev'));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
// Other middleware and setup code...
// Session configuration
app.use(session({
resave: false,
saveUninitialized: true,
secret: process.env.SESSION_SECRET,
}));
// Middleware for user object
// Initialize Passport.js
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
res.locals.user = req.session.passport ? req.session.passport.user : req.session.user;
next();
});
app.use((req, res, next) => {
// Read package.json file
fs.readFile(path.join(__dirname, 'package.json'), 'utf8', (err, data) => {
if (err) {
console.error('Error reading package.json:', err);
return next();
}
try {
const packageJson = JSON.parse(data);
// Extract version from package.json
var software = {};
software.version = packageJson.version;
software.homepage = packageJson.homepage;
software.versionLink = packageJson.homepage + "/releases/tag/v" + packageJson.version;
res.locals.software = software;
} catch (error) {
console.error('Error parsing package.json:', error);
}
next();
});
});
app.use((req, res, next) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); // HTTP 1.1.
res.setHeader('Pragma', 'no-cache'); // HTTP 1.0.
res.setHeader('Expires', '0'); // Proxies.
next();
});
// Logout route
app.post('/logout', function(req, res, next){
req.logout(function(err) {
if (err) { return next(err); }
res.redirect('/');
});
});
// Middleware to ensure authentication
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated())
return next();
else
unauthorised(res);
}
function unauthorised(res) {
const page = {
title: "Error"
};
res.locals.page = page;
const error = new Error("Unauthorized access");
error.status = 401;
throw error;
}
// Routes
app.use(express.static(__dirname + '/public')); // Public directory
// Use authentication routes
app.use('/auth', authRoutes);
app.get('/admin', function(req,res) {
res.redirect('/auth/google');
});
app.use(loadProject);
initializeScheduledJobs();
app.use('/assessments', assessmentsRoutes);
app.use('/projects', assistantRoutes);
app.use('/projects', projectRoutes);
app.get('/', function(req, res) {
const page = {
title: "ODI Maturity Assessment Tool",
link: "/"
};
res.locals.page = page;
res.render('pages/home');
});
app.get('/about', function(req, res) {
const page = {
title: "About",
link: "/about"
};
res.locals.page = page;
res.render('pages/about');
});
app.use(ensureAuthenticated, express.static(__dirname + '/private'));
// Error handling
app.get('/error', (req, res) => res.send("error logging in"));
app.get('*', function(req, res, next){
const page = {
title: "404 Not Found"
};
res.locals.page = page;
const error = new Error("Not Found");
error.status = 404;
next(error);
});
// Error handling middleware
app.use((err, req, res, next) => {
// Default status code for unhandled errors
let statusCode = 500;
let errorMessage = "Internal Server Error";
// Check if the error has a specific status code and message
if (err.status) {
statusCode = err.status;
errorMessage = err.message;
}
const page = {
title: "Error"
};
res.locals.page = page;
// Log the error stack trace
//console.error(err.stack);
// Content negotiation based on request Accept header
const acceptHeader = req.get('Accept');
if (acceptHeader === 'application/json') {
// Respond with JSON
res.status(statusCode).json({ message: errorMessage });
} else {
// Respond with HTML (rendering an error page)
res.status(statusCode).render('errors/error', { statusCode, errorMessage });
}
});
// Start server
app.listen(port , () => console.log('App listening on port ' + port));