Example #1
0
exports.init = function(app) {
	
	var routePage = new Router()

	var routeApi = new Router()

	//api
	routeApi.post('/preview-jade', api.previewJade)

	//page
	routePage.get('/', page.index)

	app.use(tools.settingHandler)
	routePage.use(ua.ua)
	routePage.use(function* (next) {
		this.set('Cache-Control', 'private, no-cache, no-store, must-revalidate')
		yield next
	})

	app
	.use(routePage.routes())
	.use(routePage.allowedMethods())
	
	app
	.use(routeApi.routes())
	.use(routeApi.allowedMethods())

	//404
	app.use(function* (next) {
		this.status =  404
		this.body = '404'
	})

	//end
}
Example #2
0
export function configure(app) {
    app.use(passport.initialize());
    app.use(passport.session());
    
    var authRouter = new Router();
    authRouter.get('/success', loginSuccessHandler);
    authRouter.get('/fail', loginFailureHandler);
    var parser = new BodyParser();
    authRouter.post('/auth/login', parser, passport.authenticate('local', { successReturnToOrRedirect: '/success', failureRedirect: '/fail' }));
    //Configure /auth/github & /auth/github/callback
    authRouter.get('/auth/github', passport.authenticate('github', { scope: ['user', 'repo'] }));
    authRouter.get('/auth/github/callback', passport.authenticate('github', { successReturnToOrRedirect: '/', failureRedirect: '/fail' }));
    app.use(authRouter.middleware());
    
    var APIv1 = new Router();
    // APIv1.use('', authHandler);
    APIv1.get('/user', getHandler);
    APIv1.get('/logout', logoutHandler);
    APIv1.post('/user', parser, postHandler);
    APIv1.post('/upload', parser, uploadHandler);
    
    var ReqRouter = new Router();
    ReqRouter.use('/api', APIv1.routes(), APIv1.allowedMethods());
    app.use(ReqRouter.routes());
    app.use(ReqRouter.allowedMethods());
}
Example #3
0
File: index.js Project: hongkou/mt
module.exports = function(app){
    //spa module
    var spa_router = new router();
    require('./spa')(spa_router);
    app.use(spa_router.routes());

    //activity module
    var activity_router = new router();
    require('./activity')(activity_router);
    app.use(activity_router.routes());

    //wechat
    app.use(require('./wechat')());
}
Example #4
0
module.exports = function(app){
    //spa module
    var spa_router = new router();
    require('./spa')(spa_router);
    app.use(spa_router.routes());

    var pages_router = new router();
    pages_router.prefix('/p');
    require('./p')(pages_router);
    app.use(pages_router.routes());

    //wechat
    app.use(require('./wechat')());
}
Example #5
0
export default (app) => {
  const router = new Router();
  const routerAPI = new Router({
    prefix: '/api',
  });

  views(app, router);
  users(app, routerAPI);

  app
    .use(router.routes())
    .use(router.allowedMethods())
    .use(routerAPI.routes())
    .use(routerAPI.allowedMethods());
};
export default (app) => {

    common.get('/', indexCtrl.index);
    //common.get('/auth/login', authCtrl.getCurrentUser);
    //common.post('/auth/login', authCtrl.login);
    //common.all('/auth/logout', authCtrl.logout);

    app
        .use(common.routes())
        .use(common.allowedMethods());

    app
        .use(router.routes())
        .use(router.allowedMethods());
}
Example #7
0
module.exports =  function (application) {
        modules.forEach((module)=> {
            router[module.method](module.path, module.handler)
        })

        application.use(router.routes());
    };
Example #8
0
  .then(() => {
    const server = new Koa()
    const router = new Router()

    router.get('/a', async ctx => {
      await app.render(ctx.req, ctx.res, '/b', ctx.query)
      ctx.respond = false
    })

    router.get('/b', async ctx => {
      await app.render(ctx.req, ctx.res, '/a', ctx.query)
      ctx.respond = false
    })

    router.get('*', async ctx => {
      await handle(ctx.req, ctx.res)
      ctx.respond = false
    })

    server.use(async (ctx, next) => {
      ctx.res.statusCode = 200
      await next()
    })

    server.use(router.routes())
    server.listen(port, () => {
      console.log(`> Ready on http://localhost:${port}`)
    })
  })
