2016-06-19 18:02:32 +08:00
|
|
|
const Hapi = require('hapi');
|
|
|
|
const HapiSwagger = require('hapi-swagger');
|
2016-06-26 16:44:39 +08:00
|
|
|
const HapiBoom = require('hapi-boom-decorators')
|
2016-06-19 18:02:32 +08:00
|
|
|
const HapiBasicAuth = require('hapi-auth-basic');
|
|
|
|
const Inert = require('inert');
|
|
|
|
const Vision = require('vision');
|
|
|
|
const Package = require('./package');
|
|
|
|
const fs = require('fs');
|
|
|
|
const path = require('path');
|
|
|
|
|
2016-06-24 06:52:45 +08:00
|
|
|
global.Promise = require('bluebird');
|
2016-06-28 07:01:21 +08:00
|
|
|
global.NylasError = require('nylas-core').NylasError;
|
2016-06-24 06:52:45 +08:00
|
|
|
|
2016-06-29 04:56:57 +08:00
|
|
|
const server = new Hapi.Server({
|
|
|
|
connections: {
|
|
|
|
router: {
|
|
|
|
stripTrailingSlash: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2016-06-22 08:51:47 +08:00
|
|
|
server.connection({ port: process.env.PORT || 5100 });
|
2016-06-19 18:02:32 +08:00
|
|
|
|
2016-06-26 16:44:39 +08:00
|
|
|
const plugins = [Inert, Vision, HapiBasicAuth, HapiBoom, {
|
2016-06-19 18:02:32 +08:00
|
|
|
register: HapiSwagger,
|
|
|
|
options: {
|
|
|
|
info: {
|
|
|
|
title: 'Nylas API Documentation',
|
|
|
|
version: Package.version,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}];
|
|
|
|
|
|
|
|
let sharedDb = null;
|
2016-06-24 07:28:48 +08:00
|
|
|
const {DatabaseConnector, SchedulerUtils} = require(`nylas-core`)
|
2016-06-23 15:49:22 +08:00
|
|
|
DatabaseConnector.forShared().then((db) => {
|
2016-06-19 18:02:32 +08:00
|
|
|
sharedDb = db;
|
|
|
|
});
|
|
|
|
|
|
|
|
const validate = (request, username, password, callback) => {
|
|
|
|
const {AccountToken} = sharedDb;
|
|
|
|
|
|
|
|
AccountToken.find({
|
|
|
|
where: {
|
|
|
|
value: username,
|
|
|
|
},
|
|
|
|
}).then((token) => {
|
|
|
|
if (!token) {
|
|
|
|
callback(null, false, {});
|
|
|
|
return
|
|
|
|
}
|
|
|
|
token.getAccount().then((account) => {
|
2016-06-24 07:28:48 +08:00
|
|
|
SchedulerUtils.notifyAccountIsActive(account.id)
|
2016-06-19 18:02:32 +08:00
|
|
|
callback(null, true, account);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
const attach = (directory) => {
|
|
|
|
const routesDir = path.join(__dirname, directory)
|
|
|
|
fs.readdirSync(routesDir).forEach((filename) => {
|
|
|
|
if (filename.endsWith('.js')) {
|
|
|
|
const routeFactory = require(path.join(routesDir, filename));
|
|
|
|
routeFactory(server);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
server.register(plugins, (err) => {
|
|
|
|
if (err) { throw err; }
|
|
|
|
|
|
|
|
attach('./routes/')
|
|
|
|
attach('./decorators/')
|
|
|
|
|
|
|
|
server.auth.strategy('api-consumer', 'basic', { validateFunc: validate });
|
|
|
|
server.auth.default('api-consumer');
|
|
|
|
|
|
|
|
server.start((startErr) => {
|
|
|
|
if (startErr) { throw startErr; }
|
2016-06-28 01:28:43 +08:00
|
|
|
console.log('API running at:', server.info.uri);
|
2016-06-19 18:02:32 +08:00
|
|
|
});
|
|
|
|
});
|