Example #1
0
MongoClient.connect(connectionString, function(err, db) {
    if(err) {
        console.log(err);
        throw err;
    }

    server.app.db = db;
    console.log('Connected to Mongo');

    server.start(function() {
        console.log('Server running at: ' + server.info.uri);
    });


});
Example #2
0
const Hapi = require('hapi');

const server = new Hapi.Server();
const config = require('./config');
const connection = {
  port: config.server.port,
  host: config.server.host 
};

server.connection(connection);

const plugins = [
  { register: require('./db/mongoose.plugin'), options: { database: config.database } },
  { register: require('./user/user.plugin') }
];

server.register(plugins, (err) => {
  if (err) return reject(err);
  server.start(function (err) {
    if (err) return console.log(err.stack);
    console.log('Server started ', server.info.uri);
  });
});
Example #3
0
var Hapi = require('Hapi'),
    MongoClient = require('mongodb').MongoClient;


var port = parseInt(process.env.PORT) || 8000;
var host = '0.0.0.0';

var server = new Hapi.Server(host, port, { cors: true });

var connectionString = process.env.MONGO_URI || 'mongodb://127.0.0.1:27017/sales';

MongoClient.connect(connectionString, function(err, db) {
    if(err) {
        console.log(err);
        throw err;
    }

    server.app.db = db;
    console.log('Connected to Mongo');

    server.start(function() {
        console.log('Server running at: ' + server.info.uri);
    });


});

