Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions acmeaircmd/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ module.exports = function (authService,settings) {
var hystrix = require('../netflix/hystrix/index.js');
var command = require('../netflix/hystrix/command.js');

module.hystrixStream = function(request, response){
hystrix.hystrixStream(request, response);
module.hystrixStream = function(request, reply){
hystrix.hystrixStream(request, reply);
}

module.createSession = function(userid, callback /* (error, sessionId) */){
Expand Down
186 changes: 10 additions & 176 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/*******************************************************************************
* Copyright (c) 2015 IBM Corp.
* Copyright (c) 2018 nearForm
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -13,182 +14,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
'use strict'

var express = require('express')
, http = require('http')
, fs = require('fs')
, log4js = require('log4js');
var settings = JSON.parse(fs.readFileSync('settings.json', 'utf8'));
const path = require('path')

var logger = log4js.getLogger('app');
logger.setLevel(settings.loggerLevel);

// disable process.env.PORT for now as it cause problem on mesos slave
var port = (process.env.VMC_APP_PORT || process.env.VCAP_APP_PORT || settings.port);
var host = (process.env.VCAP_APP_HOST || 'localhost');

logger.info("host:port=="+host+":"+port);

var authService;
var authServiceLocation = process.env.AUTH_SERVICE;
if (authServiceLocation)
{
logger.info("Use authservice:"+authServiceLocation);
var authModule;
if (authServiceLocation.indexOf(":")>0) // This is to use micro services
authModule = "acmeairhttp";
else
authModule= authServiceLocation;

authService = new require('./'+authModule+'/index.js')(settings);
if (authService && "true"==process.env.enableHystrix) // wrap into command pattern
{
logger.info("Enabled Hystrix");
authService = new require('./acmeaircmd/index.js')(authService, settings);
}
}

var dbtype = process.env.dbtype || "mongo";

// Calculate the backend datastore type if run inside BLuemix or cloud foundry
if(process.env.VCAP_SERVICES){
var env = JSON.parse(process.env.VCAP_SERVICES);
logger.info("env: %j",env);
var serviceKey = Object.keys(env)[0];
if (serviceKey && serviceKey.indexOf('cloudant')>-1)
dbtype="cloudant";
else if (serviceKey && serviceKey.indexOf('redis')>-1)
dbtype="redis";
}
logger.info("db type=="+dbtype);

var routes = new require('./routes/index.js')(dbtype, authService,settings);
var loader = new require('./loader/loader.js')(routes, settings);

// Setup express with 4.0.0

var app = express();
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser')

app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
if (settings.useDevLogger)
app.use(morgan('dev')); // log every request to the console

//create application/json parser
var jsonParser = bodyParser.json();
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });

app.use(jsonParser);
app.use(urlencodedParser);
//parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));

app.use(methodOverride()); // simulate DELETE and PUT
app.use(cookieParser()); // parse cookie

var router = express.Router();

router.post('/login', login);
router.get('/login/logout', logout);
router.post('/flights/queryflights', routes.checkForValidSessionCookie, routes.queryflights);
router.post('/bookings/bookflights', routes.checkForValidSessionCookie, routes.bookflights);
router.post('/bookings/cancelbooking', routes.checkForValidSessionCookie, routes.cancelBooking);
router.get('/bookings/byuser/:user', routes.checkForValidSessionCookie, routes.bookingsByUser);
router.get('/customer/byid/:user', routes.checkForValidSessionCookie, routes.getCustomerById);
router.post('/customer/byid/:user', routes.checkForValidSessionCookie, routes.putCustomerById);
router.get('/config/runtime', routes.getRuntimeInfo);
router.get('/config/dataServices', routes.getDataServiceInfo);
router.get('/config/activeDataService', routes.getActiveDataServiceInfo);
router.get('/config/countBookings', routes.countBookings);
router.get('/config/countCustomers', routes.countCustomer);
router.get('/config/countSessions', routes.countCustomerSessions);
router.get('/config/countFlights', routes.countFlights);
router.get('/config/countFlightSegments', routes.countFlightSegments);
router.get('/config/countAirports' , routes.countAirports);
//router.get('/loaddb', startLoadDatabase);
router.get('/loader/load', startLoadDatabase);
router.get('/loader/query', loader.getNumConfiguredCustomers);
router.get('/checkstatus', checkStatus);

if (authService && authService.hystrixStream)
app.get('/rest/api/hystrix.stream', authService.hystrixStream);


//REGISTER OUR ROUTES so that all of routes will have prefix
app.use(settings.contextRoot, router);

// Only initialize DB after initialization of the authService is done
var initialized = false;
var serverStarted = false;

if (authService && authService.initialize)
{
authService.initialize(function(){
initDB();
});
}
else
initDB();


function checkStatus(req, res){
res.sendStatus(200);
}

function login(req, res){
if (!initialized)
{
logger.info("please wait for db connection initialized then trigger again.");
initDB();
res.sendStatus(403);
}else
routes.login(req, res);
}

function logout(req, res){
if (!initialized)
{
logger.info("please wait for db connection initialized then trigger again.");
initDB();
res.sendStatus(400);
}else
routes.logout(req, res);
}


function startLoadDatabase(req, res){
if (!initialized)
{
logger.info("please wait for db connection initialized then trigger again.");
initDB();
res.sendStatus(400);
}else
loader.startLoadDatabase(req, res);
}

function initDB(){
if (initialized ) return;
routes.initializeDatabaseConnections(function(error) {
if (error) {
logger.info('Error connecting to database - exiting process: '+ error);
// Do not stop the process for debug in container service
//process.exit(1);
}else
initialized =true;

logger.info("Initialized database connections");
startServer();
});
}


function startServer() {
if (serverStarted ) return;
serverStarted = true;
app.listen(port);
logger.info("Express server listening on port " + port);
module.exports = async (fastify, opts) => {
fastify
.register(require('./fastify-plugin'), { prefix: '/rest/api' })
.register(require('fastify-static'), {
root: path.join(__dirname, 'public'),
prefix: '/'
})
}
137 changes: 83 additions & 54 deletions authservice_app.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*******************************************************************************/

var fs = require('fs');
var Fastify = require('fastify');
var settings = JSON.parse(fs.readFileSync('settings.json', 'utf8'));
var log4js = require('log4js');
var logger = log4js.getLogger('authservice_app');
Expand All @@ -41,23 +42,52 @@ logger.info("db type=="+dbtype);

var routes = new require('./authservice/routes/index.js')(dbtype,settings);

// call the packages we need
var express = require('express');
var app = express();
var morgan = require('morgan');
var schema = {
createToken: {
params: {
type: 'object',
required: ['user'],
properties: {
user: { type: 'string' }
}
}
},
validateToken: {
params: {
type: 'object',
required: ['tokenid'],
properties: {
tokenid: { type: 'string' }
}
}
},
invalidateToken: {
params: {
type: 'object',
required: ['tokenid'],
properties: {
tokenid: { type: 'string' }
}
}
}
};

if (settings.useDevLogger)
app.use(morgan('dev')); // log every request to the console
// call the packages we need
var fastify = Fastify({ logger: settings.useDevLogger ? true : false }) // log every request to the console in development

var router = express.Router();
function router (fastify, opts, next) {
fastify.post('/byuserid/:user', { }, createToken);
fastify.get('/:tokenid', { schema: schema.validateToken }, validateToken);
fastify.get('/status', {}, checkStatus);
fastify.delete('/:tokenid', { schema: schema.invalidateToken }, invalidateToken);

router.post('/byuserid/:user', createToken);
router.get('/:tokenid', validateToken);
router.get('/status', checkStatus);
router.delete('/:tokenid', invalidateToken);
next();
}

// REGISTER OUR ROUTES so that all of routes will have prefix
app.use(settings.authContextRoot+'/authtoken', router);
fastify.register(router, {
prefix: settings.authContextRoot + '/authtoken'
})

var initialized = false;
var serverStarted = false;
Expand All @@ -82,71 +112,70 @@ function initDB(){


function startServer() {
if (serverStarted ) return;
if (serverStarted) return;
serverStarted = true;
app.listen(port);
fastify.listen(port, function (err) {
if (err) {
logger.error("Error starting server " + err);
process.exit(1)
}
});
console.log('Application started port ' + port);
}

function checkStatus(req, res){
res.sendStatus(200);
function checkStatus(req, reply){
reply.send("OK");
}

function createToken(req, res){
function createToken(req, reply){
logger.debug('create token by user ' + req.params.user);
if (!initialized)
{

if (!initialized) {
logger.info("please wait for db connection initialized then trigger again.");
initDB();
res.send(403);
}else
{
routes.createSessionInDB(req.params.user, function(error, cs){
if (error){
res.status(404).send(error);
}
else{
res.send(JSON.stringify(cs));
}
})
reply.code(403).send("Forbidden");
} else {
routes.createSessionInDB(req.params.user, function(error, cs) {
if (error) {
reply.code(404).send(error);
} else {
reply.send(JSON.stringify(cs));
}
})
}
}

function validateToken(req, res){
logger.debug('validate token ' + req.params.tokenid);
if (!initialized)
{
if (!initialized) {
logger.info("please wait for db connection initialized then trigger again.");
initDB();
res.send(403);
}else
{
reply.code(403).send("Forbidden");
} else {
routes.validateSessionInDB(req.params.tokenid, function(error, cs){
if (error){
res.status(404).send(error);
}
else{
res.send(JSON.stringify(cs));
}
})
if (error) {
reply.code(404).send(error);
} else {
reply.send(JSON.stringify(cs));
}
})
}
}

function invalidateToken(req, res){
function invalidateToken(req, reply){
logger.debug('invalidate token ' + req.params.tokenid);
if (!initialized)
{
if (!initialized) {
logger.info("please wait for db connection initialized then trigger again.");
initDB();
res.send(403);
}else
{
routes.invalidateSessionInDB(req.params.tokenid, function(error){
if (error){
res.status(404).send(error);
}
else res.sendStatus(200);
})
reply.code(403).send("Forbidden");
} else {
routes.invalidateSessionInDB(req.params.tokenid, function(error) {
if (error) {
reply.code(404).send(error);
} else {
reply.code(200).send('OK');
}
})
}
}

Loading