Ejemplo n.º 1
0
    this.body = `<form action="/" method="post" enctype="multipart/form-data">
        <input type="file" name="img" multiple="multiple">
        <input type="input" name="foo">
        <input type="input" name="bar">
        <input type="input" name="baz[qux][aa]">
        <input type="input" name="baz[qux][bb]">
        <button>Upload</button>
    </form>`
  },
  upload: function * (next) {
    this.body = JSON.stringify(
      {
        files: this.request.files,
        fields: this.request.fields
      },
      null,
      2
    )
  }
}

app.use(
  body({
    querystring: require('qs'),
    formLimit: '6mb'
  })
)
app.use(route.get('/', controller.home))
app.use(route.post('/', controller.upload))
app.listen(4290)
Ejemplo n.º 2
0
        formatter: function(options) {
          return moment().format() +' # '+ options.level.toUpperCase() +': '+ (undefined !== options.message ? options.message : '') +
            (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' );
        }
      }
    )
  ]
});

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

app.use(route.get('/', messages.home));
app.use(route.get('/messages', messages.list));
app.use(route.get('/messages/:id', messages.fetch));
app.use(route.post('/messages', messages.create));
app.use(route.get('/async', messages.delay));

// Serve static files
app.use(serve(path.join(__dirname, 'public')));
app.use(serve(path.join(__dirname, '.')));


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

if (!module.parent) {
  app.listen(3000);
  console.log('listening on port 3000');
  winstonLogger.info('listening on port 3000');
}
Ejemplo n.º 3
0
"use strict";

var cortical = module.exports = require("koa")();
var router = require("koa-route");
var parseBody = require("koa-better-body")();

//Configuration bootstrap..
var config = require('./config')();

// HTTP bootstrap..
//middleware..
cortical.use(parseBody);

// routes..
var apihandler = require("./routes/routesApi.js");
cortical.use(router.post("/api/sms_sync/" , apihandler.smsSync));

//Rabbitmq bootstrap..
var ysgMessages = require('./lib/ysg_messages.js');
ysgMessages.startConsumers();

if (module.parent) {
  module.exports = cortical.callback();
} else {
	// start it
	cortical.listen(config.port, function () {
    console.log("The app is started. Listening on port "+ config.port);
	console.log("This is the configuration we're running:");
	console.log(config);
  });
}
Ejemplo n.º 4
0
app.use(route.get('/', function *() {

  this.body = 'Hello, this is a trivial cloudBit Reader App. Nothing else to see here; all the action happens server-side.  To see any recent input activity from webhook-registered cloudBits do this on the command line: `heroku logs --tail`.'

}))



/* On a root POST log info about the (should be) cloudBit event. */

app.use(route.post('/', function *() {

  console.log('received POST: %j', this.request.body)

  if (this.request.body && this.request.body.type) {
    handleCloudbitEvent(this.request.body)
  }

  this.body = 'OK'

}))



app.listen(port)
console.log('App booted on port %d', port)



// Helpers
Ejemplo n.º 5
0
exports.init = function (app) {
  app.use(route.get('/api/posts', listPosts));
  app.use(route.post('/api/posts', createPost));
  app.use(route.post('/api/posts/:postId/comments', createComment));
};
Ejemplo n.º 6
0
// logger

app.use(logger());

// response

app.use(route.get('/randomrun', function* () {
    var datas = addon.randomData(10);
    var path = addon.runMerge();
    console.log(datas);
    console.log(path);
    var point = [];
    this.body = yield render("index", { point: point, path: path });
}));

app.use(route.post('/run', parser()));

