Exemplo n.º 1
0
/**
 * Sets up a Koa app instance.
 * @param  {Object} app A Koa app instance as created by `new Koa()`
 * @return {Object}     A node `http` server instance
 */
function bootstrap(app, options) {
  var config = defaults({}, options, DEFAULT_CONFIGURATION);
  var log = logger.get(options);
  log.info('Starting and configuring Koa server');

  // Setup global error handler and logger
  app.use(error(config.error));
  app.on('error', (error) => {
    log.error('Unexpected exception ', error);
  });

  // Configure and setup middlewares
  app.use(bodyParser());
  app.use(morgan(config.morgan.format, config.morgan.options));
  app.use(responseTime());
  app.use(helmet(config.helmet));
  app.use(compress({
    flush: zlib.Z_SYNC_FLUSH
  }));
  app.use(conditional());
  app.use(etag());
  app.use(adapt(cacheControl(config.cacheControl)));
  app.use(cors(config.cors));
  app.use(favicon(config.favicon));

  app.use(jwt(config.jwt.options).unless(config.jwt.unless));
  app.use(json());

  return app;
}
Exemplo n.º 2
0
export default () => compose([
  convert(cors()),
  favicon(),
  conditional(),
  etag(),
  compress(),
]);
Exemplo n.º 3
0
module.exports = function (app) {
  // middleware configuration
  app.use(responseTime());
  app.use(err());

  if (config.app.env !== 'test') {
    app.use(logger());
  }

  app.use(conditional());
  app.use(compress());
  app.use(etag());
  if (config.app.env === 'development') {
    // upgrade to the real koa-livereload when issue #5 is fixed
    app.use(require('./koa-livereload')({
      excludes: ['/modules', '/templates']
    }));
  }

  if (config.app.env !== 'production') {
    app.use(json());
  }

  app.use(serve(path.join(__dirname, '../../client')));

  app.keys = [config.secret];
  app.use(session());

  // mount all the routes defined in the api controllers
  fs.readdirSync(path.join(__dirname, '../controllers')).forEach(function (file) {
    require('../controllers/' + file).init(app);
  });
};
Exemplo n.º 4
0
Arquivo: koa.js Projeto: vpls/vk
module.exports = function(app) {
  let env = app.env;
  app.use(convert(bodyparser));
  app.use(convert(json()));
  app.use(convert(logger()));
  app.use(etag());

  app.use(views(config.root + '/server/views',{ extension: 'jade' }));

  if ('production' === env) {
    app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(serve(path.join(config.root, 'public')));
    app.set('appPath', config.root + '/public');
  }

  if ('development' === env || 'test' === env) {
    app.use(serve(path.join(config.root, 'build')));
    app.use(serve(path.join(config.root, 'client')));
    console.log("development");
    // app.use(livereload({
    //   port : 33333
    // }));
    let compiler = webpack(webpackConf)
    app.use(require('koa-webpack-dev-middleware')(compiler, webpackConf.devServer));
    let hotMiddleware = require('webpack-hot-middleware')(compiler);
    app.use(async (ctx,next)=> {
      await hotMiddleware.bind(null, ctx.req, ctx.res);
      await next();
    });
  }

};
Exemplo n.º 5
0
export function init(options = {}) {
  const passport = initPassport(options.PassportStrategy)

  return app.use(generatePrometheusMiddleware(router, {
              ignore: [/^\/repository/]
            }))
            .use(generateProblemMiddleware({
              exposableErrorTypes: [
                CHECK_ERROR_TYPE,
                GITHUB_ERROR_TYPE,
                REPO_ERROR_TYPE
              ]
            }))
            .use(morgan(morganFormat, {skip: morganSkip}))
            .use(convert(session({store: store})))
            .use(bodyParser())
            .use(passport.initialize())
            .use(passport.session())
            .use(compress())
            .use(router.routes())
            .use(router.allowedMethods())
            .use(conditional())
            .use(etag())
            .use(serve(
              nconf.get('STATIC_DIR'), {
                index: 'none',
                maxage: 1.7 * 10 ** 8 // ~ 2 days
              }))
            .use(ensureModeMiddleware)
            .use(renderStatic)
}
module.exports = (app) => {
  // session
  app.keys = ['secret1', 'secret2', 'secret3'];
  app.use(convert(session()));

  // logger
  app.use(logger());

  // view engine
  app.use(views(path.resolve(__dirname, 'views'), { extension: 'ejs' }));

  // static
  app.use(koaStatic({
    rootDir: path.resolve(__dirname, 'static'),
  }));

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

  app.use(conditional());
  app.use(etag());
  app.use(body());

  app.use(async (ctx, next) => {
    ctx.body = ctx.request.body;
    await next();
  });

  app.use(new CSRF());

  onerror(app);
};
Exemplo n.º 7
0
/**
 * Returns the middlewares to be used.
 *
 * @param {object} settings - Runtime settings
 * @returns {array} A array with middlewares to use.
 */