test.beforeEach(t => {
  // initialize our app
  t.context.app = new Koa();

  // override koa's undocumented error handler
  // eslint-disable-next-line unicorn/prefer-add-event-listener
  t.context.app.context.onerror = errorHandler;

  // set up some routes
  const router = new Router();

  // throw an error anywhere you want!
  _.each(statusCodes, code => {
    router.get(`/${code}`, ctx => ctx.throw(code));
  });

  router.get('/basic-auth', auth({ name: 'tj', pass: '******' }), ctx => {
    ctx.body = 'Hello World';
  });

  router.get('/break-headers-sent', ctx => {
    ctx.type = 'text/html';
    ctx.body = 'foo';
    ctx.res.end();
    ctx.throw(404);
  });

  // initialize routes on the app
  t.context.app.use(router.routes());

  // use koa-404-handler
  t.context.app.use(koa404Handler);
});
Example #10
0
 it('without session', function(done) {
   // body...
   let app = koa();
   router.get('/logout', r.logout());
   app.keys = ['keys', 'keykeys'];
   app.use(session({
     store: redisStore(),
     cookie: {
       httpOnly: true,
       path: '/',
       overwrite: true,
       signed: true,
       maxAge: null //one hour in ms
     }
   }));
   app.use(router.routes())
     .use(router.allowedMethods());
   app.use(function*() {
     should.not.exist(this.session);
     this.status.should.eql(302);
   });
   request(app.listen())
     .get('/weixin/logout')
     .expect(302, done);
 });
Example #11
0
 it('without session', function(done) {
   let data = {
     key: 'z',
     val: 'f'
   };
   let app = koa();
   router.post('/addK', bodyParser(), r.addK());
   app.keys = ['keys', 'keykeys'];
   app.use(session({
     store: redisStore(),
     cookie: {
       httpOnly: true,
       path: '/',
       overwrite: true,
       signed: true,
       maxAge: null //one hour in ms
     }
   }));
   app.use(mongo({
     db: 'weixin',
   }));
   app.use(router.routes())
     .use(router.allowedMethods());
   app.use(function*() {
     should.not.exist(this.session.user);
     this.status.should.eql(302);
   });
   request(app.listen())
     .post('/weixin/addK')
     .set('Content-Type', 'application/json')
     .send(JSON.stringify(data))
     .expect(302, done);
 });
Example #12
0
 it('with session', function(done) {
   let app = koa();
   router.get('/getKs', r.getKs());
   app.keys = ['keys', 'keykeys'];
   app.use(session({
     store: redisStore(),
     cookie: {
       httpOnly: true,
       path: '/',
       overwrite: true,
       signed: true,
       maxAge: null //one hour in ms
     }
   }));
   app.use(mongo({
     db: 'weixin',
   }));
   app.use(function*(next) {
     this.session.user = '******';
     yield next;
   });
   app.use(router.routes())
     .use(router.allowedMethods());
   app.use(function*() {
     this.status.should.eql(200);
   });
   request(app.listen())
     .get('/weixin/getKs')
     .expect(200, done);
 });
Example #13
0
 it('method post user wrong', function(done) {
   let app = koa();
   router.post('/login', bodyParser(), r.postLogin());
   app.keys = ['keys', 'keykeys'];
   app.use(session({
     store: redisStore(),
     cookie: {
       httpOnly: true,
       path: '/',
       overwrite: true,
       signed: true,
       maxAge: null //one hour in ms
     }
   }));
   app.use(mongo({
     db: 'weixin',
   }));
   app.use(router.routes())
     .use(router.allowedMethods());
   app.use(function*() {
     should.not.exist(this.session.user);
   });
   request(app.listen())
     .post('/weixin/login')
     .type('form')
     .send({
       username: '******',
       password: ''
     })
     .expect(200, done);
 });
/**
 * Creates and returns a new Koa application.
 * Does *NOT* call `listen`!
 *
 * @return {Promise<Koa>} The configured app.
 */