app.use(route.post('/run', function* () {
    // console.log(this);
    // data = yield parser(this);
    // console.log("xx");
    console.log(this.request.body);
    var stationList = this.request.body.stationList;
    var distance = this.request.body.distance;
    var depot = this.request.body.depot;
    yield stationDb.insert({ stationList: stationList, depot: depot });
    var tspPath = yield addon.input(stationList.length, 20, stationList, distance);
    var resultPath = [];
    for (var i=1;i<=3;i++)
    {
        var path = yield addon.runAlgorithm(i);
Ejemplo n.º 7
0
export default (queriesFactory, configuredMethods = {}) => {
    const app = new Koa();
    const defaultMethods = {
        GET: 'managed',
        POST: 'managed',
        PUT: 'managed',
        DELETE: 'managed',
    };

    let queries;

    app.use(async (ctx, next) => {
        ctx.availableMethods = Object.assign({}, defaultMethods, configuredMethods);

        await next();
    });

    app.use(async (ctx, next) => {
        queries = queriesFactory(ctx.client);
        await next();
    });

    // GET /
    app.use(koaRoute.get('/', async (ctx, next) => {
        if (ctx.availableMethods.GET) {
            const query = ctx.request.query;
            const excludedQueryParams = ['limit', 'offset', 'filter', '_sort', '_sortDir'];
            const other = {};
            Object.keys(query).forEach(key => {
                if (excludedQueryParams.indexOf(key) !== -1) return;
                other[key] = query[key];
            });

            ctx.body = await queries.selectPage(query.limit, query.offset, query.filter, query._sort, query._sortDir, other); // eslint-disable-line no-underscore-dangle
            const totalCount = (ctx.body[0]) ? ctx.body[0].totalcount : (await queries.countAll());
            ctx.set('X-Total-Count', totalCount);
            ctx.set('Access-Control-Expose-Headers', 'X-Total-Count');
        }

        if (ctx.availableMethods.GET !== 'managed') {
            await next();
        }
    }));

    // GET /:id
    app.use(koaRoute.get('/:id', async (ctx, id, next) => {
        if (ctx.availableMethods.GET) {
            try {
                ctx.body = await queries.selectOne({ id });
            } catch (e) {
                if (e.message === 'not found') {
                    ctx.status = 404;
                } else {
                    throw e;
                }
            }
        }
        if (ctx.availableMethods.GET !== 'managed') {
            await next();
        }
    }));

    // POST /
    app.use(koaRoute.post('/', async (ctx, next) => {
        if (ctx.availableMethods.POST) {
            const data = ctx.data || ctx.request.body;
            ctx.body = await queries.insertOne(data);
        }

        if (ctx.availableMethods.POST !== 'managed') {
            await next();
        }
    }));

    // POST /multi
    app.use(koaRoute.post('/multi', async (ctx, next) => {
        if (ctx.availableMethods.POST) {
            const data = ctx.data || ctx.request.body;
            ctx.body = await queries.batchInsert(data);
        }

        if (ctx.availableMethods.POST !== 'managed') {
            await next();
        }
    }));

    // DELETE /
    app.use(koaRoute.delete('/:id', async (ctx, id, next) => {
        if (ctx.availableMethods.DELETE) {
            try {
                ctx.body = await queries.deleteOne(id);
            } catch (e) {
                if (e.message === 'not found') {
                    ctx.status = 404;
                } else {
                    throw e;
                }
            }
        }

        if (ctx.availableMethods.DELETE !== 'managed') {
            await next();
        }
    }));

    // DELETE /multi
    app.use(koaRoute.delete('/multi', async (ctx, next) => {
        if (ctx.availableMethods.DELETE) {
            const ids = ctx.query.id;
            ctx.body = await queries.batchDelete(ids);
        }
        if (ctx.availableMethods.DELETE !== 'managed') {
            await next();
        }
    }));

    // PUT /:id
    app.use(koaRoute.put('/:id', async (ctx, id, next) => {
        if (ctx.availableMethods.PUT) {
            const data = ctx.data || ctx.request.body;
            let modifiedEntity;
            try {
                modifiedEntity = await queries.updateOne(id, data);
            } catch (e) {
                if (e.message === 'not found') {
                    ctx.status = 404;
                    return;
                }

                throw e;
            }
            ctx.body = modifiedEntity;
        }

        if (ctx.availableMethods.PUT !== 'managed') {
            await next();
        }
    }));

    return app;
};
Ejemplo n.º 8
0
res.buildUserResources = function() {
  /* jshint loopfunc:true */

  var my = this;

  // Build user defined resources
  var keys = Object.keys(this.resources);
  var i = keys.length;

  while (i--) {
    var name = keys[i];
    var currentResource = my.resources[name];

    // List collection options
    this.app.koa.use(route.options('/' + name, this.defineOptions({ allow: ['POST', 'GET']})));

    // List resource options
    this.app.koa.use(route.options('/' + name + '/:label', this.defineOptions({ allow: ['GET', 'PATCH', 'PUT', 'DELETE']})));

    // Create new item
    this.app.koa.use(route.post('/' + name, function *() {

      var record = yield parse.json(this);

      // TODO: we should filter and validate here

      var newDbRecord = yield currentResource.model.create(record);

      // Filter output using filter method
      // TODO: we should avoid aditional db request
      var slectFilter = Object.keys(currentResource.blueprint.schema).join(' ');
      var dbRecord = yield currentResource
                            .model
                              .findOne({'_id': newDbRecord._id}, slectFilter)
                                .exec();
      this.body = dbRecord;
      this.response.status = 201;
    }));

    // List all items
    this.app.koa.use(route.get('/' + name, function *() {
      var slectFilter = Object.keys(currentResource.blueprint.schema).join(' ');
      var dbRecords = yield currentResource
                              .model
                                .find({}, slectFilter).exec();
      this.body = dbRecords;
    }));

    // Show one item
    this.app.koa.use(route.get('/' + name + '/:label', function *( label ) {
      var slectFilter = Object.keys(currentResource.blueprint.schema).join(' ');
      var dbRecord = yield currentResource
                            .model
                              .findOne({label: label}, slectFilter).exec();
      this.body = dbRecord;
    }));

    // Update one item using partial/full data
    this.app.koa.use(route.patch('/' + name + '/:label', function *( label ) {
      var record = yield parse.json(this);
      var dbRecord = yield currentResource
                            .model
                              .update({label: label}, record).exec();
      this.response.status = 204;
    }));

    // Update/Create one item using full data which replace original
    this.app.koa.use(route.put('/' + name + '/:label', function *( label ) {
      var record = yield parse.json(this);

      // Replace resource with new data
      var newRecord = {};
      var schemaAttrsKeys = Object.keys(currentResource.blueprint.schema);
      var schemaAttrsLength = schemaAttrsKeys.length;

      while ( schemaAttrsLength-- ) {
        var schemaAttrName = schemaAttrsKeys[schemaAttrsLength];
        newRecord[schemaAttrName] = record[schemaAttrName];
      }

      var dbRecord = yield currentResource
                            .model
                              .update({label: label}, newRecord, {upsert: true}).exec();
      this.response.status = 204;
    }));

    // Delete one item
    this.app.koa.use(route.delete('/' + name + '/:label', function *( label ) {
      var dbRecord = yield currentResource
                            .model
                              .findOne({label: label}).remove().exec();
      this.response.status = 204;
    }));

    debug('Building routes for '+ name);
  }

};
Ejemplo n.º 9
0
exports.init = function (app) {
  app.use(route.post('/api/debug/flushDatabase', flushDatabase));
};
Ejemplo n.º 10
0
const Koa = require('koa');
const route = require('koa-route');

const { resetPassword, getToken, getUser, acceptTerms } = require('./auth');

const app = new Koa();

app.use(route.get('/', getUser));
app.use(route.get('/token', getToken));
app.use(route.post('/terms/accept', acceptTerms));
app.use(route.put('/password/reset', resetPassword));

module.exports = app;
Ejemplo n.º 11
0
const _ = require('koa-route');
const bodyParser = require('koa-bodyparser');
const cors = require('./cors');
const serverless = require('serverless-http');

require('./zotero');
const Debug = require('./debug');
var Translators; // Translators module is cashed
const SearchEndpoint = require('./searchEndpoint');
const WebEndpoint = require('./webEndpoint');
const ExportEndpoint = require('./exportEndpoint');

const app = module.exports = new Koa();
app.use(cors);
app.use(bodyParser({enableTypes: ['text', 'json']}));
app.use(_.post('/web', WebEndpoint.handle.bind(WebEndpoint)));
app.use(_.post('/search', SearchEndpoint.handle.bind(SearchEndpoint)));
app.use(_.post('/export', ExportEndpoint.handle.bind(ExportEndpoint)));

Debug.init(1);

module.exports.handler = async function (event, context) {
	if (!Translators) {
		Translators = require('./translators');
		await Translators.init();
	}
	
	return await new Promise(function (resolve, reject) {
		serverless(app)(event, context, function (err, res) {
			if (err) return reject(err);
			resolve(res);
Ejemplo n.º 12
0
var _ = require('koa-route');
var koa = require('koa');
var app = koa();

var attendees = require('./');

app.use(_.get('/attendees', attendees.list));
app.use(_.get('/attendees/:id', attendees.index));
app.use(_.post('/attendees', attendees.create));
app.use(_.put('/attendees/:id', attendees.update));

app.listen(3000);

console.log('Listening on port 3000.');
console.log('Inital database:', JSON.stringify(
  attendees.db(process.argv[2] === '-v'), null, '  '
));
Ejemplo n.º 13
0
import db from '../../../db/db'
import {json} from 'co-body'
import route from 'koa-route'
import shortid from 'shortid'
import slug from 'to-slug-case'

export default route.post('/api/project/:projectId/member', function * (projectId) {
  const member = yield json(this)
  member.slug = `${slug(member.name)}-${shortid.generate()}`
  member.expenses = []
  yield db.upsert(projectId, project => {
    project.members.push(member)
    return project
  })
  this.response.status = 201
  this.response.type = 'json'
  this.body = JSON.stringify(member)
})
// @flow
import * as route from "koa-route";

const getData = async (param: string) => Promise.resolve({ foo: param });

const getter = route.get("/login");
getter((ctx, next) => {
  ctx.body = { status: "OK" };
  next();
});

route.put("/api/:param", async (ctx, param, next) => {
  const data = await getData(param);
  ctx.body = { status: "OK", ...data };
  next();
});

route.post(/public/g, () => {});
route.all("creator");
// $ExpectError
route.all({});
Ejemplo n.º 15
0
//controllers
const devices = require('./controllers/devices')
	.attachDatabase(database);
const hubs = require('./controllers/hubs')
	.attachDatabase(database);
const emulator = require('./controllers/emulator');
const upnp = require('./controllers/upnp');

app.use(addTrailingSlashes());
app.use(koaBodyParser());

// serve files in public folder (css, js etc)
app.use(koaStatic(__dirname + '/build/client'));

// user interface to modify devices stored internally
app.use(route.post('/local-api/devices', devices.create));
app.use(route.get('/local-api/devices', devices.find));
app.use(route.put('/local-api/devices/:lightId', devices.update));
app.use(route.del('/local-api/devices/:lightId', devices.remove));
app.use(route.get('/local-api/devices/:lightId', devices.find));

app.use(route.post('/local-api/hubs', hubs.create));
app.use(route.get('/local-api/hubs', hubs.find));
app.use(route.get('/local-api/hubs/:hubName/:deviceId/:state', hubs.actions));
app.use(route.put('/local-api/hubs/:hubId', hubs.update));
app.use(route.del('/local-api/hubs/:hubId', hubs.remove));
app.use(route.get('/local-api/hubs/:hubId', hubs.find));


// emulate the Hue Hub
app.use(route.post('/(.*)', emulator.postwildcard));
Ejemplo n.º 16
0
var request = require('supertest');
var should = require('should');
var route = require('koa-route');
var range = require('../');
var Koa = require('koa');
var app = new Koa();

var rawbody = new Buffer(1024);
var rawFileBuffer = fs.readFileSync('./README.md') + '';

app.use(range);
app.use(route.get('/', async function(ctx) {
  ctx.body = rawbody;
}));
app.use(route.post('/', async function(ctx) {
  ctx.status = 200;
}));
app.use(route.get('/json', async function(ctx) {
  ctx.body = {foo:'bar'};
}));
app.use(route.get('/string', async function(ctx) {
  ctx.body = 'koa-range';
}));
app.use(route.get('/stream', async function(ctx) {
  ctx.body = fs.createReadStream('./README.md');
}));
app.use(route.get('/empty', async function(ctx) {
  ctx.body = undefined;
  ctx.status = 304;
}));
Ejemplo n.º 17
0
const staticCache = require('koa-static-cache')
app.use(staticCache(path.join(__dirname, '/static'), {
    maxAge: 365 * 24 * 60 * 60
}))

// Both routing sections below will call a function and use one `.use` for all routes of that type.
// That will keep the stack smaller.

// REST and Website Routes
app.use(route.get('/', function* () {
    this.body = yield render('page/home.html')
}))

// REST and Website Routes
app.use(route.post('/test', function* () {
    this.body = yield render('page/home.html')
}))


// WebSocket Routes
app.ws.use(route.all('/good', function* (next) {
    // `this` is the regular koa context created from the `ws` onConnection `socket.upgradeReq` object.
    // the websocket is added to the context on `this.websocket`.
    this.websocket.send('Good')
    this.websocket.on('message', function(message) {
        // do something with the message from client
        console.log(message)
    });
    // yielding `next` will pass the context (this) on to the next ws middleware
    yield next
}))
Ejemplo n.º 18
0
app.use(serve('.'));
app.use(favicon('/public/img/favicon.ico'));
app.use(parser({
  strict: false,
}));
app.use( function *(next) {
  this.render = views('views', {
    map: { html: 'swig' },
  });
  yield next;
});
app.use(route.get('/', index));
app.use(route.get('/favicon.ico', null));
app.use(route.get('/:id', show));
app.use(route.post('/send', send))


function *send() {
  var htmlStr = this.request.body.html;
  // json = JSON.parse(json);
  // var result = compute.getField(json);
  // this.response.body = result;
}

function *index() {
  this.body = yield this.render('index');
}

function *show(id) {
  this.body = yield this.render(id)
Ejemplo n.º 19
0
/*
app.use(statCache(path.join(__dirname, 'web'),{
  maxAge:365*24*60*60
}));
*/
/*
app.use(stat(__dirname + '/web/css'));

app.use(stat(__dirname + '/web/js'));
*/

app.use(route.get('/', list));
app.use(route.get('/post/new', add));
app.use(route.get('/post/:id', show));
app.use(route.post('/post', create));


// route definitions

/**
 * Post listing.
 */

function *list() {
  this.body = yield render('list', { posts: posts });
}

/**
 * Show creation form.
 */
Ejemplo n.º 20
0
const Koa = require('koa');
const route = require('koa-route');
const jwt = require('koa-jwt');

const { auth } = require('config');
const { list, refresh } = require('./actions');

const app = new Koa();

app.use(route.get('/', list));

app.use(jwt({ secret: auth.secret, cookie: auth.cookie }));

app.use(route.post('/refresh', refresh));

module.exports = app;
import crypto from 'crypto';
import coBody from 'co-body';
import config from 'config';
import jwt from 'jsonwebtoken';
import koa from 'koa';
import koaRoute from 'koa-route';
import methodFilter from '../lib/middlewares/methodFilter';
import rateLimiter from '../lib/rateLimiter';
import userRepositoryFactory from '../users/userModel';

const app = koa();

app.use(methodFilter(['POST']));
app.use(koaRoute.post('/', rateLimiter(config.apps.api.security.rateLimitOptions.auth)));

app.use(koaRoute.post('/', function* login() {
    const { email, password } = yield coBody(this);
    const userRepository = userRepositoryFactory(this.client);
    const user = yield userRepository.authenticate(email, password);
    if (!user) {
        this.throw('Invalid credentials.', 401);
    }

    const token = jwt.sign(user, config.apps.api.security.jwt.privateKey);
    const cookieToken = crypto.createHmac('sha256', config.apps.api.security.secret)
        .update(token)
        .digest('hex');
    const delay = config.apps.api.security.expirationTokenDelay * 1000;
    const tokenExpires = (new Date((new Date()).getTime() + delay));

    this.cookies.set('token', cookieToken, {
Ejemplo n.º 22
0
var koa = require("koa");
var app = module.exports = koa();
var routes = require("koa-route");

// routes
var userRoutes = require("./userRoutes.js");
app.use(routes.post("/user", userRoutes.addUser));
app.use(routes.get("/user/:id", userRoutes.getUser));
app.use(routes.put("/user/:id", userRoutes.updateUser));
app.use(routes.del("/user/:id", userRoutes.deleteUser));

app.listen(3000);
console.log("The app is listening. Port 3000");
Ejemplo n.º 23
0
, app = module.exports = new koa()
, monk = require('monk')
, wrap = require('co-monk')
, db = monk('localhost/company')
, contacts = wrap(db.get('contacts'));

app.use(cors());

// Load Frontend
app.use(serve('.'));
app.use(serve(__dirname + '/view'));
app.use(serve(__dirname + '/public'));

// Routes
app.use(route.get('/contact/all', list));
app.use(route.post('/contact/edit/:first', show));
app.use(route.post('/contact/save', save));

// Handlers
function *list() {
    var res = yield contacts.find({});
    this.body = res;
}

function *show(title) {
    title = decodeURI(title);
    var res = yield contacts.find({title: title});
    this.body = res;
}

function *save(res) {
Ejemplo n.º 24
0
var compress = require('koa-compress');
var logger = require('koa-logger');
var serve = require('koa-static');
var route = require('koa-route');
var koa = require('koa');
var path = require('path');
var app = module.exports = koa();
var messages = require('./controllers/messages');
var mailer = require('./controllers/mailer');
var comment = require('./controllers/comment');

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

app.use(route.get('/', messages.home));
app.use(route.post('/getPlant', messages.getPlant)); // 获取植物信息
app.use(route.post('/sendCard', mailer.sendCard)); // 发送电子贺卡
app.use(route.get('/getComment', comment.getComment)); // 获取评论
app.use(route.post('/sendComment', comment.sendComment)); // 发送评论

// 无用的测试页面
app.use(route.get('/test', messages.test));


// Serve static files
app.use(serve(path.join(__dirname, 'public/')));

// 跨域 options 确认
app.use(function * (next){
  this.response.set({
      "Access-Control-Allow-Origin": "*"
Ejemplo n.º 25
0
module.exports = function(adapter) {

  var app = koa();

  app.use(function *(next) {
    try {
      yield next;
    } catch (error) {
      debug(error);
      this.status = error.status;
      this.body = yield render('login', {
        error: error.message,
        login: this.login,
        basedir: './views'
      });
    }
  });

  app.keys = ['a'];
  app.use(session());
  app.use(bodyParser());

  app.use(route.get('/login', login));
  var composedLogin = compose([
    validateInput,
    findUser,
    validateUser,
    validatePassword,
    success,
    twoFactor
  ]);
  app.use(route.post('/login', composedLogin));
  app.use(route.post('/login/two-factor-auth', twoFactorAuth));
  app.use(route.get('/logout', logout));



  /**
   * GET /login
   */
  function *login() {
    this.body = yield render('login', {
      basedir: './views'
    });
  }



  /**
   * POST /login
   *
   * Validate form input fields.
   */
  function *validateInput(next) {
    this.login = this.request.body.login;
    this.password = this.request.body.password;
    if (this.login && this.password) return yield next;
    debug('invalid input: login "%s", password "%s"', this.login, this.password);
    this.throw(400, MESSAGE_EMPTY);
  }



  /**
   * POST /login
   *
   * Find user in database.
   */
  function *findUser(next) {
    try {
      var query = EMAIL_REGEXP.test(this.login) ? 'email' : 'name';
      this.user = yield adapter.find(query, this.login);
      yield next;
    } catch(error) {
      debug(error);
      this.throw(403, MESSAGE_INVALID);
    }
  }



  /**
   * POST /login
   *
   * Validate user.
   */
  function *validateUser(next) {
    if (this.user.emailVerified) return yield next;
    debug('email not verified');
    this.throw(403, MESSAGE_INVALID);
  }



  /**
   * POST /login
   *
   * Validate password.
   */
  function *validatePassword(next) {
    var encrypt = thunkify(pwd.hash);
    var hash = yield encrypt(this.password, this.user.salt);
    if (hash === this.user.derived_key) return yield next;
    debug('invalid password');
    this.throw(403, MESSAGE_INVALID);
  }



  /**
   * POST /login
   *
   * Send success message if no two-factor auth.
   */
  function *success(next) {
    this.session.email = this.user.email;
    this.session.name = this.user.name;
    if (this.user.twoFactorAuth) return yield next;
    this.session.loggedIn = true;
    var target = this.session.redirect ? this.session.redirect : '/';
    this.session.redirect = null;
    this.redirect(target);
  }



  /**
   * POST /login
   *
   * Render two-factor authentication view.
   */
  function *twoFactor() {
    this.body = yield render('two-factor', {
      basedir: './views',
      action: '/login/two-factor-auth'
    });
  }



  /**
   * POST /login/two-factor-auth
   *
   * Handle two-factor authentication.
   */
  function *twoFactorAuth() {
    var token = this.request.body.token;
    var user = yield adapter.find('name', this.session.name);
    var key = user && user.twoFactorAuthKey;
    var valid = utils.verify(token, key);
    if (!valid) {
      debug('two-factor auth token invalid');
      this.session = null;
      return this.redirect('/login');
    }
    this.session.loggedIn = true;
    var target = this.session.redirect ? this.session.redirect : '/';
    this.session.redirect = null;
    this.redirect(target);
  }



  /**
   * GET /logout
   */
  function *logout() {
    this.session = null;
    this.body = yield render('logout', {
      basedir: './views'
    });
  }

  return app;

};
Ejemplo n.º 26
0
 * Created on 15.10.14.
 */
var koa = require('koa');
var route = require('koa-route');
var logger = require('koa-logger');
var formidable = require('koa-formidable');

var mongoose = require('./mongoose');
var User = require('./user');

var app = module.exports = koa();

app.use(logger());
app.use(formidable());
app.use(route.get('/user/:id', sendUser));
app.use(route.post('/user', addUser));
app.use(route.del('/user/:id', deleteUser));

function *addUser() {
	var str = JSON.stringify(this.request.body);
	str = str.substring(2, str.length-5);
	str = str.replace(/\\/g, '');
	var user = new User(JSON.parse(str));

	this.body = yield function(callback) {
		user.save(callback);
	}
}

function *sendUser(id) {
	this.body = yield User.find({name:id}).exec();
Ejemplo n.º 27
0

const app         = new Koa();
const httpServer  = http.Server(app.callback());
const sockServer  = IO(httpServer);


// CAUTION: Storing sockets in memory may make it harder to scale our app
const socketsById = {};
const iceTransactions = {};



app.use(koaRoute.post('/emit/:room/:event/:msg?', function*(room, event, msg) {
  console.log('emit:', room, event, msg);
  sockServer.in(room).emit(event, msg);
  this.response.status = 202;
}));


app.use(koaStatic('build'));




// When a socket joins, register the event handlers on it.
sockServer.on('connection', (socket) => {

  // keep track of our active sockets in memory
  socketsById[socket.id] = socket;
  socket.on('disconnect', () => {