ds.once('connected', function () {

    // Create the model
    var ParkingLotService = ds.createModel('ParkingLotService', {});

    // Refine the methods
    ParkingLotService.freespaces = function (id, cb) {
        ParkingLotService.GetFreePlacesForArticle({
            sourceUUID: 'user-8161fb80-36e6-11e6-ac61-9e71128cae77',
            destinationUUID: 'parker-5c74333d-a0e4-440d-844f-b23fefbed4f1',
            articleID: id
        }, function (err, response) {
            console.log(response);
            var result = response.GetFreePlacesForArticleResult || {};
            result.name = 'Bratislava Tower 115';
            cb(err, result);
        });
    };

    // Map to REST/HTTP
    loopback.remoteMethod(
        ParkingLotService.freespaces, {
            accepts: [
                {
                    arg: 'id', type: 'number', required: true,
                }
            ],
            returns: {arg: 'result', type: 'object', root: true},
            http: {verb: 'get', path: '/:id/freespaces'}
        }
    );

    // Expose to REST
    app.model(ParkingLotService);

    // LoopBack REST interface
    app.use(app.get('restApiRoot'), loopback.rest());
    // API explorer (if present)
    try {
        var explorer = require('loopback-explorer')(app);
        console.log('explorer started');
        app.use('/explorer', explorer);
        app.once('started', function (baseUrl) {
            console.log('Browse your REST API at %s%s', baseUrl, explorer.route);
        });
    } catch (e) {
        console.log(
            'Run `npm install loopback-explorer` to enable the LoopBack explorer'
        );
    }

    app.use(loopback.urlNotFound());
    app.use(loopback.errorHandler());

    if (require.main === module) {
        app.start();
    }


});
Beispiel #2
0
// boot scripts mount components like REST API
boot(app, __dirname);

// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:
//   app.use(loopback.static(path.resolve(__dirname', '../client')));
var websitePath = require('path').resolve(__dirname, '../client');
app.use(loopback.static(websitePath));

// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.use(loopback.urlNotFound());

// The ultimate error handler.
app.use(loopback.errorHandler());

app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    console.log('Web server listening at: %s', app.get('url'));
  });
};

