Esempio n. 1
0
    function Tomahawk(config) {
        var $this         = this,
            shutdownHooks = [];
            
        this.config  = opts.mergeEnvironment(opts.merge(config ? config : {}, baseConfig));
        this.meta    = this.config.meta ? this.config.meta : (this.config.name + '-Engine');
        if (this.config.logger) {
            this.logger = this.config.logger
        } else {
            var winston = require('winston'),
                meta = {
                    "module": $this.config.name || $this.meta,
                    "pid": process.pid
                };
            $this.logger = new (winston.Logger)({ transports: [
                new (winston.transports.Console)({
                    "level": $this.config.level || "info",
                    "json": false,
                    "colorize": true
                })
            ]});
        }
        
        if (!this.config.www) this.config.www = process.cwd();
        if (this.config.www.charAt(0) !== '/')
            this.config.www = path.join(process.cwd(), this.config.www);
        this.headers = _parseHTTPHeaders(this.config.headers, this.logger, this.meta);

        this.app     = express();
        this.server  = http.Server(this.app);
        this.io      = socketio(this.server);

        $this.app.use(morgan('combined', {
            stream : {
                write : function (message, encoding) {
                    if ($this.logger && $this.logger.log) {
                        $this.logger.log('info', message.replace(/\n/, ''), $this.meta);
                    }
                }
            }
        }));

        $this.app.use(bodyparser.urlencoded({ extended: true }));

        var requestBodyParser = $this.config.bodyparser instanceof Array ? $this.config.bodyparser : (typeof($this.config.bodyparser) === 'string' ? [$this.config.bodyparser] : ['./bodyparser']);
        for (var i = 0 ; i < requestBodyParser.length ; ++i) {
            $this.logger.log('info', 'requestBodyParser %s', requestBodyParser[i], $this.meta);
            require(requestBodyParser[i])($this.app, $this.config);
        }

        $this.app.use(function(req, res, next) {
            for (var i = 0 ; i < $this.headers.length ; ++i) {
                res.setHeader($this.headers[i].name, $this.headers[i].value);
            }
            return next();
        });
        if ($this.config.context) {
            $this.app.use($this.config.context, express.static($this.config.www));
        }
        if ($this.level === 'error') {
            $this.app.use(errorhandler());
        } else {
            $this.app.use(errorhandler());
        }

        process.on('exit', function() {
            shutdownHooks.forEach(function (hook) {
                hook();
            });
            $this.logger.log('error', 'EXIT', $this.meta);
        });
        process.on('SIGINT', function() {
            shutdownHooks.forEach(function (hook) {
                hook();
            });
            $this.logger.log('warn', 'SIGINT', $this.meta);
            process.exit(0);
        });
        
        ////////////////////////////////////////////////////////////////////////
        var pluginPath = path.join($this.config.rootPath, "..");
        $this.logger.log('debug', 'plugin-path: %s', pluginPath, $this.meta);
        for (var prop in $this.config.plugins) {
            if ($this.config.plugins.hasOwnProperty(prop)) {
                var plugin = $this.config.plugins[prop];
                var thisPluginPath = (plugin.implementation.charAt(0) === '/') ? plugin.implementation.charAt(0) : path.join(pluginPath, plugin.implementation);
                $this.logger.log('debug', 'plugin[%s]:%j', prop, path.join(thisPluginPath, "package.json"), $this.meta);
                var pluginPkgConfig = JSON.parse(fs.readFileSync(path.join(thisPluginPath, "package.json")));
                var pluginImpl = require(path.join(thisPluginPath, pluginPkgConfig.main));
                config[prop] = $this.config[prop] = pluginImpl($this.app, $this.config, $this.io, $this);
                if ($this.config[prop] && $this.config[prop].shutdown) {
                    shutdownHooks.push($this.config[prop].shutdown);
                }
                if ($this.config[prop] && $this.config[prop].constructor) {
                    $this.config[prop].constructor();
                }
            }
        }

        var routes = $this.config.routes instanceof Array ? $this.config.routes : (typeof($this.config.routes) === 'string' ? [$this.config.routes] : []);
        for (var i = 0 ; i < routes.length ; ++i) {
            $this.logger.log('debug', 'loading module: %s', routes[i], $this.meta);
            var routehooks = require(
                                        routes[i].charAt(0) === '/' ? routes[i] : 
                                        path.join($this.config.rootPath, "lib", routes[i])

                                    )($this.app, $this.config, $this.io, $this);
            if (routehooks && routehooks.shutdown) {
                shutdownHooks.push(routehooks.shutdown);
            }
        }
        var cgi = $this.config.cgi instanceof Array ? $this.config.cgi : (typeof($this.config.cgi) === 'string' ? [$this.config.cgi] : []);
        $this.logger.log('debug', 'cgis: %j', cgi, $this.meta);

        function createRouteCGI(app, cgi) {
           var method  = cgi.method || "GET";

           function handler(req, res) {
                var command = cgi.command;
                var args    = cgi.args || [];

                $this.logger.log('debug', 'spawn: %s [args:%j]', command, args, $this.meta);
                var child   = spawn(command, args);

                if (cgi.encoding)
                    child.stdin.setEncoding(cgi.encoding);

                child.stderr.on('data', function (data) {
                    $this.logger.log('debug', 'stderr: %s', (''+data), $this.meta);
                    res.write(data);
                });
                child.stdout.on('data', function (data) {
                    $this.logger.log('debug', 'stdout: %s', (''+data), $this.meta);
                    res.write(data);
                });

                child.on('close', function (code) {
                    $this.logger.log('debug', 'close', $this.meta);
                    res.end();
                });
                req.on('data', function (data) {
                    $this.logger.log('read %s', (''+data), $this.meta);
                    child.stdin.write(data);
                });
                req.on('end', function (data) {
                    $this.logger.log('end %s', (''+data), $this.meta);
                    if (data)
                        child.stdin.end(data);
                    else 
                        child.stdin.end();
                });
            }
            if (method === 'GET') {
                app.get(cgi.route, handler);
            } else if (method === 'POST') {
                app.post(cgi.route, handler);
            } else if (method === 'PUT') {
                app.put(cgi.route, handler);
            } else if (method === 'DELETE') {
                app.delete(cgi.route, handler);
            }

        }
        for (i = 0 ; i < cgi.length ; ++i) {
            createRouteCGI($this.app, cgi[i]);
        }
    }
Esempio n. 2
0
  Ce serveur accepte une requête HTTP upgrade et établit
  une connexion persistante basée sur WebSocket.
**/

/**
  On installe et on utilise le package socket.io.
  La documentation est ici :
  - https://www.npmjs.com/package/socket.io
  - https://github.com/socketio/socket.io
  - http://socket.io/
**/
var socketIO = require('socket.io');

//  On utilise utilise la fonction obtenue avec notre serveur HTTP.
var socketIOWebSocketServer = socketIO(httpServer);

/**
  Gestion de l'événement 'connection' : correspond à la gestion
  d'une requête WebSocket provenant d'un client WebSocket.
**/
var tabScore = [{pseudo: 'DaBest', score: 6}];
var tabUser= [{pseudo: 'machin'}];
var tabPerso = [{id: 'lightblue50', color: 'lightblue', top: '50px'}, {id: 'green100', color: 'green', top: '100px'}, {id: 'yellow150', color: 'yellow', top: '150px'}, {id: 'blue200', color: 'blue', top: '200px'}, {id: 'pink250', color: 'pink', top: '250px'}, {id: 'grey300', color: 'grey', top: '300px'}, {id: 'lightgreen350', color: 'lightgreen', top: '350px'}, {id: 'white400', color: 'white', top: '400px'}];
var tabDispo = [{name: 'lightblue50', position: 50, enmove: false}, {name: 'green100', position: 50, enmove: false}, {name: 'yellow150', position: 50, enmove: false}, {name: 'blue200', position: 50, enmove: false}, {name: 'pink250', position: 50, enmove: false}, {name: 'grey300', position: 50, enmove: false}, {name: 'lightgreen350', position: 50, enmove: false}, {name: 'white400', position: 50, enmove: false}];
var toutLeMondeEstLa = 0;
var perdu = false;
socketIOWebSocketServer.on('connection', function (socket) {

  // socket : Est un objet qui représente la connexion WebSocket établie entre le client WebSocket et le serveur WebSocket.
Esempio n. 3
0
                        break;
                case '/terminal.js':
                        file = '/node_modules/terminal.js/dist/terminal.js';
                        break;
                case '/socket.io-stream.js':
                        file = '/node_modules/socket.io-stream/socket.io-stream.js';
                        break;
                default:
                        res.writeHead(404, {'Content-Type': 'text/plain'});
                        res.end('404 Not Found');
                        return;
                }
                fs.createReadStream(__dirname + file).pipe(res);
        });