export default function middlewares(config, { dev, dist }) {
    const middlewaresList = [];

    if (dev) {
        middlewaresList.push(koaErrors());
    }

    // Security headers
    middlewaresList.push(helmet());

    middlewaresList.push(koaEtag());

    // We only enable gzip in dist
    if (dist) {
        middlewaresList.push(koaCompressor());
    }

    const favicon = config.favicon;
    if (favicon) {
        middlewaresList.push(koaFavicon(favicon));
    }

    if (dist) {
        middlewaresList.push(koaAccesslog());
    } else {
        middlewaresList.push(koaLogger());
    }

    return middlewaresList;
}
Exemplo n.º 8
0
function main() {
  var app = koa();

  app.name = pkg.name;
  app.proxy = true;
  app.poweredBy = false;

  onerror(app, {template: './templates/error.html'});
  sentry(app, raven);
  trace(app);

  app.isProd = app.context.isProd = process.env.NODE_ENV === 'production';

  debug('NODE_ENV=' + process.env.NODE_ENV);

  app.context.raven = raven;

  if (!app.isProd || /koa-trace/.test(process.env.DEBUG)) app.debug();

  app.use(function*(next) {
    this.set('Timing-Allow-Origin', '*');
    yield next;
  });


  app.use(cors({
    origin: true // do something more specific here
  }));

  app.use(favicon(path.resolve(__dirname, '../public/images/favicon.ico')));
  app.use(conditional());
  app.use(etag());
  app.use(serve(path.resolve(__dirname, '../public'), {
    maxage: app.isProd ? ms('30 days') : 0,
    gzip: true
  }));
  app.use(requestId('X-Request-ID'));
  app.use(responseTime());
  app.use(printRequestId());
  app.use(function*(next){
    this.locals = this.locals || {};
    this.locals.context = this;
    yield next;
  });

  app.use(htmlMinifier({
    collapseWhitespace: true,
    minifyJS: true,
    minifyCSS: true
  }));

  if (!app.isProd) {
    debug('Using livereload');
    app.use(require('koa-livereload')());
  }

  routers(app);
  return app;
}
Exemplo n.º 9
0
/**
 * Initialize an app with the given `opts`.
 *
 * @param {Object} opts
 * @return {Application}
 * @api public
 */
function api(opts) {
  opts = opts || {};
  let app = koa();

  // Oauth2 server init & caching
  let oauthServer = oauth2orize.createServer();
  oauth.init(oauthServer);
  generateAccessToken.cacheOauthServer(oauthServer);

  // querystring
  require('koa-qs')(app);
  app.querystring = require('qs');

  app.use(body());

  app.use(cors({
    methods: 'GET,POST,PUT,PATCH,OPTIONS',
    headers: 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since',
    maxAge: 300000,
    credentials: true
  }));

  // Logging
  if ('test' != env) app.use(logger());

  // Passport
  app.use(passport.initialize());

  // Enable app-wide authentication
  app.use(isAuthenticated());

  // Etag
  app.use(conditional());
  app.use(etag());

  // x-response-time
  app.use(responseTime());

  // compression
  app.use(compress());

  // rate limiting
  app.use(ratelimit({
    max: opts.ratelimit,
    duration: opts.duration,
    db: redis.hiringTicket
  }));

  // routing
  app.use(router(app));

  // Error handling
  app.use(error());

  // boot
  load(app, __dirname + '/api');

  return app;
}
Exemplo n.º 10
0
module.exports = function(app) {

  if (app.env === 'production') {
    app.use(conditional());
    app.use(etag());
  }

};
Exemplo n.º 11
0
  /**
   * Use middlewares
   */
  use() {
    this.setResponseTime();

    this.app.server.use(conditional());
    this.app.server.use(etag());

    this.useBodyParser();
  }