server.route({
    method: 'GET',
    path: '/',
    handler: function(req, reply) {
Example #4
0
'use strict';

require("babel-register");
require('./server.js'); 

const Bcrypt = require('bcryptjs');
const Hapi = require('hapi');
const Inert = require('inert');
const Vision = require('vision');
const Good = require('good');
const Basic = require('hapi-auth-basic');
const Routes = require('./lib/routes');

const server = new Hapi.Server();
server.connection({ 
    host: 'localhost',
    port: 3000 
});

const users = {
    john: {
        username: 'john',
        password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm',   // 'secret'
        name: 'John Doe',
        id: '2133d32a'
    }
};

const validate = function (request, username, password, callback) {
    const user = users[username];
    if (!user) {
Example #5
0
  server.register(plugins, err => {
    if (err) { throw err; }

    server.start(done);
  });
Example #6
0
const Character = require('./Character.js');
const DeleteGame = require('./changes/DeleteGame.js');
const DeleteReplyContract = require('./DeleteReplyContract.js');
const Game = require('./Game.js');
const GameRepository = require('./GameRepository.js');
const JoiningError = require('./changes/JoiningError.js');
const JoinReplyContract = require('./JoinReplyContract.js');
const UnhandledError= require('./changes/UnhandledError.js');

const M = require('./util/M.js');
const Env = require('./util/Env.js');
const ASOP = require('./util/AsynchronousOperations.js');

const Hapi = require('hapi');
const Joi = require('joi');
const server = new Hapi.Server();
server.connection({ port: 3000 });



server.route({
    method: 'POST',
    path: '/game/join',
    /*
     *Do not use fat arrow syntax as they do not allow context binding!
     * */
    handler: function (request, reply) {
        var ASOPChain = [];


        ASOPChain.push(function (M, env, success, failure) {
 server.start(function() {
   server.log(['log', 'server'], 'Hapi server started '+ server.info.uri);
 });
var Good = require('good');
var Hapi = require('hapi');
var GoodMongoDb = require('good-mongodb');
var Boom = require('boom');

var server = new Hapi.Server({
  //debug: {
    //request: ['error']
  //}
});
server.connection({
  port: 8080
});

var mongoUrl = 'mongodb://localhost:27017/good-mongodb';
var goodOptions = {
  //extendedRequests: true,
  //opsInterval: 5000,
  reporters: [{
      reporter: require('good-console'),
      events: {
        //ops: '*',
        response: '*',
        log: '*',
        error: '*'
      }
    },
    {
      reporter: GoodMongoDb,
      config: {
        connectionUrl: mongoUrl,
Example #9
0
var Hapi = require('hapi');

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

var port = process.env.PORT || 8000;

// Pregunta: Que significa el + antes de process...?
// Respuesta: El + antes de una variable retorna su representacion numerica
// Referencia: http://stackoverflow.com/questions/6682997/javascript-plus-symbol-before-variable
var server = new Hapi.Server(+port, '0.0.0.0', {cors: true});

server.addRoutes(routes.endpoints);

// Integrar hapi con heroku: https://github.com/wpreul/hapi-heroku
server.start(function () {
	server.settings.uri = process.env.HOST ? 'http://' + process.env.HOST + ':' + process.env.PORT : server.info.uri;
	console.log('Server started at: ' + server.settings.uri);
});

var exports = module.exports = server;
Example #10
0
var Fs = require('fs');
var Hapi = require('hapi');
var Good = require('./lib');

//Fs.unlinkSync('__log.log');

var server = new Hapi.Server();
server.connection({ host: 'localhost', port: 9001});

var goodOptions = {
    opsInterval: 1000,
    requestHeaders: true,
    //requestPayload: true,
    responsePayload: true,
    responseEvent: 'tail',
    filter: {
        foo: "censor"
    },
    reporters: [{
        reporter: require('good-console'),
        events: {
            response: '*',
            error: '*',
            log: '*',
            request: '*',
            ops: '*'
        }
    }, {
        reporter: 'good-file',
        events: {
            request: '*',
Example #11
0
var Path = require('path');
var Hapi = require('hapi');

var server = new Hapi.Server();

server.connection({ port: 4000 });

server.views({
    engines: {
        'hbs': {
            module: require('handlebars'),
            compileMode: 'sync'
        }
    },
    relativeTo: __dirname,
    path: Path.join(__dirname, 'views'),
    layoutPath: Path.join(__dirname, 'views', 'layout'),
    helpersPath: Path.join(__dirname, 'views', 'helpers'),
    layout: true,
    isCached: false,
    partialsPath: Path.join(__dirname, 'views', 'partials')
});

server.register(require('hapi-auth-cookie'), function (err) {
    server.auth.strategy('session', 'cookie', {
        password: 'secret',
        cookie: 'sid-example',
        redirectTo: '/',
        isSecure: false
    });
Example #12
0
 server.start(function () {
   server.log('info', 'Servidor escuchando en: ' + server.info.uri);
 });
Example #13
0
var fs = require('fs');
var config = fs.readFileSync('app_config.json', 'utf8');
config = JSON.parse(config);


var AWS = require('aws-sdk'),
  sqs = {},
  Hapi = require('hapi'),
  server = new Hapi.Server();

//server.connection({ host: 'localhost', port: '3000' });
server.connection({ port: config.PORT });

/* **** FUNCIONES SQS ********************** */
function sendSqsMessage(queue, message) {
  'use strict';

  AWS.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: config.AWS_REGION
  });

  //sqs = new AWS.SQS(paramsCola);
  sqs = new AWS.SQS();

  /*
  var mensajeBody = {
    "to": "rminguet@gmail.com",
    "from": "rminguet@gmail.com",
    "cuerpo": "este es el cuerpo",
Example #14
0
'use strict';

const Hapi = require('hapi');

const routes = require('./routes/routes');

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
  host: 'localhost',
  port: 3001
});

server.route(routes);

// Start the server
server.start((err) => {
  if (err) {
    throw err;
  }
  console.log('Client running at:', server.info.uri);
});
Example #15
0
'use strict';

var hapi = require('hapi');
var halacious = require('../');

var server = new hapi.Server(8080);
server.pack.register(halacious, function(err){
    if (err) return console.log(err);
    var ns = server.plugins.halacious.namespaces.add({ dir: __dirname + '/rels/mycompany', prefix: 'mco' });
});

server.route({
    method: 'get',
    path: '/users/{userId}',
    config: {
        handler: function (req, reply) {
            reply({ id: req.params.userId, name: 'User ' + req.params.userId, bossId: 200 });
        },
        plugins: {
            hal: {
                links: {
                    'mco:boss': '../{bossId}'
                },
                ignore: 'bossId'
            }
        }
    }
});

server.start(function(err){
    if (err) return console.log(err);
var basicAuth = require('src/middleware/basic-auth');
var routes = require('src/routes');
var _ = require('underscore');

var options = {
	state: {
		cookies: {
			strictHeader: false
		}
	}
};

var host = constants.application['host'];
var port = constants.application['port'];

var server = new Hapi.Server();
server.connection({ host: host, port: port });

server.register(require('hapi-auth-basic'), function(err) {
 
    server.auth.strategy('simple', 'basic', { validateFunc: basicAuth });
});

server.ext('onRequest', function(request, reply) {

   	request.plugins.createHandlerParams = function(requestParams) {
		var params = _.clone(requestParams);
		params.userId = request.auth.credentials.userId;
		return params;
	};
    return reply.continue();
Example #17
0
            isSecure: false
        }
    },
    travelogue: config // use '../../' instead of travelogue if testing this repo locally
};

var options = {
  views: {
    engines: { html: 'handlebars' },
    path: __dirname + '/views',
    partialsPath: __dirname + '/views/partials',
    layout: true
  }
};

var server = new Hapi.Server(config.hostname, config.port, options);


server.pack.allow({ ext: true }).require(plugins, function (err) {

    if (err) {
        throw err;
    }
});

var Passport = server.plugins.travelogue.passport;
Passport.use(new instagramStrategy(config.instagram, function (accessToken, refreshToken, profile, done) {

    // Find or create user here...
    return done(null, profile);
}));
Example #18
0
const Path = require('path');
const Hapi = require('hapi');
const Hoek = require('hoek');
const NunjucksHapi = require('nunjucks-hapi');
const viewPath = Path.join(__dirname, 'views')
const env = NunjucksHapi.configure(viewPath);
const Routes = require('./routes.js');
const Auth = require('./authentication.js');

// do anything you want to the env here
env.addFilter('somefilter', function(str, count) {
  // return some string
});

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
    port: Number(process.argv[2] || 9000),
    host: 'localhost'
});

server.register(require('vision'), (err) => {
    Hoek.assert(!err, err);
});
server.register(require('inert'), (err) => {
    Hoek.assert(!err, err);
});
server.register(require('hapi-auth-basic'), (err) => {
    server.auth.strategy('simple', 'basic', Auth);
});
 handler: function(request, reply) {
   server.log(['html'], { data: { email: '<h1>Hi Bob</h1>' }});
   reply('ok');
 }
Example #20
0
'use strict';
require('dotenv').load();
const Hapi = require('hapi');
const dataSet = require('../data/studentData.json');
const server = new Hapi.Server();
server.connection({
    port: process.env.port || 7000
});

server.register([{
    register: require('inert')
},{
    register: require('vision')
},{
    register: require('./core'),
    options:{
        data: dataSet
    }
}], error =>{
    if(error){
        console.log("Error:",error);
    }else{
        //Start the server
       server.start(()=>{
        console.log('Hapi server running at port:',server.info.uri);
        }); 
    }
})

Example #21
0
var Hapi = require('hapi'),
Routes = require('./routes'),
Db = require('./config/db'),
Config = require('./config/config'),
Good = require('good');
var Path = require('path');

var app = {};
app.config = Config;

//For older version of hapi.js
//var server = Hapi.createServer(app.config.server.host, app.config.server.port, {cors: true});

var server = new Hapi.Server();

server.connection({ port: app.config.server.port });

//server.route(Routes.endpoints);
 server.views({
 	engines: { html: require('handlebars') },
 	layout : true,
 	path: __dirname + '/views',
		layoutPath : Path.join(__dirname, './views/layouts'), //setting Global Layout,
		partialsPath : Path.join(__dirname,'./views/layouts/partial') //partial Views
	});

 server.route(Routes.endpoints);

 server.register({

 	register : Good,
Example #22
0
var Hapi = require('hapi');

var server = new Hapi.Server(3009, {
  views: {
    path: __dirname + '/../views',
    engines: {
      'html': {
        module: require('handlebars'),
        compileMode: 'async'
      }
    }
  }
});

server.route({
  method: 'GET',
  path: '/',
  handler: function (request, reply) {
      reply.view('index');
  }
});
Example #23
0
'use strict';

let Hapi = require('hapi');

let port = process.env.PORT || 3000;

const server = new Hapi.Server();
server.connection({ port: port });

server.register(require('inert'), (err) => {

  if (err) {
    throw err;
  }

  server.route({
    method: 'GET',
    path: '/{param*}',
    handler: {
      directory: {
        path: 'src/client'
      }
    }
  });

  server.start((err) => {

    if (err) {
      throw err;
    }
Example #24
0
describe('User', function () {

    var dbConnection;
    var SERVER_URL = 'http://example.com:8080';

    var credentials = {
        id: '531df1ee9595c6b610d64476',
        key: 'd76db572-0089-4154-8295-e2999260ade0',
        algorithm: 'sha256'
    };

    var initUser = function(done) {
        var user = {
            "__v" : 0,
            "_id" : new Mongoose.Types.ObjectId("531df1ee9595c6b610d64476"),
            "api_keys" : [ 
                "d76db572-0089-4154-8295-e2999260ade0"
            ],
            "email" : "existing@users.com",
            "name" : {
                "first" : "Barry",
                "last" : "White"
            },
            "password" : "$2a$10$5bNmnl.IexSpoaXNtFE63ef0Smtzk.7JqYLuHY3w.hJBrsfMYaHkm",
            "registered" : true,
        };

        var collection = dbConnection.connection.db.collection("users");
        // Insert a single document
        collection.insert(user, function() {
            return done();
        });
    };

    before(function (done) {
        dbConnection = Mongoose.connect('mongodb://localhost:27017/teatime-test', {db: { native_parser: true }}, function(err) {
            initUser(done);
        });
    });

    after(function (done) {
        dbConnection.connection.db.dropDatabase( function(err) {
            Mongoose.disconnect(function(err, result) {
                return done();
            });
        });
    });

    process.env.PAGINATE_LIMIT_MAX = 500;
    process.env.PAGINATE_LIMIT     = 100;
    process.env.SELECT_FIELDS_USER = "_id name registered image";

    var config = {
        host: 'localhost',
        port: +process.env.PORT || 9001
    };

    var server = new Hapi.Server();
    server.connection(config)

    server.register(require('hapi-auth-hawk'), function (err) {
        server.auth.strategy('hawk', 'hawk', { getCredentialsFunc: Auth.getCredentials });
    });

    server.register([
        require('../routes/auth'),
        require('../routes/users')
    ], function(err) {

    });

    var hawkHeader = function (path, method) {
        return Hawk.client.header(SERVER_URL + path, method, {credentials: credentials});
    };

    it('views their own profile', function(done) {
        var endpoint = '/users/me';
        var url = SERVER_URL + endpoint;
        var method = 'GET';


        server.inject({url: url, method: 'GET',  headers: { authorization: hawkHeader(endpoint, method).field } }, function(res) {
            expect(res.statusCode).to.equal(200);
            done();
        });
    });

    it('cannot view a non existant profile', function(done) {
        var endpoint = '/users/000000000000000000000000';
        var url = SERVER_URL + endpoint;
        var method = 'GET';

        server.inject({url: url, method: method, headers: { authorization: hawkHeader(endpoint, method).field } }, function(res) {
            expect(res.statusCode).to.equal(404);
            done();
        });
    });

    it('updates their own email', function(done) {
        var endpoint = '/users/me';
        var url = SERVER_URL + endpoint;
        var method = 'PUT';

        var payload = {
            email : "existing@users.com"
        };

        server.inject({url: url, method: method, payload: payload, headers: { authorization: hawkHeader(endpoint, method).field } }, function(res) {
            expect(res.statusCode).to.equal(200);
            done();
        });
    });

    it('updates their own name to just first name', function(done) {
        var endpoint = '/users/me';
        var url = SERVER_URL + endpoint;
        var method = 'PUT';

        var payload = {
            name: "Barry"
        };

        server.inject({url: url, method: method, payload: payload, headers: { authorization: hawkHeader(endpoint, method).field } }, function(res) {
            expect(res.statusCode).to.equal(200);
            done();
        });
    });

    it('updates their own full name', function(done) {
        var endpoint = '/users/me';
        var url = SERVER_URL + endpoint;
        var method = 'PUT';

        var payload = {
            name: "Barry White"
        };

        server.inject({url: url, method: method, payload: payload, headers: { authorization: hawkHeader(endpoint, method).field } }, function(res) {
            expect(res.statusCode).to.equal(200);
            done();
        });
    });

    it('updates their own password', function(done) {
        var endpoint = '/users/me';
        var url = SERVER_URL + endpoint;
        var method = 'PUT';

        var payload = {
            newPassword: "a new password",
            oldPassword: "password"
        };

        server.inject({url: url, method: method, payload: payload, headers: { authorization: hawkHeader(endpoint, method).field } }, function(res) {
            expect(res.statusCode).to.equal(200);
            done();
        });
    });

    it('cannot update their own password because original password was not sent', function(done) {
        var endpoint = '/users/me';
        var url = SERVER_URL + endpoint;
        var method = 'PUT';

        var payload = {
            newPassword: "password"
        };

        server.inject({url: url, method: method, payload: payload, headers: { authorization: hawkHeader(endpoint, method).field } }, function(res) {
            expect(res.statusCode).to.equal(400);
            done();
        });
    });

    it('cannot update their own password because original password is incorrect', function(done) {
        var endpoint = '/users/me';
        var url = SERVER_URL + endpoint;
        var method = 'PUT';

        var payload = {
            newPassword: "password",
            oldPassword: "incorrectpassword"
        };

        server.inject({url: url, method: method, payload: payload, headers: { authorization: hawkHeader(endpoint, method).field } }, function(res) {
            expect(res.statusCode).to.equal(401);
            done();
        });
    });

    it('cannot update their own profile because no data in payload', function(done) {
        var endpoint = '/users/me';
        var url = SERVER_URL + endpoint;
        var method = 'PUT';

        var payload = {};

        server.inject({url: url, method: method, payload: payload, headers: { authorization: hawkHeader(endpoint, method).field } }, function(res) {
            expect(res.statusCode).to.equal(400);
            done();
        });
    });

    it('cannot update someone else\'s profile', function(done) {
        var endpoint = '/users/000000000000000000000000';
        var url = SERVER_URL + endpoint;
        var method = 'PUT';

        var payload = {
            email : "existing@users.com",
            name: "Barry White",
            newPassword: "password",
            oldPassword: "password"
        };

        server.inject({url: url, method: method, payload: payload, headers: { authorization: hawkHeader(endpoint, method).field } }, function(res) {
            expect(res.statusCode).to.equal(400);
            done();
        });
    });

});
Example #25
0
'use strict';

var Hapi = require('hapi');
var Inert = require('inert');
var Path = require('path');

var server = new Hapi.Server();

server.connection({
  host: 'localhost',
  port: Number(process.argv[2] || 8080)
});

server.register(Inert, function (err) {
    if (err) throw err;
});

function index(request, reply) {
  reply('Hello hapi');
}

function name(request, reply) {
  reply('Hello ' + request.params.name);
}

server.route({
  path: '/',
  method: 'GET',
  handler: {
    file: Path.join(__dirname, 'index.html')
  }
Example #26
0
'use strict';

const Boom = require('boom');
const Hapi = require('hapi');
const H2O2 = require('h2o2');
const once = require('once');
const Wreck = require('wreck');

const proxyMap = {
  '/friends': 'http://localhost:6000/friends',
  '/recent': 'http://localhost:5000/recent',
  '/prefs': 'http://localhost:5000/prefs'
};

var server = new Hapi.Server();

server.register({ register: H2O2 }, err => {
  if (err) { return console.error(err); }

  server.connection({ host: 'localhost', port: 7000 });

  const proxyHandler = {
    proxy: {
      mapUri: (req, cb) => {
        const uri = proxyMap[req.path];
        if (!uri) { return cb(Boom.notFound()); }
        cb(null, uri, req.headers);
      },
      onResponse: (err, res, req, reply, settings, ttl) => {
        if (err) { return reply(err); }
        reply(res);
Example #27
0
File: server.js Project: arb/crumb
var Hapi = require('hapi');

var serverOptions = {
    views: {
        path: __dirname + '/templates',
        engines: {
            html: require('handlebars')
        }
    }
};

var server = new Hapi.Server('127.0.0.1', 8000, serverOptions);

server.pack.register({ plugin: require('../'), options: { cookieOptions: { isSecure: false } } }, function (err) {
    if (err) throw err;
});

server.route({
    method: 'get',
    path: '/',
    handler: function (request, reply) {
        return reply.view('index', { title: 'test', message: 'hi' });
    }
});

server.route({
    method: 'post',
    path: '/',
    handler: function (request, reply) {
        return reply.view('message', { title: 'test', message: request.payload.message });
    }
Example #28
0
function shutdown() {
  server.stop(() => console.log('shutdown successful'));
}
Example #29
0
const Fs = require('fs');
const Hapi = require('hapi');
const Path = require('path');
const Rot13 = require('rot13-transform');
const server = new Hapi.Server();

server.connection({
    host :'localhost',
    port:Number(process.argv[2]||8080)
});


server.route({
    method: 'GET',
    path:'/',
    handler:(request,reply)=>{
        var thisFile = Fs.createReadStream(Path.join(__dirname,'input.txt'))
        reply(thisFile.pipe(Rot13()));
    }
})

server.start((err)=>{
    if(err) throw err
})
Example #30
0
'use strict';

var miniprofiler = require('../../../lib/miniprofiler.js');
const Hapi = require('hapi');
const vision = require('vision');

const server = new Hapi.Server();
server.connection({ port: 8083 });

server.register(miniprofiler.hapi(), (err) => {
  if (err) throw (err);
});

server.register(vision, (err) => {
  if (err) throw (err);

  server.views({
    engines: { pug: require('pug') },
    path: './tests/servers/views'
  });

  miniprofiler.hapi().vision(server);
});

server.route({
  method: 'GET',
  path:'/',
  handler: function(request, reply) {
    reply.view('index', { title: 'Hey', message: 'Hello there!' });
  }
});