// start the server if `$ node server.js`
if (require.main === module) {
  app.start();
ds.once('connected', function () {

  // Create the model
  var WeatherService = ds.createModel('WeatherService', {});

  // Refine the methods
  WeatherService.forecast = function (zip, cb) {
    WeatherService.GetCityForecastByZIP({ZIP: zip || '94555'}, function (err, response) {
      console.log('Forecast: %j', response);
      var result = (!err && response.GetCityForecastByZIPResult.Success) ?
        response.GetCityForecastByZIPResult.ForecastResult.Forecast : [];
      cb(err, result);
    });
  };

  WeatherService.weather = function (zip, cb) {
    WeatherService.GetCityWeatherByZIP({ZIP: zip || '94555'}, function (err, response) {
      console.log('Weather: %j', response);
      // var result = response.GetCityWeatherByZIPResult.Temperature;
      var result = response;
      cb(err, result);
    });
  };

  // Map to REST/HTTP
  loopback.remoteMethod(
    WeatherService.forecast, {
      accepts: [
        {arg: 'zip', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/forecast'}
    }
  );

  loopback.remoteMethod(
    WeatherService.weather, {
      accepts: [
        {arg: 'zip', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/weather'}
    }
  );

  // Expose to REST
  app.model(WeatherService);

  // LoopBack REST interface
  app.use(app.get('restApiRoot'), loopback.rest());
// API explorer (if present)
  try {
    var explorer = require('loopback-explorer')(app);
    app.use('/explorer', explorer);
    app.once('started', function (baseUrl) {
      console.log('Browse your REST API at %s%s', baseUrl, explorer.route);
    });
  } catch (e) {
    console.log(
      'Run `npm install loopback-explorer` to enable the LoopBack explorer'
    );
  }

  app.use(loopback.urlNotFound());
  app.use(loopback.errorHandler());

  if (require.main === module) {
    app.start();
  }

});
Beispiel #4
0
ds.once('connected', function () {

  // Create the model
  var worms = ds.createModel('worms', {});

  // Helper functions
  function GetVals(x){
    var vals = {}
    Object.keys(x).forEach(function (key) {
      var value = x[key].$value
      vals[key] = value;
    });
    return(vals);
  }

  // API routes
  worms.children = function (id, cb) {
    worms.getAphiaChildrenByID({AphiaID: id || '106135'}, function (err, response) {
      // console.log('children: %j', response);
      var result = !err ?
        response.return.item : [];
      var result2 = result.map(GetVals)
      cb(err, result2);
    });
  };

  worms.common = function (id, cb) {
    worms.getAphiaVernacularsByID({AphiaID: id || '1080'}, function (err, response) {
      var result = !err ?
        response.return.item : [];
      var result2 = result.map(GetVals)
      cb(err, result2);
    });
  };

  worms.names = function (id, cb) {
    worms.getAphiaNameByID({AphiaID: id || '1080'}, function (err, response) {
      var result = !err ?
        response.return : [];
      var result2 = {name: result.$value}
      // var result = response;
      cb(err, result2);
    });
  };

  worms.synonyms = function (id, cb) {
    worms.getAphiaSynonymsByID({AphiaID: id || '733271'}, function (err, response) {
      var result = !err ?
        response.return.item : [];
      var result2 = [result].map(GetVals)
      // var result2 = response;
      cb(err, result2);
    });
  };

  worms.sources = function (id, cb) {
    worms.getSourcesByAphiaID({AphiaID: id || '1080'}, function (err, response) {
      var result = !err ?
        response.return.item : [];
      var result2 = result.map(GetVals)
      // var result2 = response;
      cb(err, result2);
    });
  };

  // worms.extid = function (id, type, cb) {
  //   worms.getExtIDbyAphiaID({AphiaID: id || '1080', type: type || 'ncbi'}, function (err, response) {
  //     console.log('extid: %j', response);
  //     // var result = !err ?
  //     //   response.return.item : [];
  //     // var result2 = result.map(GetVals)
  //     var result2 = response;
  //     cb(err, result2);
  //   });
  // };

  worms.recordsbyvernacular = function (vernacular, cb) {
    worms.getAphiaRecordsByVernacular({vernacular: vernacular || 'salmon'}, function (err, response) {
      var result = !err ?
        response.return.item : [];
      var result2 = [result].map(GetVals)
      // var result2 = response;
      cb(err, result2);
    });
  };

  worms.recordsbydate = function (startdate, enddate, cb) {
    worms.getAphiaRecordsByDate({startdate: startdate || '2014-06-01T00:00:00', enddate: enddate || '2014-06-02T00:00:00'}, function (err, response) {
      var result = !err ?
        response.return.item : [];
      var result2 = result.map(GetVals)
      // var result2 = response;
      cb(err, result2);
    });
  };

  worms.recordsbyextid = function (id, type, cb) {
    worms.getAphiaRecordByExtID({id: id || '6830', type: type || 'ncbi'}, function (err, response) {
      var result = !err ?
        response.return : [];
      var result2 = [result].map(GetVals)
      // var result2 = response;
      cb(err, result2);
    });
  };

  worms.recordsbyid = function (id, cb) {
    worms.getAphiaRecordByID({AphiaID: id || '1080'}, function (err, response) {
      var result = !err ?
        response.return : [];
      var result2 = [result].map(GetVals)
      // var result2 = response;
      cb(err, result2);
    });
  };

  worms.records = function (scientificname, cb) {
    worms.getAphiaRecords({scientificname: scientificname || "Holothuria edulis"}, function (err, response) {
      var result = !err ?
        response.return.item : [];
      var result2 = result.map(GetVals)
      // var result2 = response;
      cb(err, result2);
    });
  };

  worms.matchrecords = function (scientificname, cb) {
    worms.matchAphiaRecordsByNames({scientificname: scientificname || "Holothuria edulis"}, function (err, response) {
      var result = !err ?
        response.return.item.item : [];
      var result2 = [result].map(GetVals)
      // var result2 = response;
      cb(err, result2);
    });
  };

  worms.hierarchy = function (id, cb) {
    worms.getAphiaClassificationByID({AphiaID: id || '733271', convert: true}, function (err, response) {
      // var result = !err ?
      //   response.return.item : [];
      // var result2 = result.map(GetVals)
      var result = response;
      cb(err, result);
    });
  };

// getChildren(file.return)
// var getChildren = function(obj) {
//   var out = [];
//   var tried = true;
//   var xplus = obj;
//   var nms = ["AphiaID", "rank", "scientificname"];
//   while(tried == true) {
//     var vals = xplus.child;
//     delete vals['attributes'];
//     delete vals['child'];
//     // var vals2 = {
//     //   AphiaID: vals.AphiaID['$value'],
//     //   rank: vals.rank['$value'],
//     //   scientificname: vals.scientificname['$value']
//     // };
//     out.push(vals);
//     var xplus = xplus.child;
//     var tried = xplus.AphiaID;
//     if(tried == undefined) {
//       var tried = false;
//     } else {
//       var tried = true;
//     }
//   };
//   return(out);
// };


  // Map to REST/HTTP
  loopback.remoteMethod(
    worms.children, {
      accepts: [
        {arg: 'id', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/children'}
    }
  );

  loopback.remoteMethod(
    worms.common, {
      accepts: [
        {arg: 'id', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/common'}
    }
  );

  loopback.remoteMethod(
    worms.names, {
      accepts: [
        {arg: 'id', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/names'}
    }
  );

  loopback.remoteMethod(
    worms.synonyms, {
      accepts: [
        {arg: 'id', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/synonyms'}
    }
  );

  loopback.remoteMethod(
    worms.sources, {
      accepts: [
        {arg: 'id', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/sources'}
    }
  );

  // broken right now, not sure why
  // loopback.remoteMethod(
  //   worms.extid, {
  //     accepts: [
  //       {arg: 'id', type: 'string', required: true,
  //         http: {source: 'query'}},
  //       {arg: 'type', type: 'string', required: true,
  //         http: {source: 'query'}}
  //     ],
  //     returns: {arg: 'result', type: 'object', root: true},
  //     http: {verb: 'get', path: '/extid'}
  //   }
  // );

  loopback.remoteMethod(
    worms.recordsbyvernacular, {
      accepts: [
        {arg: 'vernacular', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/recordsbyvernacular'}
    }
  );

  loopback.remoteMethod(
    worms.recordsbydate, {
      accepts: [
        {arg: 'startdate', type: 'string', required: true,
          http: {source: 'query'}},
        {arg: 'enddate', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/recordsbydate'}
    }
  );

  loopback.remoteMethod(
    worms.recordsbyextid, {
      accepts: [
        {arg: 'id', type: 'string', required: true,
          http: {source: 'query'}},
        {arg: 'type', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/recordsbyextid'}
    }
  );

  loopback.remoteMethod(
    worms.recordsbyid, {
      accepts: [
        {arg: 'id', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/recordsbyid'}
    }
  );

  loopback.remoteMethod(
    worms.records, {
      accepts: [
        {arg: 'scientificname', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/records'}
    }
  );

  loopback.remoteMethod(
    worms.matchrecords, {
      accepts: [
        {arg: 'scientificname', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/matchrecords'}
    }
  );

  loopback.remoteMethod(
    worms.hierarchy, {
      accepts: [
        {arg: 'id', type: 'string', required: true,
          http: {source: 'query'}}
      ],
      returns: {arg: 'result', type: 'object', root: true},
      http: {verb: 'get', path: '/hierarchy'}
    }
  );

  // Expose to REST
  app.model(worms);

  // LoopBack REST interface
  app.use(app.get('restApiRoot'), loopback.rest());
  // API explorer (if present)
  try {
    var explorer = require('loopback-explorer')(app);
    app.use('/explorer', explorer);
    app.once('started', function (baseUrl) {
      console.log('Browse your REST API at %s%s', baseUrl, explorer.route);
    });
  } catch (e) {
    console.log(
      'Run `npm install loopback-explorer` to enable the LoopBack explorer'
    );
  }

  app.use(loopback.urlNotFound());
  app.use(loopback.errorHandler());

  if (require.main === module) {
    app.start();
  }

});
Beispiel #5
0
var rateLimiting = require('./middleware/rate-limiting');
app.middleware('routes:after', rateLimiting({limit: 100, interval: 60000}));

var proxy = require('./middleware/proxy');
var proxyOptions = require('./middleware/proxy/config.json');
app.middleware('routes:after', proxy(proxyOptions));

app.middleware('files',
  loopback.static(path.join(__dirname, '../client/public')));
app.middleware('files', '/admin',
  loopback.static(path.join(__dirname, '../client/admin')));

// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.middleware('final', loopback.urlNotFound());

// The ultimate error handler.
app.middleware('final', loopback.errorHandler());

app.start = function() {
  var port = app.get('port');

  http.createServer(app).listen(port, function() {
    console.log('Web server listening at: %s', 'http://localhost:3000/');
    https.createServer(httpsOptions, app).listen(httpsPort, function() {
      app.emit('started');
      console.log('Web server listening at: %s', app.get('url'));
    });
  });
boot(app, __dirname, function(err) {
  if (err) throw err;
  
//
// I would prefer that this code was somewhere else (../boot/passport.js ?)
// I think it could be important that the code is "after" boot, or at a specific point in boot.
// "work in progress" I follow the yellow brick road from googling...
//
// Passport configurators..
var loopbackPassport = require('loopback-component-passport');
var PassportConfigurator = loopbackPassport.PassportConfigurator;
var passportConfigurator = new PassportConfigurator(app);

/*
 * body-parser is a piece of express middleware that
 *   reads a form's input and stores it as a javascript
 *   object accessible through `req.body`
 *
 */
var bodyParser = require('body-parser');

/**
 * Flash messages for passport
 *
 * Setting the failureFlash option to true instructs Passport to flash an
 * error message using the message given by the strategy's verify callback,
 * if any. This is often the best approach, because the verify callback
 * can make the most accurate determination of why authentication failed.
 */
var flash      = require('express-flash');

// attempt to build the providers/passport config
var config = {};
try {
	config = require('../providers.json');
} catch (err) {
	console.trace(err);
	process.exit(1); // fatal
}

// Set up the /favicon.ico
app.use(loopback.favicon());

// request pre-processing middleware
app.use(loopback.compress());

// -- Add your pre-processing middleware here --

// Setup the view engine (jade)
var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// boot scripts mount components like REST API
boot(app, __dirname);

// to support JSON-encoded bodies
app.use(bodyParser.json());
// to support URL-encoded bodies
app.use(bodyParser.urlencoded({
	extended: true
}));

// The access token is only available after boot
app.use(loopback.token({
  model: app.models.accessToken
}));

app.use(loopback.cookieParser(app.get('cookieSecret')));
app.use(loopback.session({
	secret: 'kitty',
	saveUninitialized: true,
	resave: true
}));
passportConfigurator.init();

// We need flash messages to see passport errors
app.use(flash());

//console.log("NO setupModels at the moment");

passportConfigurator.setupModels({
	userModel: app.models.user,
	userIdentityModel: app.models.userIdentity,
	userCredentialModel: app.models.userCredential
});


for (var s in config) {
	var c = config[s];
	c.session = c.session !== false;
	passportConfigurator.configureProvider(s, c);
}
var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;

app.get('/', function (req, res, next) {
  res.render('pages/index', {user:
    req.user,
    url: req.url
  });
});

app.get('/auth/account', ensureLoggedIn('/login.html'), function (req, res, next) {
  res.render('pages/loginProfiles', {
    user: req.user,
    url: req.url
  });
});

app.get('/link/account', ensureLoggedIn('/login.html'), function (req, res, next) {
  res.render('pages/linkedAccounts', {
    user: req.user,
    url: req.url
  });
});

app.get('/local', function (req, res, next){
  res.render('pages/local', {
    user: req.user,
    url: req.url
  });
});

app.get('/signup', function (req, res, next){
  res.render('pages/signup', {
    user: req.user,
    url: req.url
  });
});

app.post('/signup', function (req, res, next) {

  var User = app.models.user;

  var newUser = {};
  newUser.email = req.body.email.toLowerCase();
  newUser.username = req.body.username.trim();
  newUser.password = req.body.password;

  User.create(newUser, function (err, user) {
    if (err) {
      req.flash('error', err.message);
      return res.redirect('back');
    } else {
      // Passport exposes a login() function on req (also aliased as logIn())
      // that can be used to establish a login session. This function is
      // primarily used when users sign up, during which req.login() can
      // be invoked to log in the newly registered user.
      req.login(user, function (err) {
        if (err) {
          req.flash('error', err.message);
          return res.redirect('back');
        }
        return res.redirect('/auth/account');
      });
    }
  });
});

app.get('/login', function (req, res, next){
  res.render('pages/login', {
    user: req.user,
    url: req.url
   });
});

app.get('/link', function (req, res, next){
  res.render('pages/link', {
    user: req.user,
    url: req.url
  });
});

app.get('/auth/logout', function (req, res, next) {
  req.logout();
  res.redirect('/');
});

// -- Mount static files here--
// All static middleware should be registered at the end, as all requests
// passing the static middleware are hitting the file system
// Example:
var path = require('path');
app.use(loopback.static(path.resolve(__dirname, '../client/public')));

// Requests that get this far won't be handled
// by any middleware. Convert them into a 404 error
// that will be handled later down the chain.
app.use(loopback.urlNotFound());

// The ultimate error handler.
app.use(loopback.errorHandler());

  // start the server if `$ node server.js`
  if (require.main === module)
    app.start();
});