Exemplo n.º 12
0
module.exports = function ApplicationWeb(configuration) {
  var app = koa();
  var visitor = ua(configuration.global.applications.api.googleanalytics.key);

  app.keys = [configuration.global.redis.key];
  app.name = configuration.application;
  app.poweredBy = false;

  app.use(responseTime());
  app.use(cors());

  // var optionsSSL;
  //
  // if (environment === 'production') {
  //   optionsSSL = {
  //     key: fs.readFileSync('server.key'),
  //     cert: fs.readFileSync('server.crt')
  //   };
  //
  //   app.use(forceSSL());
  // }

  app.use(function* (next) {
    this.locals = this.locals || {};
    this.locals.body = {};
    this.locals.date = new Date();
    this.locals.lang = (typeof this.query.lang !== 'undefined') ? this.query.lang : 'en';
    this.locals.messages = new Messages(this.locals.lang);
    this.locals.querystringParameters = Qs.parse(this.querystring);

    yield next;
  });

  app.use(function* (next) {
    this.locals = this.locals || {};
    yield next;
  });

  app.use(function* (next) {
    if (configuration.environment !== 'development') {
      visitor.pageview(this.request.originalUrl, function(err) {
        console.log('err', err);
      });
    }

    yield next;
  });

  app.use(router(app));

  app.use(gzip());
  app.use(fresh());
  app.use(etag());

  return app;
};
Exemplo n.º 13
0
module.exports = function (app) {
  // middleware configuration
  app.use(responseTime);
  app.use(cors());
  app.use(conditional());
  app.use(etag());
  app.use(bodyParser());
  app.use(authenticate);
  app.use(router(app));
  app.use(logger());

  // create all models first so controllers have them available
  let model, schema;
  for (let name of require('fs').readdirSync(__dirname+'/../models')) {
    if (name[0] === '.') return;
    name = name.substring(0, name.length - 3);
    schema = require('../models/' + name);
    model = mongoose.model(name, schema);
  };

  // auto mount all the simple routes defined in the api controllers
  // initialize complex custom defined routes
  // if route is found in exempt, do not run auth check
  for (let fileName of fs.readdirSync(__dirname+'/../controllers')) {
    let controller = require(__dirname+'/../controllers/' + fileName);
    fileName = fileName.substring(0, fileName.length - 3);
    for (let propName in controller) {
      if (propName === 'init') {
        controller.init(app);
      } else {
        let arr = propName.split("_");
        let methodName = arr[0];
        let handlerName = arr[1];

        let exempt = false;
        for (let endpoint in authExempt) {
          for (let method of authExempt[endpoint]) {
            (fileName === endpoint && handlerName === method) ? exempt = true : false;
          }
        }
        let pathName = `/${config.app.apiPrefix}/${pluralize(fileName)}/${handlerName}`;
        exempt ? app[methodName](pathName, controller[propName]) : app[methodName](pathName, authCheck(),  controller[propName]);
      }
    }
  };

  // mount REST routes for all models last so it doesn't override the controller methods
  for (let model of mongoose.modelNames()){
    // TODO figure out how to inject middleware that executes beforehand, extend koa-mongo-rest
    generateApi(app, mongoose.model(model), '/' + config.app.apiPrefix);
  }
};
Exemplo n.º 14
0
    it('should pass through', function (done) {
      var app = koa();
      app.use(fresh());
      app.use(etag())

      app.use(function *(next) {
        this.status = 500;
        this.body = {error: 'err'};
      });

      request(app.listen())
      .get('/')
      .expect({error: 'err'})
      .expect(500, done);
    });
