This repository has been archived by the owner on Oct 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
237 lines (208 loc) · 7.62 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
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
/*
* (C) Copyright 2017 o2r project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
const config = require('./config/config');
config.version = require('./package.json').version;
const debug = require('debug')('substituter');
const mongoose = require('mongoose');
const backoff = require('backoff');
const fse = require('fs-extra');
fse.mkdirsSync(config.fs.base);
fse.mkdirsSync(config.fs.compendium);
const yaml = require('js-yaml');
mongoose.Promise = global.Promise;
const dbURI = config.mongo.location + config.mongo.database;
const dbOptions = {
autoReconnect: true,
reconnectTries: Number.MAX_VALUE,
keepAlive: 30000,
socketTimeoutMS: 30000,
promiseLibrary: global.Promise,
useNewUrlParser: true
};
mongoose.connect(dbURI, dbOptions);
mongoose.connection.on('error', (err) => {
debug('Could not connect to MongoDB @ %s: %s', dbURI, err);
});
// Express modules and tools
const express = require('express');
const compression = require('compression');
const app = express();
const responseTime = require('response-time');
const bodyParser = require('body-parser');
const randomstring = require('randomstring');
var controllers = {};
controllers.substitute = require('./controllers/substitute');
controllers.substitutions = require('./controllers/substitutions');
app.use((req, res, next) => {
debug(req.method + ' ' + req.path);
next();
});
app.use(responseTime());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
// Passport & session modules for authenticating users.
const User = require('./lib/model/user');
const passport = require('passport');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
/*
* Authentication & Authorization
* This is be needed in every service that wants to check if a user is authenticated.
*/
// minimal serialize/deserialize to make authdetails cookie-compatible.
passport.serializeUser((user, cb) => {
cb(null, user.orcid);
});
passport.deserializeUser((id, cb) => {
debug("Deserialize for %s", id);
User.findOne({ orcid: id }, (err, user) => {
if (err) cb(err);
cb(null, user);
});
});
function initApp(callback) {
debug('Initialize application');
try {
// configure express-session, stores reference to auth details in cookie.
// auth details themselves are stored in MongoDBStore
var mongoStore = new MongoDBStore({
uri: dbURI,
collection: 'sessions'
}, err => {
if (err) {
debug('Error starting MongoStore: %s', err);
}
});
mongoStore.on('error', err => {
debug('Error with MongoStore: %s', err);
});
app.use(session({
secret: config.sessionsecret,
resave: true,
saveUninitialized: true,
maxAge: 60 * 60 * 24 * 7, // cookies become invalid after one week
store: mongoStore
}));
app.use(passport.initialize());
app.use(passport.session());
/*
* configure routes
*/
var Compendium = require('./lib/model/compendium');
app.post('/api/v1/substitution', (req, res) => {
res.setHeader('Content-Type', 'application/json');
if (!req.isAuthenticated()) {
res.status(401).send({"error":"not authenticated"});
return;
}
if (req.user.level < config.user.level.substitute) {
res.status(401).send({"error":"not allowed"});
return;
}
// new random id
let newID = randomstring.generate(config.id_length);
let passon = {
user: req.user.orcid,
id: newID,
metadata: {
substituted: true,
substitution: req.body
}
};
debug('[%s] Starting substitution of new compendium [base: "%s" - overlay: "%s"] ...', passon.id, passon.metadata.substitution.base, passon.metadata.substitution.overlay);
return controllers.substitute.checkBase(passon) // check base and get metadata
.then(controllers.substitute.checkOverlay) // check overlay
.then(controllers.substitute.checkSubstitutionFiles) // check the provided substitution data
.then(controllers.substitute.createFolder) // create folder with id
.then(controllers.substitute.copyBaseFiles) // copy base files into folder
.then(controllers.substitute.copyOverlayFiles) // copy overlay files into folder
.then(controllers.substitute.createVolumeBinds) // create metadata for writing to yaml
.then(controllers.substitute.updateCompendiumConfiguration) // write docker run cmd and new id to compendium configuration file
.then(controllers.substitute.updateMetadata) // update metadata of substituted compendium (paths, identifier)
.then(controllers.substitute.saveToDB) // save to DB
.then((passon) => {
debug('[%s] Finished substitution of new compendium.', passon.id);
res.status(200).send({ 'id': passon.id });
})
.catch(err => {
debug('[%s] Error during substitution: %s', passon.id, err);
let status = 500;
if (err.status) {
status = err.status;
}
let msg = 'Internal error';
if (err.msg) {
msg = err.msg;
}
res.status(status).send({ error: msg });
});
});
// GET list of substitution
app.get('/api/v1/substitution', controllers.substitutions.view);
// GET list of related substitutions by filter "base" and/or "overlay"
var server = app.listen(config.net.port, () => {
debug('substituter %s with API version %s waiting for requests on port %s',
config.version,
config.api_version,
config.net.port);
});
server.timeout = 30000;
} catch (err) {
callback(err);
}
callback(null);
}
var dbBackoff = backoff.fibonacci({
randomisationFactor: 0,
initialDelay: config.mongo.initial_connection_initial_delay,
maxDelay: config.mongo.initial_connection_max_delay
});
dbBackoff.failAfter(config.mongo.initial_connection_attempts);
dbBackoff.on('backoff', function (number, delay) {
debug('Trying to connect to MongoDB (#%s) in %sms', number, delay);
});
dbBackoff.on('ready', function (number, delay) {
debug('Connect to MongoDB (#%s)', number, delay);
mongoose.connect(dbURI, dbOptions, (err) => {
if (err) {
debug('Error during connect: %s', err);
mongoose.disconnect(() => {
debug('Mongoose: Disconnected all connections.');
});
dbBackoff.backoff();
} else {
// delay app startup to when MongoDB is available
debug('Initial connection open to %s: %s', dbURI, mongoose.connection.readyState);
initApp((err) => {
if (err) {
debug('Error during init!\n%s', err);
mongoose.disconnect(() => {
debug('Mongoose: Disconnected all connections.');
});
dbBackoff.backoff();
} else {
debug('Started application.');
}
});
}
});
});
dbBackoff.on('fail', function () {
debug('Eventually giving up to connect to MongoDB');
process.exit(1);
});
dbBackoff.backoff();