socketio(server).of('pty').on('connection', function(socket) {
        // receives a bidirectional pipe from the client see index.html
        // for the client-side
        ss(socket).on('new', function(stream, options) {
                var name = options.name;

                var pty = child_pty.spawn('zsh', options);
                pty.stdout.pipe(stream).pipe(pty.stdin);
                ptys[name] = pty;
                socket.on('disconnect', function() {
                        console.log("end");
                        pty.kill('SIGHUP');
                        delete ptys[name];
                });
        });
});
Esempio n. 4
0
var  express = require('express'),
     app = express(),
     socketIO = require('socket.io'),
     //http = require('http'),
     //crypto = require('crypto'),
     //key = "ladkfjeoijiejoef9878euofjopd6y7e452vjl",
     server = require('http').createServer(app),
     io = socketIO(server);

var generateMessage = function(from, text){
    return {
        from,
        text
    };
};
var isRealString = function(str) {
    return typeof str === 'string' && str.trim().length > 0;
};
var users = [];
function addUser(id, name, room){
    var user = {id, name, room};
    users.push(user);
    return user;
};
function removeUser(id){
    var user = getUser(id);
    if(user){
        users = users.filter((user) => user.id !== id);
    };
    return user;
};
Esempio n. 5
0
//read the client html file into memory
//__dirname in node is the current directory
//in this case the same folder as the server js file
var index = fs.readFileSync(__dirname + '/../client/client.html');

function onRequest(request, response) {

 response.writeHead(200, {"Content-Type": "text/html"});
 response.write(index);
 response.end();
}
var app = http.createServer(onRequest).listen(port);
console.log("Listening on 127.0.0.1:" + port);

//pass in the http server into socketio and grab the websocket server as io
var io = socketio(app);
var allSquares = {};