Exemplo n.º 15
0
    it('should request with etag return source status', function (done) {
      var app = koa();
      app.outputErrors = true;
      app.use(fresh());
      app.use(etag())

      app.use(function *(next) {
        this.redirect('/foo');
      });

      request(app.listen())
      .get('/')
      .set('If-None-Match', '"-2137833482"')
      .expect('Redirecting to <a href="/foo">/foo</a>.')
      .expect(302, done);
    });
Exemplo n.º 16
0
    it('should clean body when status 204', function (done) {
      var app = koa();
      app.outputErrors = true;
      app.use(fresh());
      app.use(etag())

      app.use(function *(next) {
        this.status = 204;
        this.body = {hi: 'foo'};
      });

      request(app.listen())
      .get('/')
      .expect('')
      .expect(204, done);
    });
Exemplo n.º 17
0
    it('should respond with 304', function(done){
      const app = new Koa();

      app.use(conditional());
      app.use(etag());

      app.use((ctx, next) => {
        return next().then(() => {
          ctx.body = body;
        });
      });

      request(app.listen())
      .get('/')
      .set('If-None-Match', calculate(JSON.stringify(body)))
      .expect(304, done);
    })
Exemplo n.º 18
0
    it('should do nothing', function(done){
      const app = new Koa();

      app.use(conditional());
      app.use(etag());

      app.use((ctx, next) => {
        return next().then(() => {
          ctx.body = body;
        });
      });

      request(app.listen())
      .get('/')
      .set('If-None-Match', 'tobi')
      .expect(200, done);
    })
Exemplo n.º 19
0
    it('should HEAD request not etag return 200 and etag', function (done) {
      var app = koa();
      app.outputErrors = true;
      app.use(fresh());
      app.use(etag())

      app.use(function *(next) {
        this.status = 200;
        this.body = {hi: 'foo'};
      });

      request(app.listen())
      .head('/')
      .expect('etag', '"-2137833482"')
      .expect({})
      .expect(200, done);
    });
Exemplo n.º 20
0
module.exports = function(){
	var app = koa();
  
  // compress
  app.use(compress({
    filter: function (content_type) {
    	return /text/i.test(content_type)
    },
    threshold: 2048,
    flush: require('zlib').Z_SYNC_FLUSH
  }));
  
  // etag start
  app.use(conditional());
  app.use(etag());
  
	var basePath = path.dirname(module.parent.filename);
	app.use(views(basePath + '/views', {
	  map: {
	    html: 'hogan'
	  }
	}));
	
	
	var config = require(basePath + '/package.json');
	// https://github.com/koajs/koa-redis
	if(config.session && config.session.keys) {
    var redisConfig = require(basePath + '/redis.json');
		app.keys = [config.session.keys];
		app.use(session({
		  store: redisStore(redisConfig)
		}));
		// 页面加载后生成sessionid
		app.use(function *(next) {
		  this.session.name = 'koa-redis';
		  yield next;
		});
	}
	
	// https://github.com/alexmingoia/koa-router
	var router = global.router = require('koa-router')();
	app.use(router.routes()).use(router.allowedMethods());
	
	return app;
};
Exemplo n.º 21
0
    it('should POST request with etag return 200 and not etag', function (done) {
      var app = koa();
      app.outputErrors = true;
      app.use(fresh());
      app.use(etag())

      app.use(function *(next) {
        this.status = 201;
        this.body = {hi: 'foo'};
      });

      request(app.listen())
      .post('/')
      .set('If-None-Match', '"-2137833482"')
      .expect('etag', '"-2137833482"')
      .expect({hi: 'foo'})
      .expect(201, done);
    });
