-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
439 lines (389 loc) · 17.1 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#!/bin/env node
// OpenShift sample Node application
var express = require('express');
var cors = require('cors');
var fs = require('fs');
var mongo = require('./mongo.js');
var cas = require('./cas.js');
var ubertool= require('./ubertool.js');
var batch = require('./batch.js');
var user = require('./user.js');
var formula = require('./formula.js');
var batch_amqp = require('./batch_amqp.js');
/**
* Define the sample application.
*/
var App = function() {
// Scope.
var self = this;
var db = mongo.getDB();
cas.setDB(db);
ubertool.setDB(db);
user.setDB(db);
formula.setDB(db);
batch.setDB(db);
/* ================================================================ */
/* Helper functions. */
/* ================================================================ */
/**
* Set up server IP address and port # using env variables/defaults.
*/
self.setupVariables = function() {
// Set the environment variables we need.
self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
self.port = process.env.OPENSHIFT_NODEJS_PORT || 8081;
if (typeof self.ipaddress === "undefined") {
// Log errors on OpenShift but continue w/ 127.0.0.1 - this
// allows us to run/test the app locally.
console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
self.ipaddress = "127.0.0.1";
};
};
/**
* Populate the cache.
*/
self.populateCache = function() {
if (typeof self.zcache === "undefined") {
self.zcache = { 'index.html': '' };
}
// Local cache for static content.
self.zcache['index.html'] = fs.readFileSync('./index.html');
};
/**
* Retrieve entry (content) from cache.
* @param {string} key Key identifying content to retrieve from cache.
*/
self.cache_get = function(key) { return self.zcache[key]; };
/**
* terminator === the termination handler
* Terminate server on receipt of the specified signal.
* @param {string} sig Signal to terminate on.
*/
self.terminator = function(sig){
if (typeof sig === "string") {
console.log('%s: Received %s - terminating sample app ...',
Date(Date.now()), sig);
process.exit(1);
}
console.log('%s: Node server stopped.', Date(Date.now()) );
};
/**
* Setup termination handlers (for exit and a list of signals).
*/
self.setupTerminationHandlers = function(){
// Process on exit and signals.
process.on('exit', function() { self.terminator(); });
// Removed 'SIGPIPE' from the list - bugz 852598.
['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
].forEach(function(element, index, array) {
process.on(element, function() { self.terminator(element); });
});
};
/* ================================================================ */
/* App server functions (main app logic here). */
/* ================================================================ */
/**
* Create the routing table entries + handlers for the application.
*/
self.createRoutes = function() {
self.routes = { };
self.post_routes = { };
self.routes['/cas/:cas_num'] = function(req, res) {
console.log("/cas/" + req.params.cas_num + " REST API reached ");
cas.getChemicalName(req.params.cas_num, function(error,chem_name){
res.send(chem_name);
});
};
self.routes['/all-cas'] = function(req, res) {
console.log("/all-cas REST API reached");
cas.getAll(function(error,all_cas){
res.send(all_cas);
});
};
self.routes['/casdata/:chemical_name'] = function(req, res) {
var chemical_name = req.params.chemical_name;
console.log("Chemical Name: " + chemical_name);
cas.getChemicalData(chemical_name, function(error,cas_data){
if(cas_data != null)
{
res.send(cas_data);
}
});
};
self.routes['/ubertool/:config_type/config_names'] = function(req, res) {
var config_type = req.params.config_type;
console.log("Config Type: " + config_type);
ubertool.getAllConfigNames(config_type,function(error,config_names){
res.send(config_names);
});
};
self.routes['/ubertool/:config_type/:config'] = function(req, res) {
var config_type = req.params.config_type;
var config = req.params.config;
ubertool.getConfigData(config_type,config,function(error,config_data){
res.send(config_data);
});
};
self.post_routes['/batch'] = function submitBatch(req, res){
console.log("Batch Submitted to Node.js server.");
var json = req.body;
var results = batch_amqp.submitUbertoolBatchRequest(json);
res.send("Submitting Batch.\n");
};
self.routes['/batch_configs'] = function(req, res, next) {
batch.getBatchNames(function(error, batch_ids){
res.send(batch_ids);
});
};
self.routes['/batch_results/:batchId'] = function(req, res, next) {
var batchId = req.params.batchId;
console.log("BatchId: " + batchId);
batch.getBatchResults(batchId, function(error, batch_data){
if(batch_data != null)
{
res.send(batch_data);
} else {
res.send("Problem returning results");
}
});
};
self.post_routes['/batch_results/:batchId'] = function(req,res,next){
var batchId = req.params.batchId;
console.log("BatchId: " + batchId);
var body = '';
req.on('data', function (data)
{
body += data;
});
req.on('end', function ()
{
console.log("body: " + body);
var json = JSON.parse(body);
var user_id = json.user_id;
var user_api_key = json.api_key;
console.log("json user_id: " + user_id + " user_api_key: " + user_api_key);
user.authenticateRestAccess(user_id,user_api_key,function(err,authenticated){
console.log("authenticated: " + authenticated);
if(authenticated){
batch.getBatchResults(batchId, function(error, batch_data){
if(batch_data != null)
{
res.send(batch_data);
} else {
res.send("Problem returning results");
}
});
} else {
console.log('User API Authentication failed');
res.send("User: " + user_id + " passed an incorrect api key and cannot call this method.");
}
});
});
};
self.post_routes['/ubertool/:config_type/:config'] = function(req,res){
var config_type = req.params.config_type;
var config = req.params.config;
var body = '';
var json = '';
req.on('data', function (data)
{
body += data;
});
req.on('end', function ()
{
json = JSON.parse(body);
ubertool.addUpdateConfig(config_type,config,json, function(error, results)
{
res.send(results);
});
});
};
self.post_routes['/user/login/:userid'] = function(req, res, next){
var user_id = req.params.userid;
console.log('user id: ' + user_id);
var body = '';
req.on('data', function (data)
{
body += data;
});
req.on('end', function ()
{
json = JSON.parse(body);
user.getLoginDecision(user_id,json.password,function(err, decision_data){
if(decision_data.decision)
{
var acsid_string = "test="+decision_data.sid;
console.log("acsid_string: " + acsid_string);
res.header('Set-Cookie',acsid_string);
}
res.send(decision_data);
});
});
};
self.post_routes['/user/registration/:user_id'] = function(req, res, next){
var user_id = req.params.user_id;
console.log('user id: ' + user_id);
var body = '';
req.on('data', function (data)
{
body += data;
});
req.on('end', function ()
{
json = JSON.parse(body);
console.log(json);
console.log('password: ' + json.pswrd);
console.log('email address: ' + json.email_address);
user.registerUser(user_id,json.pswrd,json.email_address,function(err, sid_data){
res.send(sid_data);
});
});
};
self.post_routes['/user/openid/login'] = function(req, res, next){
var body = '';
req.on('data', function (data)
{
body += data;
});
req.on('end', function ()
{
var json = JSON.parse(body);
user.openIdLogin(json.openid, function(err, login_data){
res.send(login_data);
});
});
};
self.post_routes['/user/sessionid'] = function(req, res, next){
var body = '';
req.on('data', function (data)
{
body += data;
});
req.on('end', function ()
{
var json = JSON.parse(body);
var user_id = json['user_id'];
var session_id = json['session_id'];
console.log("User id: " + user_id + " session id: " + session_id);
user.checkUserSessionId(user_id, session_id, function(err, decision_data){
console.log(decision_data);
res.send(decision_data);
});
});
};
self.routes['/all-cas'] = function(req, res, next){
cas.getAll(function(error,all_cas){
res.send(all_cas);
});
};
//Formula Services
self.routes['/formula/:registration_num'] = function(req, res, next){
var registration_num = req.params.registration_num;
console.log("Registration Number: " + registration_num);
formula.getFormulaData(registration_num, function(error,chemicals){
console.log(chemicals)
res.send(chemicals);
});
};
self.routes['/formulas/:pc_code'] = function(req, res, next){
var pc_code = req.params.pc_code;
console.log("PC Code: " + pc_code);
formula.getFormulaDataFromPCCode(pc_code, function(error,chemical){
res.send(chemical);
});
};
self.routes['/all_formula'] = function(req, res, next){
formula.getAllFormulaData(function(error,formula_data){
res.send(formula_data);
});
};
self.routes['/api'] = function(req, res) {
console.log("Describe REST API");
var apiDescription = "/user/login/:userid<br>"+
"POST: Decides if the password passed in the json in the body of the request (key password) is valid for the user id as the last part of the url. Returns a json document with the decision(true/false), the sessionId, expiration date time. It adds a value to the passed cookie that tells google appengine that the user is valid to view protected pages.<br>"+
"/user/registration/:user_id<br>"+
"POST: registers a user given the user id as the last part of the url and the password and email address passed as arguments in the json request. Returns a json document with the sessionId, expiration date time.<br>"+
"/user/openid/login<br>"+
"POST: Using the openId passed in the json request, retrieves the userId, sessionId, and expiration date time for the sessionID. <br>"+
"/user/sessionid<br>"+
"POST: Attempts to validate a sessionId for a userId, both passed as arguments in the json request. Returns a json document with the decision(true/false), the sessionId, expiration date time.<br>"+
"/batch_configs<br>"+
"GET: Retrieves all the names for batch configurations in the system. No parameters are passed<br>"+
"/batch<br>"+
"POST: Submits a batch configuration to the asynchronous batching system via ActiveMQ.<br>"+
"/batch_results/:batchId <br>"+
"GET: Retrieves the results of an ubertool batch, based on the batchId passed in the URL. Returns a hierarchical JSON data.<br>"+
"POST: Similar to GET request, except that it authenticates the userId along with an apiKey (both passed as arguments in the json documents). If authenticated to a valid user, will retrieve results.<br>"+
"/cas/:cas_num<br>"+
"GET: Retrieves the chemical name associated with a CAS number<br>"+
"/casdata/:chemical_name<br>"+
"GET: Retrieves the CAS Number and PC Code<br>"+
"/all-cas<br>"+
"GET: Retrieves all of the CAS Numbers<br>"+
"/formula/:registration_num<br>"+
"GET: Retrieves formulation data based on a registration number. This service returns PC Percentage, Product Name, and PC Code in the json response.<br>"+
"/formulas/:pc_code<br>"+
"GET: Retrieves all of the formulations given a PC Code. The return is a json document containing an array of data, each data record contains Registration Number, PC Percentage, Product Name, and PC Code"+
"/all_formula"+
"GET: Retrieves all of the formulations available. The return is a json document containing an array of data, each data record contains Registration Number, PC Percentage, Product Name, and PC Code"+
"/ubertool/:config_type/config_names"+
"GET: Retrieves all configurations for a given ubertool configuration (use, pest, aqua, eco, expo, terre, ubertool). Returns a json document, with a variety of properties."+
"/ubertool/:config_type/:config"+
"GET: Retrieves a configuration for a given ubertool configuration (use, pest, aqua, eco, expo, terre, ubertool) based on a specific configuration ID (the last part of the url). Returns a json document, with a variety of properties."+
"POST: Places an ubertool configuration into the mongo db, which can be referenced by ubertool configurations and is the basis for running an ubertool batch."+
"/api-key"+
"GET: Retrieves an API Key, though this is not stored to a user, just a means of generating an API key. ";
res.send(apiDescription);
}
self.routes['/'] = function(req, res) {
res.setHeader('Content-Type', 'text/html');
res.send(self.cache_get('index.html') );
};
};
/**
* Initialize the server (express) and create the routes and register
* the handlers.
*/
self.initializeServer = function() {
self.createRoutes();
self.app = express();
self.app.use(cors());
self.app.configure(function(){
self.app.use(express.bodyParser());
});
// Add handlers for the app (from the routes).
for (var r in self.routes) {
self.app.get(r, self.routes[r]);
}
for (var r in self.post_routes) {
self.app.post(r, self.post_routes[r]);
}
};
/**
* Initializes the sample application.
*/
self.initialize = function() {
self.setupVariables();
self.populateCache();
self.setupTerminationHandlers();
// Create the express server and routes.
self.initializeServer();
};
/**
* Start the server (starts up the sample application).
*/
self.start = function() {
// Start the app on the specific interface (and port).
self.app.listen(self.port, self.ipaddress, function() {
console.log('%s: Node server started on %s:%d ...',
Date(Date.now() ), self.ipaddress, self.port);
});
};
}; /* Sample Application. */
/**
* main(): Main code.
*/
var zapp = new App();
zapp.initialize();
zapp.start();