export default async function createServer() {
  const app = new Koa();
  const router = new Router();

  // adds ctx.ok(), ctx.notFound(), etc..
  app.use(respond());
  app.use(convert(cors()));
  app.use(bodyParser());

  // Container is configured with our services and whatnot.
  const container = getConfiguredContainer();

  // Adds middleware that creates a new Container Scope for each request.
  app.use(containerScope(container));

  // Create the API's.
  createApis(router, container);

  // Install routes
  app.use(router.allowedMethods());
  app.use(router.routes());

  // Default handler when nothing stopped the chain.
  app.use(notFoundHandler);

  return app;
}
Example #15
0
module.exports = function (app) {
  // middleware configuration
  if (config.app.env !== 'production') {
    onerror(app);
  }
  if (config.app.env !== 'test') {
    app.use(logger());
  }
  if (config.staticServe.isNeeded) {
    var serve = require('koa-static');
    app.use(serve(config.staticServe.root));
  } else {
    var cors = require('kcors');
    app.use(cors());
  }
  app.use(bodyParser());
  app.use(jwt({ secret: config.app.secret }).unless({ path: [/^\/api\/auth/]}));

  // mount all the routes defined in resources
  var api = new Router({prefix: '/api'});
  fs.readdirSync('./resources').forEach(function (file) {
    require('../resources/' + file).init(api);
  });
  app
    .use(api.routes())
    .use(api.allowedMethods());

};
Example #16
0
  const composed_route = routerConfig.reduce((prev, curr) => {
    const routes = importDir('./' + curr.folder)
    const router = new Router({ prefix: curr.prefix })

    Object.keys(routes).map(name => routes[name](router))
    return [router.routes(), ...prev]
  }, [])