Exemplo n.º 22
0
module.exports = function (app) {
  // middleware configuration
  app.use(conditional());
  app.use(etag());
  app.use(router(app));
  app.use(logger());
  app.use(responseTime);
  app.use(cors());

  // middleware below this line is only reached if jwt token is valid
  // TODO enable jwt auth app.use(jwt({secret: config.app.secret}));

  // create all models first so controllers have them available
  let model, schema;
  for (let name of require('fs').readdirSync(__dirname+'/../models')) {
    if (name[0] === '.') return;
    name = name.substring(0, name.length - 3);
    schema = require('../models/' + name);
    model = mongoose.model(name, schema);
  };

  // auto mount all the simple routes defined in the api controllers
  // initialize complex custom defined routes
  for (let fileName of fs.readdirSync(__dirname+'/../controllers')) {
    let controller = require(__dirname+'/../controllers/' + fileName);
    fileName = fileName.substring(0, fileName.length - 3);
    for (let propName in controller) {
      if (propName === 'init') {
        controller.init(app);
      } else {
        let arr = propName.split("_");
        let methodName = arr[0];
        let handlerName = arr[1];
        app[methodName](`/${config.app.apiPrefix}/${pluralize(fileName)}/${handlerName}`, controller[propName]);
      }
    }
  };

  // mount REST routes for all models last so it doesn't override the controller methods
  for (let model of mongoose.modelNames()){
    generateApi(app, mongoose.model(model), '/' + config.app.apiPrefix);
  }
};
Exemplo n.º 23
0
module.exports = function (app) {
  // middleware configuration
  app.use(responseTime());
  app.use(function * (next) {
    try {
      yield next;
    } catch (err) {
      this.status = err.status || 500;
      this.body = err.message || require('http').STATUS_CODES[this.status];
      this.app.emit('error', err, this);
    }
  });

  if (config.app.env !== 'test') {
    app.use(logger());
  }

  app.use(conditional());
  app.use(compress());
  app.use(etag());

  if (config.app.env === 'development') {
    // upgrade to the real koa-livereload when issue #5 is fixed
    /*app.use(require('./koa-livereload')({
      excludes: ['/modules', '/templates']
    }));*/
  }

  if (config.app.env !== 'production') {
    app.use(json());
  }

  app.use(serve(path.join(__dirname, '../../client')));

  app.keys = [config.secret];
  app.use(session());

  // mount all the routes defined in the api controllers
  fs.readdirSync(path.join(__dirname, '../controllers')).forEach(function (file) {
    require('../controllers/' + file).init(app);
  });
};
Exemplo n.º 24
0
  Server.prototype.init = function () {
    var layoutPage = config.isDev ? '_layout' : '_layout.production';
    var staticMaxAge = 0;

    this.app.keys = ['fnjklhjh89347932kejlqw'];
    this.app.use(bodyParser());
    this.app.use(methodOverride());
    this.app.use(session({
      path: '/',
      httpOnly: true,
      maxage: null,
      rewrite: true,
      signed: true
    }));

    render(this.app, {
      root: path.join(this.rootFolder, 'views'),
      layout: layoutPage,
      viewExt: 'html',
      cache: !config.isDev,
      debug: config.isDev,
      locals: {},
      filters: {}
    });

    if (!config.isDev) {
      this.app.use(gzip());
      this.app.use(fresh());
      this.app.use(etag());
      staticMaxAge = 365 * 24 * 60 * 60 * 1000;
    }

    this.app.use(serveStatic(path.join(this.rootFolder, '/public/bower'), {
      maxage: staticMaxAge
    }));
    this.app.use(serveStatic(path.join(this.rootFolder, config.server.assets), {
      maxage: staticMaxAge
    }));


    return this;
  };
Exemplo n.º 25
0
    it('should request with etag return 304', function (done) {
      var app = koa();
      app.outputErrors = true;
      app.use(fresh());
      app.use(etag())

      app.use(function *(next) {
        this.status = 200;
        this.body = {hi: 'foo'};
      });

      request(app.listen())
      .get('/')
      .set('If-None-Match', '"-2137833482"')
      .expect('etag', '"-2137833482"')
      .expect('')
      .expect(304, function (err, res) {
        should.not.exist(err);
        should.not.exist(res.headers['content-type']);
        should.not.exist(res.headers['content-length']);
        done();
      });
    });