// When there is a server connection
io.sockets.on("connection", function(socket) {

  socket.join('Main Room');

  socket.on('newRect', function(data) {
    allSquares[data.time] = {
      x: data.coords.x,
      y: data.coords.y,
      width: data.coords.width,
      height: data.coords.height
    };
    io.sockets.in('Main Room').emit('updateCanvas', allSquares);
Esempio n. 6
0
var socket;
app.use(express.static(__dirname + "/client"));
app.use(express.bodyParser());

// connect to the amazeriffic 
mongoose.connect("mongodb://localhost/amazeriffic");

var ToDoSchema = mongoose.Schema({
    description: String,
    tags: [ String ]
});

var ToDo = mongoose.model("ToDo", ToDoSchema);

var server = http.createServer(app);
var io = socketIo(server);
server.listen(3000);

io.on("connection",function(skt){
   "use strict";
   
   console.log("connected to server");
   socket = skt;
});


app.get("/todos.json", function (req, res) {
    "use strict";

    ToDo.find({}, function (err, toDos) {
        res.json(toDos);
Esempio n. 7
0
var MongoClient = require('mongodb').MongoClient;
var server = require('http').Server(app);
var httpServer = http.createServer();
var router = express.Router(); 
var mongo = require('mongodb');
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
var user = {};
var maDb;
var today;
var userConnected = {};
var fromTo;
var room = 0;
var multer = require('multer');
const socketIo = require('socket.io');
var IOServer = socketIo(httpServer);
setInterval(function(){
	var dayMonth = new Date().getDate();
	var objToday = new Date(),
	    weekday = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'),
	    dayOfWeek = weekday[objToday.getDay()],
	    domEnder = new Array( '', '', '', '', '', '', '', '', '', '' ),
	    dayOfMonth = today + (objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder[objToday.getDate()] : objToday.getDate() + domEnder[parseFloat(("" + objToday.getDate()).substr(("" + objToday.getDate()).length - 1))],
	    months = new Array('Janvier', 'Fevrier', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'),
	    curMonth = months[objToday.getMonth()],
	    curYear = objToday.getFullYear(),
	    curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),
	    curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),
	    curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),
	    curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";
		today = dayOfWeek + " " + dayMonth + "  " + curMonth + ' ' + curYear + ", " + curHour + ":" + curMinute + "." + curSeconds + ' '+ curMeridiem + " ";
Esempio n. 8
0
 createIOServer(port, options) {
     if (this.httpServer && port === 0) {
         return io(this.httpServer, options);
     }
     return io(port, options);
 }
var io = require('socket.io');
var ioc = require('socket.io-client');
var redis = require('socket.io-redis');

var srv = io(8125);
srv.adapter(redis({ host: 'localhost', port: 6380 }));
var nsp = srv.of('/nsp');

var cli = ioc('ws://localhost:8125', {forceNew: true});

cli.on('broadcast event', function(payload) {
  console.log(payload);
});

cli.on('nsp broadcast event', function(payload) {
  console.log("BAD");
});

var cliNsp = ioc('ws://localhost:8125/nsp', {forceNew: true});

cliNsp.on('broadcast event', function(payload) {
  console.log(payload);
});

cliNsp.on('nsp broadcast event', function(payload) {
  console.log("GOOD");
});
Esempio n. 10
0
var io = require('socket.io');
var http = require('http');
var fs = require('fs');
var server;

app.use(router(app));
app.use(stat('./public'));
app.get('/rooms', rooms);

app.use(function *() {
    this.type = 'text/html';
    this.body = fs.createReadStream('./public/index.html');
});

server = http.Server(app.callback());
io = io(server);

io.on('connection', function (socket) {
	socket.on('join', function (data) {
		socket.join(data.id);
		set(socket, {name: '<username>'});
		sync(socket);
	});
	socket.on('leave', function (data) {
		socket.leave(data.id);
		sync(socket);
	});
	socket.on('username', function (name) {
		set(socket, {name: name});
		sync(socket);
	});
Esempio n. 11
0
import routes from '~/core/rest';
import apolloServer from '~/core/graphql';
import mongoose from '~/core/mongoose';
import sequelize from '~/core/sequelize';
import passport from '~/core/passport';
import redis from '~/core/redis';

import {
  NODE_ENV, PORT, HOST, SECRET, RATE_LIMIT,
  SENTRY_DSN, STATIC_FILES, RENDERTRON_URL,
} from './env';

const app = express();
const server = http.Server(app);
const io = socket(server);

app.set('socket', io);

if (NODE_ENV === 'production') Raven.config(SENTRY_DSN).install();

/**
 * @name middleware-functions
 */
app.use(helmet());
app.use(cors());
app.use(rateLimit({ max: Number(RATE_LIMIT), windowMs: 15 * 60 * 1000 }));
app.use(compression());
app.use(morgan('tiny'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
Esempio n. 12
0
function createChat(server) {
  var guestNumber = 1;
  var nickNames = {};
  var currentRooms = {};
  io = io(server);

  io.on('connection', function (socket) {
     
    socket.on('disconnect', function() {
      var name = nickNames[socket.id];
      io.emit('logout', { 
        name: name, 
        allUsers: nickNames
      });
      delete nickNames[socket.id];
    })
    
    nickNames[socket.id] = 'guest' + guestNumber;
    guestNumber += 1;
    
    currentRooms[socket.id] = 'lobby';
    socket.join(currentRooms[socket.id]);
    
    io.to(currentRooms[socket.id]).emit('nicknameChangeResult', {
      allUsers: nickNames,
      message: "logged in as " + nickNames[socket.id] 
    });

    function processCommand (data) {
      if (data['message'].slice(0, 6) === '/nick ') {
        var name = data['message'].slice(6);
        io.to(currentRooms[socket.id]).emit('nicknameChangeRequest', { name: name })
      } else if (data['message'].slice(0, 6) === '/join ') {
        var newRoom = data['message'].slice(6);
        handleRoomChangeRequests(newRoom);
      }
    }
    
    function handleRoomChangeRequests (newRoom) {
      socket.leave(currentRooms[socket.id]);
      currentRooms[socket.id] = newRoom;      
      socket.join(newRoom);
    }

    socket.on('message', function (data) {
      if (data['message'][0] === '/') {
        processCommand(data);
      } else {
        io.to(currentRooms[socket.id]).emit('server_message', { 
          text: data['message'],
          username: nickNames[socket.id]
         }); 
      }
    });
    
    function nameTaken(name) {
      Object.keys(nickNames).forEach(function(key) {
        if (name === nickNames[key]) { return true; }
      })
      return false;
    }
    
    
    socket.on('nicknameChangeRequest', function(data) {
      if ((data['name'].slice(0,5) === 'guest') || (nameTaken(data['name']))) {
        socket.emit('nicknameChangeResult', {
          success: false,
          message: 'Names cannot begin with "Guest".'
        });    
      } else {
        var oldName = nickNames[socket.id]
        nickNames[socket.id] = data['name'];
        io.emit('nicknameChangeResult', {
          success: true,
          oldName: oldName,
          newName: nickNames[socket.id],
          message: 'Name changed',
          allUsers: nickNames
        });
      }
    });
  });
}
Esempio n. 13
0
const express = require('express');
const path = require('path');
const http = require('http');
const socketIO = require('socket.io');
const consign = require('consign');
const bodyParser = require('body-parser');
const cookie = require('cookie');
const expressSession = require('express-session');
const methodOverride = require('method-override');
const config = require('./config');
const error = require('./middlewares/error');

const app = express();
const server = http.Server(app);
const io = socketIO(server);
const store = new expressSession.MemoryStore();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(expressSession({
  store,
  resave: true,
  saveUninitialized: true,
  name: config.sessionKey,
  secret: config.sessionSecret
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')));
Esempio n. 14
0
File: app.js Progetto: NITD/iot
var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/api');
var users = require('./app_server/routes/users');

var app = express();

//Cross domains
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  next();
});

//Socket.io
var io = socket_io();
app.io = io;
require('./app_server/sockets/socket')(io);

// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
Esempio n. 15
0
/**
 * init webSocket
 * @param expressApp
 * @private
 */
function _init(httpServer, onComplete) {

  /** disable if not desired */
  if (!process.env.USE_WEBSOCKETS) {
    onComplete();
    return;
  }

  /** create socket */
  io = socketIO(
    httpServer,
    {
      'upgrade': true,
      'allowUpgrades': true,
      'match original protocol': true,
      'secure': true,
      'pingTimeout': 25000,
      'pingInterval': 10000
    }
  );

  /** waterfall the events init */
  async.waterfall([

      // get all events name
      function getWsEvents(wfcallback) {
        _getConfigurationService().getPropertiesArray(DYNAMIC_EVENTS, wfcallback);
      },

      // get single events
      function getSingleEvents(eventsArray, wfcallback) {

        async.each(eventsArray, function (event, eachCallback) {
          // Perform operation on file here.
          console.log(MODULE_NAME + ': processing event ' + event);
          _getConfigurationService().getPropertiesJsonByRoot(
            EVENT_ROOT + event,
            function onConfig(err, val) {
              eventsConf[event] = val;
              eachCallback(err);
            });

        }, function (err) {
          if (err) {
            console.error(MODULE_NAME + ': events processing FAILED');
            wfcallback(err);
          } else {
            console.log(MODULE_NAME + ': event conf loading ok');
            wfcallback();
          }

        });
      },

      // register events on socketio
      function register(wfcallbakc) {
        _registerSocketEvents(io, wfcallbakc);
      }
    ],
    onComplete
  );


}
Esempio n. 16
0
const http = require('http')
const express = require('express')
const socketIo = require('socket.io')
const _ = require('lodash')
const app = express()
const port = process.env.PORT || 3000
const createLife = require('./createLife.js')
const selfupRejs = require('selfup-rejs')
const rejs = new selfupRejs

const server = http.createServer(app)
  .listen(port, () => {
  console.log('Listening on port ' + port + '.')
})

const io = socketIo(server)

app.use(express.static('public'))
app.set('view engine', 'ejs')

app.get('/', (req, res) => {
  res.render('universe')
})


io.sockets.on('connection', socket => {

  let status = ""

  socket.on('message', (channel, message) => {
    let makeNewUniverses = () => {
	constructor(httpServer, bulletDB) {
		this.io = socketio(httpServer);
		this.bulletDB = bulletDB;
	}
Esempio n. 18
0
module.exports = function(DB, PORT) {
  var app = express();
  var server = http.Server(app);
  var io = socketIO(server);

  passport.use(new BasicStrategy({}, function(username, password, done) {
    var params = { username: username };

    DB.Users.findByParams(params)
      .then(R.head)
      .then(function(user) {
        if (!user) throw 'not authorized';

        return DB.Utils.eqPasswords(password, user.password)
          .then(function() {
            return done(null, user);
          });
      })
      .catch(function(err) {
        done(null, false, { message: 'You are not authorized' });
      });
  }));

  app.use(morgan('tiny', { stream: accessLogStream }));
  app.use(cors());
  app.use(passport.initialize());
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));

  app.post('/register', function(req, res) {
    DB.Users.insert(req.body)
      .then(function(user) {
        res.json(user);
      })
      .catch(function(err) {
        res.status(500).json({ error: err });
      });
  });

  app.get('/me',
    passport.authenticate('basic', { session: false }),
    function(req, res) {
      res.json(req.user);
    }
  );

  app.get('/users',
    passport.authenticate('basic', { session: false }),
    function(req, res) {
      DB.Users.all()
        .then(function(users) {
          res.json(users);
        })
        .catch(function() {
          res.status(500);
        });
    }
  );

  app.post('/answers',
    passport.authenticate('basic', { session: false }),
    function(req, res) {
      var params = {
        userId: req.user.id,
        questionId: req.body.questionId,
        answerId: req.body.answerId
      };

      DB.Answers.insertGameAnswer(params)
        .then(function(answer) {
          res.json(answer);
        })
        .catch(function(err) {
          res.status(500).json({ message: err });
        });
    }
  );

  app.use(function handle404(req, res) {
    res.status(404).end('not found');
  });

  app.use(function handleError(err, req, res) {
    console.error(err.stack);
    res.status(500).json({err: err.message});
  });

  DB.Broadcast.subscribe(function(cursor) {
    cursor.each(function(err, object) {
      io.emit(object.topic, object.args);
    });
  });

  DB.Users.changes().then(function(cursor) {
    cursor.each(function(err, user) {
      if (err) return;

      io.emit('users:update', user);
    });
  });

  server.listen(PORT);

  return app;
};
Esempio n. 19
0
"use strict";
const fs = require('fs');
const path = require('path');
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const platform_1 = require('./platform');
const webPort = parseInt(process.env.PORT || 3001);
const confDir = path.join(__dirname, '..', 'configuration', process.platform);
const browserDir = path.join(__dirname, '..', 'browser');
const app = express();
const httpd = http.createServer(app);
const io = socketIO(httpd, { pingInterval: 1000, pingTimeout: 2500 });
app.use(express.static(confDir));
app.use(express.static(browserDir));
app.get('/', function (req, res) {
    res.redirect('/index.html');
});
app.get('/screens', function (req, res) {
    fs.readdirSync(confDir).forEach(fileName => {
        if (/screen\..+\.html/.test(fileName)) {
            const filePath = path.join(confDir, fileName);
            const html = fs.readFileSync(filePath);
            res.write(html);
        }
    });
    res.end();
});
io.on('connection', function (socket) {
    socket.on('type', function (text, callback) {
        platform_1.default.type(text, callback);
Esempio n. 20
0
function iniciar(route, handle) {
	function onRequest(req, res) {
		var pathname = url.parse(req.url).pathname;
		var querystring = url.parse(req.url).query;
		if(pathname !=='/favicon.ico') {
			console.log('Request Recived for ' + pathname);
			route(pathname, querystring, handle, res);
		} else if(pathname === '/'){
			res.end();
		}
	}

	var server = http.createServer(onRequest);
	var socket = io(server);
	socket.on('connection', function(socket_listener){
		socket_listener.on('addbus', function(plate, type){
			console.log('Adding bus...');
			model.addbus(socket_listener, plate, type);
		});
		socket_listener.on('modbus', function(id, plate, type){
			console.log('Modifying bus...');
			model.modbus(socket_listener, id, plate, type);
		});
		socket_listener.on('delbus', function(id, plate, type){
			console.log('Deleting bus...');
			model.delbus(socket_listener, id);
		});
		socket_listener.on('payticket', function(checklist, total){
			console.log('Paying ticket...');
			model.pay(socket_listener, checklist, total);
		});
		socket_listener.on('showticket', function(ticket){
			console.log('Paying ticket...');
			model.showticket(socket_listener, ticket);
		});
		socket_listener.on('addtoroute', function(point){
			console.log('Adding route info...');
			model.addtoroute(socket_listener, point);
		});
		socket_listener.on('expandroute', function(route, hour, busid){
			console.log('Expanding route info...');
			model.expandroute(socket_listener, route, hour, busid);
		});
		socket_listener.on('delroute', function(route, hour){
			console.log('Deleting route info...');
			model.delroute(socket_listener, route, hour);
		});
		socket_listener.on('requestschedule', function(){
			console.log('Requesting schedule...');
			model.schedule(socket_listener);
		});
		socket_listener.on('requestmanagebus', function(){
			console.log('Requesting bus info...');
			model.busmanage(socket_listener);
		});
		socket_listener.on('requestmanageroute', function(route, hour, busid){
			console.log('Requesting route info...');
			model.routemanage(socket_listener, route, hour, busid);
		});
	});
	server.listen(8080, '0.0.0.0');
	console.log('Server Initiated at http://0.0.0.0:8080/');
}
Esempio n. 21
0
KeyValue.getKeyValues().then(function(data) {
  cfg.setKeyValue(data);

  // --------------------------------------------------------
  // These next three calls are per the example application at:
  // https://github.com/jaredhanson/passport-local/blob/master/examples/express3-no-connect-flash/app.js
  // --------------------------------------------------------
  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.findById(id, function (err, user) {
      done(err, user);
    });
  });

  passport.use(new LocalStrategy(
    function(username, password, done) {
      //Find the user by username.  If there is no user with the given
      //username, or the password is not correct, set the user to `false` to
      //indicate failure and set a flash message.  Otherwise, return the
      //authenticated `user`.
      User.findByUsername(username, function(err, user) {
        if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
        if (user.get('status') != 1) {
          return done(null, false, {
            message: username + ' is not an active account.'
          });
        }
        user.checkPassword(password, function(err, same) {
          if (err) return done(err);
          if (same) {
            return done(null, user);
          } else {
            return done(null, false, {message: 'Invalid password'});
          }
        });
      });
    }
  ));

  // --------------------------------------------------------
  // All configurations.
  // --------------------------------------------------------
  app.engine('jade', cons.jade);
  app.set('view engine', 'jade');
  app.set('views', path.join(__dirname,'views'));
  app.use(favicon(__dirname + '/static/favicon.ico'));
  app.use(express.static('static'));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser(cfg.cookie.secret));

  console.log('Creating MySQL session pool and session configuration.')
  cfg.session.pool = MySQL.createPool({
    user: cfg.database.dbUser
    , password: cfg.database.dbPass
    , host: cfg.database.host
    , port: cfg.database.port
    , database: cfg.database.db
    , schema: {
        tablename: 'session'
        , columnNames: {
            session_id: 'sid'
            , expires: 'expires'
            , data: 'session'
        }
      }
  });
  sessionCfg = {
    host: cfg.database.host
    , port: cfg.database.port
    , user: cfg.database.dbUser
    , password: cfg.database.dbPass
    , database: cfg.database.db
  };

  var sessionStore = new SessionStore(sessionCfg);
  // --------------------------------------------------------
  // sessionMiddleware() allows the same authentication to
  // be used in Express as in Socket.io.
  // --------------------------------------------------------
  var sessionMiddleware = session({
    secret: cfg.session.secret
    , cookie: {maxAge: cfg.cookie.maxAge, secure: useSecureCookie}
    , rolling: true   // Allows session to remain active as long as it is being used.
    , resave: false   // Usually false since express-mysql-session implements touch().
    , saveUninitialized: false
    , store: sessionStore
  });
  app.use(sessionMiddleware);

  app.use(bodyParser.urlencoded({extended: false}));
  app.use(device.capture());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(flash());

  // --------------------------------------------------------
  // Insure that our priority numbers are prepped and ready.
  // --------------------------------------------------------
  generateBarcodes();

  // --------------------------------------------------------
  // Handle a "touch" by an SPA client that maintains the
  // session on the HTTP side while the client continues to
  // use exclusively websockets or Socket.io. The session is
  // automagically touched by the end of handling the request.
  // This allows the session maintained by the HTTP side,
  // which can be "abandoned" by the client for long periods
  // of time while the user is using the SPA client, to remain
  // valid and ready when the user returns to full page mode.
  // --------------------------------------------------------
  app.put('/touch', function(req, res) {
    res.statusCode = 204;
    res.end();
  });

  // --------------------------------------------------------
  // Deliver these JS libraries to the templating system.
  // --------------------------------------------------------
  app.locals.libs = {};
  app.locals.libs.mmt = moment;   // Moment's global reference is deprecated.
  app.locals.libs._ = _;          // Underscore

  // --------------------------------------------------------
  // Localization.
  // --------------------------------------------------------
  app.use(function(req, res, next) {
    if (req.session && req.session.user) {
      var lang = req.session.user.lang || cfg.site.defaultLanguage;
      req.headers['accept-language'] = lang;
    }
    next();
  });

  app.use(i18n.abide({
    supported_languages: cfg.site.languages
    , default_lang: cfg.site.defaultLanguage
    , debug_lang: cfg.site.debugLanguage
    , translation_directory: 'i18n'
  }));

  // --------------------------------------------------------
  // This is a hack because i18n-abide does not work natively
  // outside the context of a request. Therefore, we force
  // it into the context of a request in order to localize
  // all of the site wide variables for our templates. See
  // config.js in the site section.
  //
  // Note: any additions to cfg.site in config.js need to be
  // added to this function.
  // --------------------------------------------------------
  var i18nLocals = function(req, res, next) {
    var title = cfg.getKeyValue('siteShortName');
    app.locals.siteTitle = req.gettext(title);
    next();
  };

  /* --------------------------------------------------------
  * hasSuper()
  *
  * Forces the user in the attending role to choose a supervisor
  * before continuing. Also populates the supervisor variable
  * for use in the templates.
  * -------------------------------------------------------- */
  var hasSuper = function(req, res, next) {
    var superName
      ;
    if (req.session.roleInfo.roleName === 'attending') {
      if (req.session.supervisor) {
        // --------------------------------------------------------
        // Store the supervisor in app.locals for the templates.
        // Not all supervisors have their displayName field
        // populated so fall back to first and last if necessary.
        // --------------------------------------------------------
        superName = req.session.supervisor.displayName;
        if (! superName) {
          superName = req.session.supervisor.firstname + ' ' + req.session.supervisor.lastname;
        }
        app.locals.supervisor = superName;
        next();
      } else {
        res.redirect(cfg.path.setSuper);
      }
    } else {
      next();
    }
  };

  /* --------------------------------------------------------
  * logDevice()
  *
  * Logs the device the client is using to the console.
  * -------------------------------------------------------- */
  var logDevice = function(req, res, next) {
    //console.dir(req.device);
    next();
  };

  /* --------------------------------------------------------
  * logRoute()
  *
  * Logs a bit about the route being accessed by the user.
  * This does not imply that the route has been approved yet.
  * -------------------------------------------------------- */
  var logRoute = function(req, res, next) {
    var msg = ''
      ;
    if (req.session && req.session.user && req.session.user.username) {
      msg += req.session.user.username + ': ';
    }
    msg += '[' + req.method + '] ' + req.url;
    logInfo(msg);
    next();
  };

  /* --------------------------------------------------------
  * Records in the session the jumpTo URL per the value of
  * the jumpTo field passed in the request body. The value
  * of the field corresponds to a lookup in the configuration
  * to ascertain the proper URL for the key passed. The
  * pregnancy id is ascertained by checking the session for
  * the current pregnancy id and replaced if there is a
  * placeholder for it.
  * -------------------------------------------------------- */
  app.use(function(req, res, next) {
    var url
      ;
    if (req.method === 'POST' &&
        req.body &&
        req.body.jumpTo) {
      if (_.has(cfg.jumpTo, req.body.jumpTo)) {
        url = cfg.jumpTo[req.body.jumpTo];
        if (req.session.currentPregnancyId && /:id/.test(url)) {
          url = url.replace(/:id/, req.session.currentPregnancyId);
        }
        req.session.jumpTo = url;
        logInfo(req.session.user.username + ': <JumpTo> ' + url);
      }
    }
    next();
  });

  /* --------------------------------------------------------
  * Make the current path available to the templates so that
  * it can be used to dynamically create an url for entering
  * history mode.
  * -------------------------------------------------------- */
  app.use(function(req, res, next) {
    var currUrl
      ;
    if (req.method === 'GET' &&
        req.url.search(/^\/pregnancy\//) !== -1) {
      app.locals.currUrl = req.url;
    }
    next();
  });

  // --------------------------------------------------------
  // Debugging, etc.
  // --------------------------------------------------------
  app.use(function(req, res, next) {
    if (cfg.site.debug) {
      console.log('============================');
      console.log(req.method + ': ' + req.url);
      console.log(req.headers);
      console.log('-----');
      console.log(req.body);
      console.log('============================');
      console.log('isAuthenticated(): ' + req.isAuthenticated());
      console.log('============================');
    }
    next();
  });

  // --------------------------------------------------------
  // Protect against cross site request forgeries.
  // --------------------------------------------------------
  app.use(csrfProtection);
  app.use(function(req, res, next) {
    app.locals.token = req.csrfToken();
    next();
  });

  // --------------------------------------------------------
  // Make the application revision available to the templates.
  // --------------------------------------------------------
  if (fs.existsSync('./VERSION')) {
    tmpRevision = fs.readFileSync('./VERSION', {encoding: 'utf8'});
    tmpRevision = tmpRevision.trim();
    logInfo('Version: ' + tmpRevision);
    app.use(function(req, res, next) {
      app.locals.applicationRevision = tmpRevision? tmpRevision: '';
      next();
    });
  } else {
    app.locals.applicationRevision = void(0);
  }

  // --------------------------------------------------------
  // Check for the system mode that we are in per the
  // SystemMode.dat file in the top-level directory. We do this
  // when we start as well as periodically thereafter.
  // --------------------------------------------------------
  systemMode = getNewSystemMode(SYSTEM_MODE_FILE);
  process.send({cmd: SYSTEM_MODE_CHANGE, systemMode: systemMode});
  if (systemMode !== 0) logInfo('Starting in SystemMode: ' + systemMode);

  setInterval(function() {
    var tmpSystemMode = getNewSystemMode(SYSTEM_MODE_FILE);
    if (tmpSystemMode !== systemMode) {
      systemMode = tmpSystemMode;
      process.send({cmd: SYSTEM_MODE_CHANGE, systemMode: systemMode});
      logInfo('New SystemMode: ' + systemMode);
    }
  }, checkSystemModeMS);

  // --------------------------------------------------------
  // express-device functionality: render different views
  // according to device type.
  // --------------------------------------------------------
  device.enableViewRouting(app);

  // --------------------------------------------------------
  // Development configuration
  // --------------------------------------------------------
  if (app.get('env') === 'development') {
    logInfo('DEVELOPMENT mode');
  }

  // --------------------------------------------------------
  // Production configuration
  // --------------------------------------------------------
  if (app.get('env') === 'production') {
    logInfo('PRODUCTION mode');
  }

  // ========================================================
  // ========================================================
  // Routes
  //
  // Note that the auth method placed before the inRoles()
  // authentication requirements in many of the routes allows
  // the request to get redirected to the login page rather
  // than just being denied if the user is not yet logged in.
  // ========================================================
  // ========================================================

  // --------------------------------------------------------
  // Group of methods that are commonly needed for
  // many requests.
  // common: populates the request with info for protected routes.
  // spaCommon: same but for API calls.
  // --------------------------------------------------------
  common.push(logRoute, logDevice, setSystemMode, auth, setRoleInfo, i18nLocals);
  spaCommon.push(logRoute, logDevice, setSystemMode, spaAuth, setRoleInfo, i18nLocals);

  // --------------------------------------------------------
  // Login and logout
  // --------------------------------------------------------
  app.get(cfg.path.login, logRoute, setRoleInfo, setSystemMode, home.login);
  app.post(cfg.path.login, logRoute, setRoleInfo, setSystemMode, home.loginPost);
  app.get(cfg.path.logout, logRoute, clearRoleInfo, home.logout);

  // --------------------------------------------------------
  // Catch routes to see if user refreshed page on an SPA route
  // but don't handle the API calls.
  // --------------------------------------------------------
  app.use(function(req, res, next) {
    // If url is anything /api, ignore.
    if (/^\/api\//.test(req.url)) return next();

    // If url is for transitioning from SPA to full page load, ignore.
    if (/^\/toprenatal/.test(req.url)) return next();

    // Ignore the birth certificate.
    if (/^\/printBirthCertificate/.test(req.url)) return next();

    if (req.session && req.session.isSpaOnly) return api.doSpa(req, res, next);
    next();
  });

  // --------------------------------------------------------
  // Home for phase one prenatal (full page load) and the
  // labor/delivery/postpartum SPA.
  // --------------------------------------------------------
  app.get(cfg.path.home, common, hasSuper, api.doSpa, home.home);

  // --------------------------------------------------------
  // Handle transitions between prenatal full page loads and
  // labor/delivery/postpartum SPA.
  // --------------------------------------------------------
  app.get(cfg.path.toPrenatal, common, hasSuper, home.handleSPA);
  app.get(cfg.path.toLabor, common, hasSuper, home.handleSPA);

  // --------------------------------------------------------
  // Search
  // --------------------------------------------------------
  app.get(cfg.path.search, common, hasSuper,
      inRoles(['clerk', 'supervisor', 'attending', 'guard']), search.view);
  app.post(cfg.path.search, common, hasSuper,
      inRoles(['clerk', 'supervisor', 'attending', 'guard']), search.execute);

  // --------------------------------------------------------
  // Users
  // --------------------------------------------------------
  app.get(cfg.path.userList, common, inRoles(['administrator']), api.doSpa, users.list);
  app.all(cfg.path.userLoad, users.load);  // parameter handling
  app.get(cfg.path.userNewForm, common, inRoles(['administrator']), api.doSpa, users.addForm);
  app.post(cfg.path.userCreate, common, inRoles(['administrator']), api.doSpa, users.create);
  app.get(cfg.path.userEditForm, common, inRoles(['administrator']), api.doSpa, users.editForm);
  app.post(cfg.path.userUpdate, common, inRoles(['administrator']), api.doSpa, users.update);

  // --------------------------------------------------------
  // Roles
  // --------------------------------------------------------
  app.get(cfg.path.roleList, common, inRoles(['administrator']), api.doSpa, roles.list);
  app.all(cfg.path.roleLoad, roles.load);  // parameter handling
  app.get(cfg.path.roleNewForm, common, inRoles(['administrator']), api.doSpa, roles.addForm);
  app.post(cfg.path.roleCreate, common, inRoles(['administrator']), api.doSpa, roles.create);
  app.get(cfg.path.roleEditForm, common, inRoles(['administrator']), api.doSpa, roles.editForm);
  app.post(cfg.path.roleUpdate, common, inRoles(['administrator']), api.doSpa, roles.update);

  // --------------------------------------------------------
  // Role assignment to users
  // --------------------------------------------------------
  app.all(cfg.path.userLoad2, users.load);  // parameter handling

  // --------------------------------------------------------
  // Profile
  // --------------------------------------------------------
  app.get(cfg.path.profile, common, users.editProfile);
  app.post(cfg.path.profile, common, users.saveProfile);

  // --------------------------------------------------------
  // Set the supervisor if a attending.
  // --------------------------------------------------------
  app.get(cfg.path.setSuper, common, inRoles(['attending']), users.editSupervisor);
  app.post(cfg.path.setSuper, common, inRoles(['attending']), users.saveSupervisor);

  // --------------------------------------------------------
  // Pregnancy management
  // --------------------------------------------------------
  app.all(cfg.path.pregnancyLoad, pregnancy.load);  // parameter handling
  app.get(cfg.path.pregnancyNewForm, common, hasSuper,
      inRoles(['clerk','attending','supervisor']), pregnancy.generalAddForm);
  app.get(cfg.path.pregnancyNewCurrPatForm, common, hasSuper,
      inRoles(['clerk','attending','supervisor']), pregnancy.generalAddForm);
  app.post(cfg.path.pregnancyCreate, common, hasSuper,
      inRoles(['clerk','attending','supervisor']), pregnancy.generalAddSave);
  app.get(cfg.path.pregnancyEditForm, common, hasSuper,
      inRoles(['clerk','attending','supervisor']), pregnancy.generalEditForm);
  app.post(cfg.path.pregnancyUpdate, common, hasSuper,
      inRoles(['clerk','attending','supervisor']), pregnancy.generalEditSave);
  app.post(cfg.path.pregnancyDelete, common, hasSuper,
      inRoles(['supervisor']), pregnancy.pregnancyDelete);

  // Pregnancy Questionnaire
  app.get(cfg.path.pregnancyQuesEdit, common, hasSuper,
      inRoles(['clerk', 'attending','supervisor']), pregnancy.questionaireForm);
  app.post(cfg.path.pregnancyQuesUpdate, common, hasSuper,
      inRoles(['clerk', 'attending','supervisor']), pregnancy.questionaireSave);

  // Pregnancy midwife interview
  app.get(cfg.path.pregnancyMidwifeEdit, common, hasSuper,
      inRoles(['attending','supervisor']), pregnancy.midwifeForm);
  app.post(cfg.path.pregnancyMidwifeUpdate, common, hasSuper,
      inRoles(['attending','supervisor']), pregnancy.midwifeSave);

  // Pregnancy History
  app.get(cfg.path.pregnancyHistoryAdd, common, hasSuper,
      inRoles(['attending','supervisor']), pregnancyHistory.pregnancyHistoryAddForm);
  app.post(cfg.path.pregnancyHistoryAdd, common, hasSuper,
      inRoles(['attending','supervisor']), pregnancyHistory.pregnancyHistorySave);
  app.get(cfg.path.pregnancyHistoryEdit, common, hasSuper,
      inRoles(['attending','supervisor']), pregnancyHistory.pregnancyHistoryEditForm);
  app.post(cfg.path.pregnancyHistoryEdit, common, hasSuper,
      inRoles(['attending','supervisor']), pregnancyHistory.pregnancyHistorySave);
  app.post(cfg.path.pregnancyHistoryDelete, common, hasSuper,
      inRoles(['attending','supervisor']), pregnancyHistory.pregnancyHistoryDelete);

  // Prenatal
  app.get(cfg.path.pregnancyPrenatalEdit, common, hasSuper,
      inRoles(['clerk','attending','supervisor']), pregnancy.prenatalForm);
  app.post(cfg.path.pregnancyPrenatalUpdate, common, hasSuper,
      inRoles(['clerk', 'attending','supervisor']), pregnancy.prenatalSave);

  // Prenatal Exams
  app.get(cfg.path.pregnancyPrenatalExamAdd, common, hasSuper,
      inRoles(['clerk','attending','supervisor']), prenatalExam.prenatalExamAddForm);
  app.post(cfg.path.pregnancyPrenatalExamAdd, common, hasSuper,
      inRoles(['clerk','attending','supervisor']), prenatalExam.prenatalExamSave);
  app.get(cfg.path.pregnancyPrenatalExamEdit, common, hasSuper,
      inRoles(['clerk','attending','supervisor']), prenatalExam.prenatalExamEditForm);
  app.post(cfg.path.pregnancyPrenatalExamEdit, common, hasSuper,
      inRoles(['clerk','attending','supervisor']), prenatalExam.prenatalExamSave);
  app.post(cfg.path.pregnancyPrenatalExamDelete, common, hasSuper,
      inRoles(['attending','supervisor']), prenatalExam.prenatalExamDelete);
  app.get(cfg.path.pregnancyPrenatalExamLatest, common, hasSuper,
      inRoles(['attending','supervisor']), prenatalExam.prenatalExamLatest);

  // Labs main page
  app.get(cfg.path.pregnancyLabsEditForm, common, hasSuper,
      inRoles(['attending','supervisor', 'clerk']), pregnancy.labsForm);

  // Lab Tests
  app.post(cfg.path.labTestAddForm, common, hasSuper,
      inRoles(['attending', 'supervisor', 'clerk']), labs.labTestAddForm);
  app.post(cfg.path.labTestAdd, common, hasSuper,
      inRoles(['attending', 'supervisor', 'clerk']), labs.labTestSave);
  app.get(cfg.path.labTestEdit, common, hasSuper,
      inRoles(['attending', 'supervisor', 'clerk']), labs.labTestEditForm);
  app.post(cfg.path.labTestEdit, common, hasSuper,
      inRoles(['attending', 'supervisor', 'clerk']), labs.labTestSave);
  app.post(cfg.path.labTestDelete, common, hasSuper,
      inRoles(['attending', 'supervisor', 'clerk']), labs.labDelete);

  // Referrals
  app.get(cfg.path.referralAdd, common, hasSuper,
      inRoles(['attending', 'supervisor']), referral.referralAddForm);
  app.post(cfg.path.referralAdd, common, hasSuper,
      inRoles(['attending', 'supervisor']), referral.referralSave);
  app.get(cfg.path.referralEdit, common, hasSuper,
      inRoles(['attending', 'supervisor']), referral.referralEditForm);
  app.post(cfg.path.referralEdit, common, hasSuper,
      inRoles(['attending', 'supervisor']), referral.referralSave);
  app.post(cfg.path.referralDelete, common, hasSuper,
      inRoles(['attending', 'supervisor']), referral.referralDelete);

  // Progress Notes
  app.get(cfg.path.pregnoteAdd, common, hasSuper,
      inRoles(['attending', 'supervisor']), pregnote.pregnoteAddForm);
  app.post(cfg.path.pregnoteAdd, common, hasSuper,
      inRoles(['attending', 'supervisor']), pregnote.pregnoteSave);
  app.get(cfg.path.pregnoteEdit, common, hasSuper,
      inRoles(['attending', 'supervisor']), pregnote.pregnoteEditForm);
  app.post(cfg.path.pregnoteEdit, common, hasSuper,
      inRoles(['attending', 'supervisor']), pregnote.pregnoteSave);
  app.post(cfg.path.pregnoteDelete, common, hasSuper,
      inRoles(['attending', 'supervisor']), pregnote.pregnoteDelete);

  // Health Teachings
  app.get(cfg.path.teachingAdd, common, hasSuper,
      inRoles(['attending', 'clerk', 'supervisor']), teaching.teachingAddForm);
  app.post(cfg.path.teachingAdd, common, hasSuper,
      inRoles(['attending', 'clerk', 'supervisor']), teaching.teachingSave);
  app.get(cfg.path.teachingEdit, common, hasSuper,
      inRoles(['attending', 'clerk', 'supervisor']), teaching.teachingEditForm);
  app.post(cfg.path.teachingEdit, common, hasSuper,
      inRoles(['attending', 'clerk', 'supervisor']), teaching.teachingSave);
  app.post(cfg.path.teachingDelete, common, hasSuper,
      inRoles(['attending', 'clerk', 'supervisor']), teaching.teachingDelete);

  // Doctor and dentist consult dates
  app.post(cfg.path.docDenConsult, common, hasSuper,
      inRoles(['attending', 'supervisor']), pregnancy.doctorDentistSave);

  // Vaccinations
  app.get(cfg.path.vaccinationAdd, common, hasSuper,
      inRoles(['attending', 'supervisor']), vaccination.vaccinationAddForm);
  app.post(cfg.path.vaccinationAdd, common, hasSuper,
      inRoles(['attending', 'supervisor']), vaccination.vaccinationSave);
  app.get(cfg.path.vaccinationEdit, common, hasSuper,
      inRoles(['attending', 'supervisor']), vaccination.vaccinationEditForm);
  app.post(cfg.path.vaccinationEdit, common, hasSuper,
      inRoles(['attending', 'supervisor']), vaccination.vaccinationSave);
  app.post(cfg.path.vaccinationDelete, common, hasSuper,
      inRoles(['attending', 'supervisor']), vaccination.vaccinationDelete);

  // Medications and vitamins
  app.get(cfg.path.medicationAdd, common, hasSuper,
      inRoles(['attending', 'supervisor']), medication.medicationAddForm);
  app.post(cfg.path.medicationAdd, common, hasSuper,
      inRoles(['attending', 'supervisor']), medication.medicationSave);
  app.get(cfg.path.medicationEdit, common, hasSuper,
      inRoles(['attending', 'supervisor']), medication.medicationEditForm);
  app.post(cfg.path.medicationEdit, common, hasSuper,
      inRoles(['attending', 'supervisor']), medication.medicationSave);
  app.post(cfg.path.medicationDelete, common, hasSuper,
      inRoles(['attending', 'supervisor']), medication.medicationDelete);

  // Checkin and checkout routes for the guard
  app.get(cfg.path.checkInOut, common, inRoles(['guard']), checkInOut.checkInOut);
  app.post(cfg.path.checkIn, common, inRoles(['guard']), checkInOut.checkInOutSave);
  app.post(cfg.path.checkOut, common, inRoles(['guard']), checkInOut.checkInOutSave);
  app.get(cfg.path.newCheckIn, common, inRoles(['guard']), checkInOut.checkInOut);
  app.post(cfg.path.newCheckIn, common, inRoles(['guard']), checkInOut.checkInOutSave);
  app.get(cfg.path.simpleCheckOut, common,
      inRoles(['guard', 'attending', 'clerk', 'supervisor']), checkInOut.simpleCheckOutForm);
  app.post(cfg.path.simpleCheckOut, common,
      inRoles(['guard', 'attending', 'clerk', 'supervisor']), checkInOut.simpleCheckOut);

  // Priority List
  app.post(cfg.path.priorityListLoad, priorityList.load);  // parameter handling for AJAX save only
  app.get(cfg.path.priorityList, common, hasSuper,
      inRoles(['attending', 'clerk', 'supervisor']), priorityList.page);  // GET page
  app.post(cfg.path.priorityList, common, hasSuper,
      inRoles(['attending', 'clerk', 'supervisor']), priorityList.data);  // POST AJAX for data
  app.post(cfg.path.priorityListSave, common, hasSuper,
      inRoles(['attending', 'clerk', 'supervisor']), priorityList.save);  // POST AJAX for save


  // AJAX Calls.
  app.post(cfg.path.requiredTetanus, common, hasSuper,
      inRoles(['attending', 'supervisor']), vaccination.requiredTetanusSave);

  // Reports
  app.get(cfg.path.reportForm, common, hasSuper,
      inRoles(['supervisor', 'clerk']), report.form);
  app.post(cfg.path.reportRun, common, hasSuper,
      inRoles(['supervisor', 'clerk']), report.run);
  app.get(cfg.path.reportSummary, common, hasSuper,
      inRoles(['supervisor', 'clerk', 'attending']), report.summary);

  // Invoice Worksheet
  app.get(cfg.path.invoiceWorksheet, common,
      inRoles(['supervisor', 'clerk', 'attending']), invWork.invoiceWorksheet);

  // Birth Certificate printing
  app.get(cfg.path.birthCertificatePrinting, common,
      inRoles(['supervisor', 'clerk', 'attending']), report.birthCertificate);

  // ========================================================
  // ========================================================
  // SPA related routes and data calls below.
  // ========================================================
  // ========================================================

  // SPA pages: the initial full page load of a SPA portion of the app.
  app.get(cfg.path.spaLoad, api.params);    // parameter handling
  app.get(cfg.path.spa, common,
      inRoles(['administrator', 'supervisor', 'clerk', 'attending']), api.spa.main);

  // History API
  app.all(cfg.path.apiLoad, api.params);    // parameter handling
  app.get(cfg.path.apiHistory, common,
      inRoles(['supervisor']), api.history.get);

  // User/Role Management
  app.all(cfg.path.apiUser, spaCommon, inRoles(['administrator']), api.userRoles.user);

  // User Profile
  app.all(cfg.path.apiProfile, spaCommon,
      inRoles(['administrator', 'clerk', 'guard', 'supervisor', 'attending']),
      api.userRoles.profile);
  app.all(cfg.path.apiProfilePassword, spaCommon,
      inRoles(['administrator', 'clerk', 'guard', 'supervisor', 'attending']),
      api.userRoles.profile);

  // Searches
  app.get(cfg.path.apiSearch, spaCommon,
      inRoles(['clerk', 'guard', 'supervisor', 'attending']), apiSearch);

  // Pregnancy
  app.get(cfg.path.apiPregnancy, spaCommon,
      inRoles(['clerk', 'guard', 'supervisor', 'attending']), getPregnancy);


  // --------------------------------------------------------
  // Error handling.
  // --------------------------------------------------------
  app.use(error.notFoundApiError);
  app.use(error.notFoundError);
  app.use(error.logException);
  app.use(error.displayError);
  app.use(error.exitError);
  if (app.get('env') === 'development') {
    app.use(errorHandler());
  }

  // --------------------------------------------------------
  // The last resort.
  // --------------------------------------------------------
  process.on('uncaughtException', function(err) {
    logError('uncaughtException: ', err.message);
    logError(err.stack);
    process.exit(1);
  });


  // --------------------------------------------------------
  // Start the server.
  // --------------------------------------------------------
  if (process.env.NODE_ENV == 'test') {
    logInfo('TEST mode');
    app.listen(cfg.host.port, cfg.host.name);
  } else {
    // --------------------------------------------------------
    // Determine which port this instance will listen on. In a
    // cluster of workers, due to the need to use sticky sessions
    // for the sake of Socket.io, we have the workers listen on
    // separate ports if there are more than one worker. See
    // http://socket.io/docs/using-multiple-nodes/ for details.
    //
    // Note that if cfg.cpu.workers is greater than 1, then a
    // reverse proxy like Nginx must be configured that implements
    // sticky sessions or else only one worker will be used.
    // --------------------------------------------------------
    if (process.env.WORKER_ID) {
      if (cfg.tls.key) {
        workerPort = Number(cfg.host.tlsPort) + Number(process.env.WORKER_ID);
      } else {
        workerPort = Number(cfg.host.port) + Number(process.env.WORKER_ID);
      }
    }
    if (cfg.tls.key) {
      // --------------------------------------------------------
      // Listen for HTTPS connections.
      // --------------------------------------------------------
      var tlsCfg = {};
      tlsCfg.key = fs.readFileSync(cfg.tls.key);
      tlsCfg.cert = fs.readFileSync(cfg.tls.cert);
      server = https.createServer(tlsCfg, app);
      server.listen(workerPort, cfg.host.name);

      // --------------------------------------------------------
      // Catch all incoming HTTP connections and redirect to HTTPS.
      // We don't redirect to the workerPort because if we are
      // running more than one worker in a cluster, the reverse
      // proxy should be implementing some form of sticky connections
      // which should choose the correct worker port, if the
      // remoteAddress has already been assigned to one.
      // --------------------------------------------------------
      http.createServer(function(req, res) {
        var httpsLoc = url.format({
              protocol: 'https', hostname: cfg.host.name, port: cfg.host.tlsPort
            })
          ;
        res.setHeader('Location', httpsLoc);
        res.statusCode = 302;
        res.end('Redirecting to ' + httpsLoc);
      }).listen(cfg.host.port, cfg.host.name);

    } else {
      // --------------------------------------------------------
      // HTTP only. This should not be used for production.
      // --------------------------------------------------------
      server = http.createServer(app);
      server.listen(workerPort, cfg.host.name);
    }

    // ========================================================
    // ========================================================
    // Initialize the communication module for this worker.
    // ========================================================
    // ========================================================
    comm.init(SocketIO(server), sessionMiddleware);
  }

  if (cfg.tls.key) {
    logInfo('Server listening for HTTPS on port ' + workerPort +
        ' and redirecting port ' + cfg.host.port);
  } else {
    logInfo('Server listening in INSECURE mode on port ' + workerPort);
  }

})
Esempio n. 22
0
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var socketIO = require("socket.io");

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();
/**
 * Socket IO
 */
var io = socketIO();
app.io = io;

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// app.use('/', routes);
Esempio n. 23
0
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'X-Requested-With');
        res.header('Access-Control-Allow-Headers', 'Content-Type');
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        next();
    });

    // session / auth
    app.use(passport.initialize());

    // admin site routes
    require('./server/admin/router.js')(app);

    // Don't expose our internal server to the outside.
    var server = app.listen(0, 'localhost'),
        io = sio(server);

    io.adapter(sio_redis({
        key: nconf.get('sio_redis_key'),
        host: nconf.get('redis_host'),
        port: nconf.get('redis_port')
    }));

    // TODO: factor out into service
    var chatHandler = function (socket) {
        console.log('chat connected: ', socket.id);

        // TODO: better validation etc. and rooms
        socket.on('message', function (data) {
            io.of('/chat').emit('message', data);
        });
Esempio n. 24
0
"use strict";
var http  = require("http")
var express = require("express"),
    app = express(),
    path = require("path"),
    groupId = 0,
    usersData = {},
    compilerRoute = require("./route/compiler");
var server = http.createServer(app);
app.use('/public',express.static(path.join(__dirname, 'public')));



//editor file to go online
var socketio = require("socket.io");
var io = socketio(server);





app.use('/ace-builds',express.static(path.join(__dirname, 'ace-builds')));
app.set('views', path.join(__dirname, 'public'));
app.set('view engine', 'ejs');
app.use('/compile',compilerRoute);



io.on("connection",function(socket){
         socket.on("add_user",function(user){
             printJson("user",user)
Esempio n. 25
0
let express = require('express'),
  logger = require('morgan'),
  socketServer = require('socket.io'),
  http = require('http'),
  bodyParser = require('body-parser'),
  log = require('easy-log'),
  load = require('express-load'),
  socketHandler = require('./socket-handler'),
  AuctionEvents = require('./auction-events'),

  cors = require('./routes/cors'),
  auction = require('./routes/auction');

let app = express(),
  server = http.createServer(app),
  io = socketServer(server),
  port = 4000; // process.env.PORT ||

load('sockets', {cwd: __dirname})
  .into(app);

socketHandler.start(app, io);

AuctionEvents.instance(io);

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/api/*', cors);
app.use('/api/auctions', auction);
Esempio n. 26
0
export default function slackin ({
  token,
  interval = 5000, // jshint ignore:line
  org,
  css,
  coc,
  path='/',
  channels,
  silent = false // jshint ignore:line,
}){
  // must haves
  if (!token) throw new Error('Must provide a `token`.')
  if (!org) throw new Error('Must provide an `org`.')

  if (channels) {
    // convert to an array
    channels = channels.split(',').map((channel) => {
      // sanitize channel name
      if ('#' === channel[0]) return channel.substr(1)
      return channel
    })
  }

  // setup app
  let app = express()
  let srv = http(app)
  let assets = __dirname + '/assets'

  // fetch data
  let slack = new Slack({ token, interval, org })

  slack.setMaxListeners(Infinity)

  // capture stats
  log(slack, silent)

  // middleware for waiting for slack
  app.use((req, res, next) => {
    if (slack.ready) return next()
    slack.once('ready', next)
  })

  // splash page
  app.get('/', (req, res) => {
    let { name, logo } = slack.org
    let { active, total } = slack.users
    if (!name) return res.send(404)
    let page = dom('html',
      dom('head',
        dom('title',
          'Join ', name, ' on Slack!'
        ),
        dom('meta name=viewport content="width=device-width,initial-scale=1.0,minimum-scale=1.0,user-scalable=no"'),
        dom('link rel="shortcut icon" href=https://slack.global.ssl.fastly.net/272a/img/icons/favicon-32.png'),
        css && dom('link rel=stylesheet', { href: css })
      ),
      splash({ coc, path, css, name, org, logo, channels, active, total })
    )
    res.type('html')
    res.send(page.toHTML())
  })

  // static files
  app.use('/assets', express.static(assets))

  // invite endpoint
  app.post('/invite', json(), (req, res, next) => {
    let chanId
    if (channels) {
      let channel = req.body.channel
      if (!channels.includes(channel)) {
        return res
        .status(400)
        .json({ msg: 'Not a permitted channel' })
      }
      chanId = slack.getChannelId(channel)
      if (!chanId) {
        return res
        .status(400)
        .json({ msg: `Channel not found "${channel}"` })
      }
    }

    let email = req.body.email

    if (!email) {
      return res
      .status(400)
      .json({ msg: 'No email provided' })
    }

    if (!remail().test(email)) {
      return res
      .status(400)
      .json({ msg: 'Invalid email' })
    }

    if (coc && '1' != req.body.coc) {
      return res
      .status(400)
      .json({ msg: 'Agreement to CoC is mandatory' })
    }

    invite({ token, org, email, channel: chanId }, err => {
      if (err) {
        if (err.message === `Sending you to Slack...`) {
          return res
          .status(303)
          .json({ msg: err.message, redirectUrl: `https://${org}.slack.com` })
        }

        return res
        .status(400)
        .json({ msg: err.message })
      }

      res
      .status(200)
      .json({ msg: 'WOOT. Check your email!' })
    })
  })

  // iframe
  app.get('/iframe', (req, res) => {
    let large = 'large' in req.query
    let { active, total } = slack.users
    res.type('html')
    res.send(iframe({ path, active, total, large }).toHTML())
  })

  app.get('/iframe/dialog', (req, res) => {
    let large = 'large' in req.query
    let { name } = slack.org
    let { active, total } = slack.users
    if (!name) return res.send(404)
    let dom = splash({ coc, path, name, org, channels, active, total, large, iframe: true })
    res.type('html')
    res.send(dom.toHTML())
  })

  // badge js
  app.use('/slackin.js', express.static(assets + '/badge.js'))

  // badge rendering
  app.get('/badge.svg', (req, res) => {
    res.type('svg')
    res.set('Cache-Control', 'max-age=0, no-cache')
    res.set('Pragma', 'no-cache')
    res.send(badge(slack.users).toHTML())
  })

  // realtime
  sockets(srv).on('connection', socket => {
    socket.emit('data', slack.users)
    let change = (key, val) => socket.emit(key, val)
    slack.on('change', change)
    socket.on('disconnect', () => {
      slack.removeListener('change', change)
    })
  })

  return srv
}
Esempio n. 27
0
    start() {
        let io = socketIO(this.server, {
            serveClient: true,
            path: '/socket.io'
        });

        io.use((socket, next) => {
            let address = socket.handshake.address;
            let allowed = _.some(ALLOWED_IP_RANGES, (range) => {
                return rangeCheck.inRange(address, range);
            });

            if (!allowed) {
                log.warn(`${PREFIX} Reject connection from ${address}`);
                next(new Error('You are not allowed on this server!'));
                return;
            }

            next();
        });

        io.on('connection', (socket) => {
            let address = socket.handshake.address;
            log.debug(`${PREFIX} New connection from ${address}: id=${socket.id}`);

            // Add to the socket pool
            this.sockets.push(socket);

            socket.on('disconnect', () => {
                log.debug(`${PREFIX} socket.disconnect(): id=${socket.id}`);

                _.each(this.controllers, (controller, port) => {
                    if (!controller) {
                        return;
                    }
                    controller.removeConnection(socket);
                });

                // Remove from the socket pool
                this.sockets.splice(this.sockets.indexOf(socket), 1);
            });

            // Show available serial ports
            socket.on('list', () => {
                log.debug(`${PREFIX} socket.list(): id=${socket.id}`);

                serialport.list((err, ports) => {
                    if (err) {
                        log.error(err);
                        return;
                    }

                    ports = ports.concat(_.get(settings, 'cnc.ports') || []);

                    let portsInUse = _(this.controllers)
                        .filter((controller) => {
                            return controller && controller.isOpen();
                        })
                        .map((controller) => {
                            return controller.port;
                        })
                        .value();

                    ports = _.map(ports, (port) => {
                        return {
                            port: port.comName,
                            manufacturer: port.manufacturer,
                            inuse: _.includes(portsInUse, port.comName)
                        };
                    });

                    socket.emit('serialport:list', ports);
                });
            });

            // Open serial port
            socket.on('open', (port, options) => {
                log.debug(`${PREFIX} socket.open("${port}", ${JSON.stringify(options)}): id=${socket.id}`);

                let controller = this.controllers[port];
                if (!controller) {
                    const { controllerType = 'Grbl', baudrate } = { ...options };

                    if (controllerType === 'Grbl') {
                        controller = new GrblController(port, { baudrate });
                    } else if (controllerType === 'TinyG2') {
                        controller = new TinyG2Controller(port, { baudrate });
                    } else {
                        throw new Error('Not supported controller: ' + controllerType);
                    }
                }

                controller.addConnection(socket);

                if (controller.isOpen()) {
                    socket.emit('serialport:open', {
                        port: port,
                        baudrate: controller.options.baudrate,
                        controllerType: controller.type,
                        inuse: true
                    });
                    return;
                }

                controller.open();
            });

            // Close serial port
            socket.on('close', (port) => {
                log.debug(`${PREFIX} socket.close("${port}"): id=${socket.id}`);

                let controller = this.controllers[port];
                if (!controller) {
                    log.error(`${PREFIX} Serial port "${port}" not accessible`);
                    return;
                }

                controller.close();
            });

            socket.on('command', (port, cmd, ...args) => {
                log.debug(`${PREFIX} socket.command("${port}", "${cmd}"): id=${socket.id}, args=${JSON.stringify(args)}`);

                let controller = this.controllers[port];
                if (!controller || controller.isClose()) {
                    log.error(`${PREFIX} Serial port "${port}" not accessible`);
                    return;
                }

                controller.command.apply(controller, [socket, cmd].concat(args));
            });

            socket.on('write', (port, data) => {
                log.debug(`${PREFIX} socket.write("${port}", "${data}"): id=${socket.id}`);

                let controller = this.controllers[port];
                if (!controller || controller.isClose()) {
                    log.error(`${PREFIX} Serial port "${port}" not accessible`);
                    return;
                }

                controller.write(socket, data);
            });
        });
    }
Esempio n. 28
0
    db,
    userRoutes,
    socketIO;

/* DB connection */
mongoose.connect('mongodb://localhost:27017/quizz');
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
  console.log('db connected');
});

/*Express App config*/
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

http = http.Server(app);
io = io(http);

/*Routes for our application*/
indexRoutes = require('./routes/index')(app);
userRoutes = require('./routes/users')(app);

/*Socket IO connection for our application*/
socketIO = require('./socketIO')(app, io);

http.listen(3000, function(){
  console.log('listening on *:3000');
});
Esempio n. 29
0
function createServer() { // ( [ io | port | server ], [ options ] )
    var options = {
        "logLevel":         "info", // silly, debug, info, warn, error, silent
        "sessionCookie":    "sid",
        "guestAllowed":     true,
        "guestAnonymous":   false,
        "guestCookie":      "rtcs.io-guest"
    };

    var opts;
    var io;
    var createType;

    var args = Array.prototype.slice.call(arguments);
    var arg = args.shift();
    if (!arg) {
        createType = 1;
        io = socketIO();
    } else if (arg instanceof socketIO) { // Socket.IO Server
        createType = 2;
        opts = args.shift();
        io = arg;
    } else if ('number' === typeof arg) { // Port
        createType = 3;
        opts = args.shift();
        io = socketIO(arg, opts);
    } else if (arg.listen) { // HTTP(S) Server
        createType = 4;
        opts = args.shift();
        io = socketIO(arg, opts);
    } else {
        createType = 5;
        opts = arg;
        io = socketIO(opts);
    }

    if (opts) {
        for (var name in opts) {
            if (opts.hasOwnProperty(name)) {
                if ('object' === typeof opts[name] && 'object' === typeof options[name]) {
                    for (var subname in opts[name]) {
                        if (opts[name].hasOwnProperty(subname)) {
                            options[name][subname] = opts[name][subname];
                        }
                    }
                } else {
                    options[name] = opts[name];
                }
            }
        }
    }

    log.level = options.logLevel;

    switch (createType) {
        case 1: log.debug('create default socket.io'); break;
        case 2: log.debug('use existing socket.io server'); break;
        case 3: log.debug('create socket.io at port %s', arg); break;
        case 4: log.debug('create socket.io with http(s) server'); break;
        case 5: log.debug('create socket.io'); break;
    }

    return new Server(io, options);
}
Esempio n. 30
0
app.use(express.favicon());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.session({ secret: 'oh oh oh secrety secrets', store: sessionStore }));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// dev env middleware
if (app.get('env') === 'development') {
  app.use(express.errorHandler());
}


const server = new http.Server(app);
const io = socketio(server);

server.listen(app.get('port'), () => {
  log.debug(`Express is listening on port ${app.get('port')}`);
});


// routes - they need access to the onlineUsers array for rejecting in-use usernames
const onlineUsers = new Set();

const Routes = require('./routes');
const routes = new Routes(onlineUsers);

app.get('/', routes.index);
app.get('/dumdum', routes.dumdum);
app.get('/login', routes.login);