Example #17
0
export default function(server: Server) {
  const router = new Router();
  const primus = new Primus(server, {
    compression: true,
    transformer: 'engine.io',
  });
  primus.plugin('emit', require('primus-emit'));

  router.get('/sockets.js', ctx => {
    ctx.body = primus.library();
  });
  koa.use(router.routes());

  global.broadcast = function(...args) {
    primus.forEach(s => s.emit(...args));
  };

  primus.on('connection', spark => {
    getAllUsers().then(data => spark.emit('accounts', data));

    spark.on('getAccounts', () => {
      getAllUsers().then(data => spark.emit('accounts', data));
    });
  });

  setInterval(() => {
    getAllUsers().then(users => broadcast('accounts', users));
  }, 10 * 1000);

  return primus;
}
module.exports = function(app){
    //user module
    var user_router = new router();
    user_router.prefix('/api/user');
    require('./user')(user_router);
    app.use(user_router.routes());
}
Example #19
0
test.cb('correct access log items', t => {
    const app = new Koa();
    const router = new Router();

    app.use(logger.access({ type: "file", path: "./logs/" }));

    router.get('/', ctx => {
        ctx.body = "hello";
    });

    app.use(router.routes());

    request(app.listen())
        .get('/')
        .expect(200)
        .end(function (err, result) {
            const res = result;
            const file = `./logs/access.${new Moment().format()}.log`;
            const log = fs.readFileSync(file).toString();
            const items = log.split(/[\n\r]+/);
            items.pop();
            const current = items.pop();
            
            const logItems = current.split(' - ');
            const headers = res.headers;
            
            t.is(true, logItems[13] === `${headers['content-length']}Bytes`);
            t.is(true, logItems[11] === "" + res.statusCode);
            t.is(true, logItems[7] === res.req.path);
            t.is(true, logItems[5] === res.req.method);
            t.end();
        })
});
Example #20
0
module.exports = function(app, passport) {
  // register functions
  var router = new Router();

  router.use(function *(next) {
    this.type = "json";
    yield next;
  });

  router.get("/", function *() {
    this.type = "html";
    yield indexController.index.apply(this);
  });

  router.get("/auth", authController.getCurrentUser);
  router.post("/auth", authController.signIn);

  router.all("/signout", authController.signOut);
  router.post("/signup", authController.createUser);

  // secured routes
  router.get("/value", secured, countController.getCount);
  router.get("/inc", secured, countController.increment);
  router.get("/dec", secured, countController.decrement);
  app.use(router.routes());
};
Example #21
0
module.exports = (stats) => {
    const router = new Router();

    router.get('/', getStats);

    return router.routes();


    ////////////

    function *getStats() {
        const retention = parseRetention(this.request.query);

        this.status = 200;
        this.body = stats.getHistory(retention);


        ////////////

        function parseRetention(q) {
            if (!q || !q.retention) {
                return;
            }

            const i = parseInt(q.retention);
            if (!i) {
                return;
            }

            return i;
        }
    }
};
Example #22
0
File: koa.js Project: gurbano/j5
Server.prototype.addHook = function(prefix, url, cb) {
	let router = new Router();
	router.prefix(`/`+ prefix);
	router.get('/'+url, cb);
	this.app.use(router.routes());	

};
var apiRouter = function*(next) {
  if (/^\/api/.test(this.path)) {
    yield compose([api.routes(), api.allowedMethods()]).call(this, next);
  } else {
    yield next;
  }
};
Example #24
0
function register(app, config) {
  const router = new Router();

  // Register each of the api endpoints
  const endpoints = [user, admin];
  for (const endpoint of endpoints) {
    const { routes, urlBase } = endpoint;
    const apiRouter = new Router({ prefix: `/api${urlBase}` });
    for (const x of routes) {
      const { method, route, handlers } = x;
      const lastHandler = handlers.pop();

      // Secure the api, unless flag set in user.config OR endpoint/route has disabled auth
      if (config.secureApi) {
        if (!endpoint.disableAuth && !x.disableAuth) {
          handlers.unshift(jwt({ secret: config.secrets.session }));
        }
      } else {
        displayInsecureBanner(config.env);
      }

      // Register route with koa-router
      apiRouter[method.toLowerCase()](route, ...handlers, async (ctx) => await lastHandler(ctx));
    }
    app.use(apiRouter.routes()).use(apiRouter.allowedMethods());
  }

  // Register the api endpoint, and the unknown api endpoint
  router.all('/api/', ctx => (ctx.body = { message: 'You\'ve reached the API' }));

  // Register route for all invalid api endpoints
  router.all('/api/*', ctx => {
    ctx.status = 404;
    ctx.body = { message: 'Invalid API Route' };
  });

  // Register the static routes
  const indexPath = join(config.paths.root, 'client', 'index.html');
  router.get('/*', async (ctx, next) => {
    ctx.type = 'text/html';
    ctx.body = createReadStream(indexPath);
    await next();
  });

  app.use(router.routes()).use(router.allowedMethods());
}
Example #25
0
module.exports = function apiMounter(app){
    let allRoute = ctrls;
    log.debug('mounting...');
    allRoute.forEach((r, i, arr) => {
        bindRoute(r);
    });
    app.use(ApiRouter.routes());
};
Example #26
0
export default function routes() {
    return compose(
        [
            router.routes(),
            router.allowedMethods()
        ]
    )
}
function register (app) {
    var router = new Router();
    router.get('/', function(){
        this.body = 'Home Page';
    }); // responds to "/"
    app.use(router.routes());
    app.use(router.allowedMethods());
}
Example #28
0
module.exports = function(options) {
  var config = readConfig(options)
  var router = new koaRouter({prefix: options.prefix})

  browserSync.watch("source/**/*.elm").on("change", browserSync.reload)
  browserSync.watch("public/**/*.html").on("change", browserSync.reload)

  browserSync.watch("stylesheets/**/*.scss", function(event, file) {
    if (event === "change") {
      browserSync.reload("*.css")
    }
  })

  browserSync.init({
    proxy: "localhost:8001",
    logFileChanges: false,
    reloadOnRestart: true,
    notify: false,
    open: false,
    port: 8002,
    ui: {
      port: 8003
    }
  })

  router.get('*', function*(next){
    var file = this.request.url.slice(1)
    var isJs = file.match(/\.js$/)
    var name = file.replace(/\.js$/, '')
    var filePath = path.resolve(`source/${name}.elm`)
    var haveElmFile = fs.existsSync(filePath)

    if(isJs && haveElmFile){
      this.type = 'text/javascript'
      this.body = yield renderElm(filePath, config)
    } else {
      yield next
    }
  })

  router.get('/main.css', function*(next) {
    this.type = 'text/css'
    this.body = yield renderCSS(path.resolve('stylesheets/main.scss'))
  })

  router.get('*', function*(next) {
    this.type = 'text/html'
    this.body = renderHtml(path.resolve('public/index.html'))
  })

  app
    .use(serve(path.resolve('public')))
    .use(router.routes())

  app.listen(8001)

  console.log("Listening on localhost:8001")
}
Example #29
0
File: index.js Project: aikin/ghsm
export default function api() {
  const router = new Router({ prefix });

  Object.keys(routes).forEach(name => routes[name](router));
  return compose([
    router.routes(),
    router.allowedMethods()
  ]);
}
Example #30
0
  const composed = routerConfigs.reduce((prev, curr) => {
    const routes = importDir('./' + curr.folder);
    const router = new Router({
      prefix: curr.prefix
    });

    Object.keys(routes).map(name => routes[name](router));

    return [router.routes(), router.allowedMethods(), ...prev];
  }, []);