Exemplo n.º 26
0
var geocoder = require( './lib/geocoder' )({
  geocode: maybeGeocode
});
var locator = require( './lib/locator' )();

var koa = require( 'koa' );
var path = require( 'path' );
var app = module.exports = koa();

// Calculate response time, at the top before any other middleware,
// to wrap all subsequent middlewares.
app.use( responseTime() );
app.use( logger() );
app.use( compress() );
app.use( fresh() );
app.use( etag() );
app.use( jsonp() );
// Support `fields` query string to reduce response, @see json-mask.
app.use( mask() );
app.use( selector() );

// Small fix to prevent request for favicon.ico.
router.get( '/favicon.ico', function *() {
  this.status = 304;
  this.type = "image/x-icon";
} );

// The routes are first handled by geocoder to ensure lng and lat params.
// It then goes through the first cache layer that will check for locations
// cache to return. If not, if then check if the map KML is cached and set
// the body so that the loader does not request Google again. The loader
Exemplo n.º 27
0
const Koa = require('koa');

const app = module.exports = new Koa();

// error handler to JSON stringify errors
const errorRes = require('./middleware/error-res');
app.use(errorRes);

const morgan = require('./middleware/morgan');
app.use(morgan);

app.use(adapt(favicon(require.resolve('./public/favicon.ico'))));
app.use(adapt(require('koa-response-time')()));
app.use(adapt(conditional()));
app.use(adapt(etag()));

app.use(adapt(Compress({
    flush: require('zlib').Z_SYNC_FLUSH
})));
app.keys = ['gf-weidian-composite'];

app.use(adapt(session({
    maxAge: 24 * 60 * 60 * 1000 // One Day
}, app)));

app.use(adapt(bodyParser));
app.use(adapt(require('koa-validate')()));

/*var json = require('koa-json');
app.use(json({ pretty: false, param: 'pretty' }));*/
Exemplo n.º 28
0
module.exports = options => compose([
  conditional(),
  etag(),
  compress(),
  serveStatic(options),
]);
Exemplo n.º 29
0
var conditional = require('koa-conditional-get');
var etag        = require('koa-etag');
var duration    = require('./middleware/duration');
var koaLogger   = require('./middleware/logger');
var koaStatic   = require('koa-static');
var resume      = require('./routes/resume');

//configs
var port   = process.env.PORT || config.port;
var logger = devlog.channel('portfolio');

// middleware for koa
// etag works together with conditional-get
app.use(cors());  //CORS
app.use(conditional()); //needed by etag
app.use(etag());        //etag for cache management
app.use(duration());    //puts "Duration" in the header
app.use(koaLogger());    //puts "Duration" in the header
app.use(koaStatic(config.public)); //specify public folder

// middleware for socket.io's connect and disconnect
app.io.use(function*(next) {
  // on connect
  logger.log('socket connected');
  yield * next;
  logger.log('socket disconnected');
  // on disconnect
});

app.use(route.get('/api/resume/', resume.get));
Exemplo n.º 30
0
import conditional from 'koa-conditional-get';

/*
 * We want to load errorHandler first, because usually, the global uncaught exception
 * catch will be instanciated inside it.
 */
import errorHandler from './middlewares/errorHandler';
// eslint-disable-next-line import/no-extraneous-dependencies, import/first
import appMiddlewares from '__app_modules__server_middlewares__';

import renderer from './middlewares/renderer';
import storeCreator from './middlewares/store';
import router from './middlewares/router';
import actionDispatcher from './middlewares/actionDispatcher';
import staticAssetsServer from './middlewares/staticAssetsServer';

export default compose([
    // Enable Hot Reload when vitamin devServer url differs from app url (externalUrl)
    process.env.NODE_ENV !== 'production' &&
        function* setCORS(next) { this.set('Access-Control-Allow-Origin', '*'); yield next; },
    conditional(),
    etag(),
    errorHandler(),
    ...appMiddlewares,
    staticAssetsServer(),
    storeCreator(),
    actionDispatcher(),
    router(),
    renderer(),
].filter(Boolean));