-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
252 lines (215 loc) · 7.62 KB
/
server.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
const ExpressGA = require("express-universal-analytics");
const express = require("express");
const express_session = require("express-session");
const getRepoInfo = require("git-repo-info");
const cookieParser = require("cookie-parser");
const path = require("path");
const log4js = require("log4js");
const google = require("./google");
const logins = require("./logins");
const bodyParser = require('body-parser');
let logger = undefined;
function enable_logging(config) {
let logfile = config.log;
let type = "file";
if (logfile === "stdout") {
type = logfile;
logfile = undefined;
}
log4js.configure({
appenders: {
out: {
type: type,
filename: logfile,
layout: {
type: "pattern",
pattern: "%[[%p] %f{1}:%l >>%] %m"
}
}
},
categories: {
default: { appenders: ["out"], level: "all", enableCallStack: true }
}
});
// set the global logger
logger = log4js.getLogger();
}
function create_routes(config, app) {
const { git_portal_version, git_server_version } = gitConfig(
config.content.dist
);
const git_application_versions = [
git_portal_version,
git_server_version
].join(";");
// Google OAuth
app.get("/login", google.logInLink);
app.get("/logout", logOut);
app.get("/oauth2callback", google.oauth2callback);
// Google Analytics event callback (see eventLog function below for further details)
app.get("/eventlog", eventLog(git_application_versions));
app.post("/pageview", pageview());
// main distribution/resource folder
app.use("/", express.static(config.content.dist));
}
function logOut(req, res) {
res.clearCookie(logins.cookieName, { domain: getDomain(req.hostname) });
res.redirect("/");
}
//get domain from hostname
function getDomain(host) {
let parts = host.split(".");
if (parts.length >= 2) {
return parts[parts.length - 2] + "." + parts[parts.length - 1];
} else return host;
}
/**
* Event Log web service endpoint for Google Analytics reporting.
* Endpoint path is of form '/eventlog?action=click&category=gwas&label=show_variants&value=true'
*
* TODO: this function should capture the front end portal page context of the event; use instead of the req.originalUrl
*
* @param {Request} [req]
* @param {Response} [res]
* @return {Send}
* @public
*/
function eventLog(git_application_version) {
return (req, res) => {
// if google analytics is configured - if a UA code is provided under the
// configuration property `auth.google.UAId` - then execute the logging through google analytics
if (!!req.visitor) {
req.visitor.setUid(logins.getUserId(req));
// custom dimensions
// see the analytics account for their descriptions
// !!! NOTE: you will have to define these if you migrate analytics accounts! !!!
// req.visitor.set("cd1", git_portal_version) // gitPortalVersion in Analytics
// req.visitor.set("cd2", git_server_version) // gitServerVersion in Analytics
req.visitor
.event({
ec: req.query.category,
ea: req.query.action,
el: req.query.label + ";" + git_application_version,
ev: 0,
dp: req.query.page
})
.send();
}
res.sendStatus(200)
};
}
function pageview() {
return (req, res) => {
// extract page from referer: first get rid of protocol, then get everything after the hostname
const referer = req.get('Referer');
logger.info('pageview referrer', req.body.currentPage, req.body.previousPage || req.body.currentPage);
// if google analytics is configured - if a UA code is provided under the
// configuration property `auth.google.UAId` - then execute the logging through google analytics
if (!!req.visitor) {
req.visitor.setUid(logins.getUserId(req));
const path = req.body.currentPage.split('://')[1].match(/\/.*/g)[0];
const page = title = path.split('?')[0];
const query = path.split('?')[1];
req.visitor.pageview(page, req.hostname, path, {
dl: req.body.currentPage,
dr: req.body.previousPage,
cs: req.hostname,
cm: 'referral',
uip: req.headers['x-forwarded-for'].split(',').pop() || req.connection.remoteAddress || req.socket.remoteAddress
}).send();
// res.sendStatus(200);
}
res.sendStatus(200)
};
}
function validateConfig(config) {
let valid = true;
if (!config.content.dist) {
logger.error("Missing content.dist from configuration.");
valid = false;
}
return valid;
}
function gitConfig(dist) {
const git_server_info = getRepoInfo(__dirname);
const git_portal_info = getRepoInfo(path.dirname(dist));
const git_portal_version = [
"portal",
git_portal_info.branch,
git_portal_info.sha.substring(0, 7)
].join(":");
const git_server_version = [
"server",
git_server_info.branch,
git_server_info.sha.substring(0, 7)
].join(":");
return {
git_portal_version,
git_server_version
};
}
//start function
function start(config) {
// setup logging
enable_logging(config);
let valid = validateConfig(config);
if (!valid) {
logger.warn("Check your configuration file and try again.");
return;
}
let port = config.port || 80;
let app = express();
// technically this is optional, but logins won't work if it fails
// RMB: moved the database connection method up here
// in advance of the express_session initialisation?
// TODO: modify the logins database to apply it to the express-session
//logins.connectToDatabase(config);
// Deploy the Express session middleware
// TODO: need review on how it is being used, and perhaps adapt to Portal session management(?)
app.use(
express_session({
secret: config.session.secret || "dummy-session-secret",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: config.session.cookie.maxAge
}
})
);
// express plugins
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Elaborated session management
app.use(logins.captureClientIp);
/*
Will only insert middleware to process Google Analytics if a non-empty
Google Analytics Property Tracking identifier of format "UA-#########-#"
is configured in the config file under tag config.auth.google.UAId
*/
let ua_id = config.auth.google.UAId;
if (ua_id) {
app.use(
ExpressGA({
uaCode: ua_id,
// default GA cookie '_ga' assumed
// extract user id from request
reqToUserId: logins.getUserId,
autoTrackPages: false
})
);
}
// express settings
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
// setup routes
create_routes(config, app);
// google auth
google.useConfig(config);
// get metadata before starting server
// app.listen(port, () => logger.info(`Server started on port ${port}...`));
return app;
}
module.exports = {
start: start
};