Пример #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;
}
Пример #2
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());

};
Пример #3
0
const authMiddleware = app => {
  app.use(async (ctx, next) => {
    ctx.state.clientAuthMethod = determineAuthMethod(ctx);
    await next();
  });

  // Basic auth
  // NOTE: enable once proper sign in has been implemented
  // app.use(async (ctx, next) => {
  //   if (ctx.state.clientAuthMethod === 'basic') {
  //     await basicAuth({
  //       name: 'user',
  //       pass: config.passwords.user,
  //     })(ctx, next);
  //   } else {
  //     await next();
  //   }
  // });

  // JWT auth
  app.use(
    jwt({
      secret: config.JWT_SECRET,
      key: 'auth',
      // Optionally get jwt from cookie, eg. for download links
      // cookie: 'server-template'
    }).unless({
      paths: skipAuthPaths,
      custom() {
        return determineAuthMethod(this) !== 'jwt';
      },
    })
  );

  // Determine user role
  // NOTE: The example supports two hardcoded users ('admin' and 'user')
  // and their username as used also as role name
  app.use(async (ctx, next) => {
    const rolesByAuth = {
      basic: 'user',
      // TODO or ctx.state.auth.role?
      jwt: ctx.state.auth ? ctx.state.auth.sub : null,
    };
    ctx.state.role = rolesByAuth[ctx.state.clientAuthMethod];
    await next();
  });

  // Log minimal user details
  app.use(async (ctx, next) => {
    mergeToLogCtx({
      user: {
        role: ctx.state.role,
      },
    });
    await next();
  });
};
Пример #4
0
function authToken() {
    return compose([
        function *(next) {
            if (this.query && this.query.hasOwnproperty('access_token')) {
                this.headers.authorization = 'Bearer ' + this.query.access_token;
            }
            yield next;
        },
        jwt({secret: config.session.secrets, passthrough: true})
    ])
}
Пример #5
0
module.exports = function (app) {
  // middleware configuration
  if (config.app.env !== 'test') {
    app.use(logger());
  }
  if (config.app.env === 'development') {
    app.use(require('koa-livereload')({excludes: ['/modules']}));
  }
  app.use(cors({
    maxAge: config.app.cacheTime / 1000,
    credentials: true,
    methods: 'GET, HEAD, OPTIONS, PUT, POST, DELETE',
    headers: 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  }));
  app.use(bodyParser());

  // register special controllers which should come before any jwt token check and be publicly accessible
  require('../controllers/public').init(app);
  require('../controllers/login').init(app);

  // serve the static files in the /client directory, use caching only in production (7 days)
  var sendOpts = config.app.env === 'production' ? {root: 'client', maxage: config.app.cacheTime} : {root: 'client'};
  app.use(function *(next) {
    // do not handle /api paths
    if (this.path.substr(0, 5).toLowerCase() === '/api/') {
      yield next;
      return;
    } else if (yield send(this, this.path, sendOpts)) {
      // file exists and request successfully served so do nothing
      return;
    } else if (this.path.indexOf('.') !== -1) {
      // file does not exist so do nothing and koa will return 404 by default
      // we treat any path with a dot '.' in it as a request for a file
      return;
    } else {
      // request is for a subdirectory so treat it as an angular route and serve index.html, letting angular handle the routing properly
      yield send(this, '/index.html', sendOpts);
    }
  });

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

  // mount all the routes defined in the api controllers
  fs.readdirSync('./server/controllers').forEach(function (file) {
    require('../controllers/' + file).init(app);
  });
};
Пример #6
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());
}
Пример #7
0
app.init = co(function *(overwriteDB) {
    // initialize mongodb and populate the database with seed data if empty
    yield mongo.connect();
    yield mongoSeed(overwriteDB);

    // register special controllers which should come before any jwt token check and be publicly accessible
    require('./controllers/public').init(app);
    require('./controllers/login').init(app);

    // serve the static files in the /client directory, use caching only in production (7 days)
    var sendOpts = config.app.env === 'production' ? {root: dist, maxage: config.app.cacheTime} : {root: dist};
    var send = require('koa-file-server')(sendOpts).send;

    app.use(function *(next) {

        // do not handle /api paths
        if (this.path.substr(0, 5).toLowerCase() === '/api/') {
            yield next;
            return;
        } else if (yield send(this, this.path)) {
            // file exists and request successfully served so do nothing
            return;
        } else if (this.path.indexOf('.') !== -1) {
            // file does not exist so do nothing and koa will return 404 by default
            // we treat any path with a dot '.' in it as a request for a file
            return;
        } else {
            yield send(this, 'index.html');
        }
    });

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

    // mount all the routes defined in the api controllers
    fs.readdirSync('./server/controllers').forEach(function (file) {
        require('./controllers/' + file).init(app);
    });

    app.listen(config.app.port);

    console.log('Listening on port: ' + config.app.port);
    console.log('Running app in environment: ' + config.app.env);

});
Пример #8
0
module.exports = function (app) {
  // middleware configuration
  if (config.app.env !== 'test') {
    app.use(logger());
  }
  if (config.app.env === 'development') {
    app.use(require('./koa-livereload')({excludes: ['/partials']}));
  }
  app.use(passport.initialize());
  app.use(passport.session());

  // mount passport oauth routes
  passport.routes(app);

  // register publicly accessible api endpoint. this is useful for special cases like login, user profile images, etc.
  require('../controllers/public').init(app);

  // serve the angular static files from the /client directory, use caching (7 days) only in production
  // if the file is not found and requested path is not /api, serve index.html page and let angular handle routing
  var sendOpts = config.app.env === 'production' ? {root: 'client', maxage: 1000 * 60 * 60 * 24 * 7} : {root: 'client'};
  app.use(function *(next) {
    if (this.path.substr(0, 5).toLowerCase() === '/api/') {
      yield next;
    } else {
      if (yield send(this, this.path, sendOpts)) {
        return;
      }
      yield send(this, '/index.html', sendOpts);
    }
  });

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

  // mount all the routes defined in the api controllers
  fs.readdirSync('./server/controllers').forEach(function (file) {
    require('../controllers/' + file).init(app);
  });
};
Пример #9
0
module.exports = function (app) {
  // middleware configuration
  if (config.app.env !== 'test') {
    app.use(logger());
  }
  if (config.app.env === 'development') {
    app.use(livereload({excludes: ['/modules']}));
  }

  // register special controllers which should come before any jwt token check and be publicly accessible
  require('../controllers/public').init(app);
  require('../controllers/signin').init(app);

  // serve the angular static files from the /client directory
  var sendOpts = {root: 'client', maxage: config.app.cacheTime};
  app.use(function *(next) {
    // skip any route that starts with /api as it doesn't have any static files
    if (this.path.substr(0, 5).toLowerCase() === '/api/') {
      yield next;
      return;
    }
    // if the requested path matched a file and it is served successfully, exit the middleware
    if (yield send(this, this.path, sendOpts)) {
      return;
    }
    // if given path didn't match any file, just let angular handle the routing
    yield send(this, '/index.html', sendOpts);
  });

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

  // mount all the routes defined in the api controllers
  fs.readdirSync('./server/controllers').forEach(function (file) {
    require('../controllers/' + file).init(app);
  });
};
Пример #10
0
'use strict';

var config = require('config-layered')();
var koa = require('koa');
var jwt = require('koa-jwt');
var session = require('koa-session');

var seneca = require('seneca')();
seneca.use('seneca-bluebird');

// start the microservices in-process
var authHandler = require('alt-auth-seneca')(config, seneca);
var userHandler = require('alt-user-seneca')(config, seneca);
var apiKeyHandler = require('./seneca-apiKey')(config, seneca);

var app = koa();
app.keys = config.koa.keys;
app.use(session(app));

app.use(jwt(config.jwt).unless({ path: [/^\/($|public|auth|connect)/] }));

app.use(require('koa-static')('public'));

app.use(authHandler.koa());
app.use(userHandler.koa());

// api key submission routes
// app.use();

require('./auto-serve-ssl')(app.callback(), config);
Пример #11
0
app.use(timingLogger);
app.use(errorHandler);

app.use(bodyParser());
app.use(convert(cors()));

const apiUrl = '/api';

log('config public routes');
const authApi = new Router({prefix: apiUrl})
const userStore = dataStore({filename: '../users.json', autoload: true});
authApi.use('/auth', new AuthRouter({userStore, io}).routes())
app.use(authApi.routes()).use(authApi.allowedMethods())

log('config protected routes');
app.use(convert(koaJwt(jwtConfig)));
const protectedApi = new Router({prefix: apiUrl})
const productStore = dataStore({filename: '../products.json', autoload: true});
const productRouter=new ProductRouter({productStore, io});
protectedApi.use('/product',productRouter.routes())
app.use(protectedApi.routes()).use(protectedApi.allowedMethods());

io.on('connection', socketioJwt.authorize(jwtConfig))
  .on('authenticated', (socket) => {
    const username = socket.decoded_token.username;
    socket.join('${username}');
	productRouter.setSocket(socket);
    log(`${username} authenticated and joined`);
    socket.on('disconnect', () => {
      log(`${username} disconnected`);
    })
Пример #12
0
dotenv.load();

// App configuration
var app = koa();
app.use(cors()); // Enable cross-site data transfer
app.use(bodyparser()); // Enable POST body parsing

// Routes
var ping = require('./routes/ping');
var register = require('./routes/register');

// Validate incoming id_tokens unless they are going through a public directory
var privateKey = new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64');
app.use( 
    jwt({
        secret: privateKey,
        algorithm: 'HS256'
    })
    .unless({path:[/^\/public/]})
);

app.use(routes.get('/public/ping', ping.publicPing));
app.use(routes.get('/ping', ping.privatePing));
app.use(routes.post('/register', register.create));

var port = process.env.PORT || 12001;
app.listen(port);
console.log(`Listening on port: ${port}`)

module.exports = app;
Пример #13
0
    return ctx.throw('Bad auth data', 400);
  }
  let user;
  try {
    user = await db.User.findById(ctx.state.user.id);
    debug('trying to find test-login', user.name);
  }
  catch (err) {
    return ctx.throw('User not found', 404);
  }


  ctx.body = {user: user.email};
}

let jwtMiddleware = convert(koaJwt({ secret: config.secret }))

router.get("/test-login", convert.compose(jwtMiddleware, handleTestLogin));

app.use(router.routes());




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

module.exports = app;



// Auth реализует POST на "/login" , котрый принимает поля {login/email:ddd, password}
Пример #14
0
const jwt = require('koa-jwt');
const jwksRsa = require('../../lib');

const jwksHost = process.env.JWKS_HOST;
const audience = process.env.AUDIENCE;
const issuer = process.env.ISSUER;

// Initialize the app.
const app = new Koa();

app.use(jwt({
  secret: jwksRsa.koaJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 2,
    jwksUri: `${jwksHost}/.well-known/jwks.json`
  }),
  audience,
  issuer,
  algorithms: [ 'RS256' ]
}));

const router = new Router();

router.get('/me', ctx => {
  ctx.body = ctx.state.user
});

app.use(router.middleware());

// Start the server.
Пример #15
0
const configureKoaJwt = ({jwt: {secret: {accessToken}}}) => authorize({
  secret: accessToken,
  cookie: false,
  passthrough: true
})
Пример #16
0
		} else {
			throw e; // Pass the error to the next handler since it wasn't a JWT error.
		}
	}
});

// Public endpoint to login.
app.use(function *(next) {
	if (this.url.match(/^\/login/)) {
		var claims = yield parse(this);
		var token = jwt.sign(claims, privateKey, {algorithm: 'RS256'});
		this.status = 200;
		this.body = {token: token};
	} else {
		yield next;
	}
});

// Everything behind this will be protected.
app.use(jwt({
	secret: publicKey,
	algorithm: 'RS256'
}));

app.use(function *() {
	this.status = 200;
	this.body = 'You are logged in dude! Welcome!';
});

app.listen(3000);
Пример #17
0
const compose = require('koa-compose')
const convert = require('koa-convert')
const jwt = require('koa-jwt')
const constants = require('../constants')

const decodeJwt = convert(jwt({
  secret: constants.SESSION_SECRET,
  passthrough: true
}))

module.exports = compose([decodeJwt])
Пример #18
0
const jwt     = require('koa-jwt')
const compose = require('koa-compose')

const db      = require('../database')
const config  = require('../config')


const jwtMiddleware = jwt({
    secret: config.get('jwt.secret')
})

const checkUser = async (ctx, next) => {
    if (!ctx.state.user.id) {
        ctx.status = 401
        return
    }

    const user = await db.from('users')
        .where('id', ctx.state.user.id)
        .then(([u]) => u)

    if (!user) {
        ctx.status = 401
        return
    }

    ctx.state.user.role = user.role

    await next()
}
Пример #19
0
var app = require('koa')();
var router = require('koa-router')();
var config = require('./config');
var bodyParser = require('koa-bodyparser');
var mongoose = require('mongoose');
var jwt = require('koa-jwt');

mongoose.connect(config.database);

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));

app.use(bodyParser());
require('./routes').register(router);
router.use(jwt({ secret: config.secret }));
require('./routesprotected').register(router);
app.use(router.routes());

if (!module.parent) {
	app.listen(3000);
}

module.exports = app;
Пример #20
0
app.use(convert(WebpackDevMiddleware(compiler, {
  hot: true,
  noInfo: true,
  publicPath: webpackConfig.output.publicPath,
  historyApiFallback: true
})))

app.use(convert(WebpackHotMiddleware(compiler, {
  log: console.log,
  path: '/__webpack_hmr',
  heartbeat: 10 * 1000
})))

app.use(serve(__dirname + '/../public'))
app.use(convert(jwt({
  secret: process.env.JWT_SECRET
}).unless({
  path: [
    '/login',
    '/register',
    '/favicon.ico'
  ]
})))

app.use(logger())
app.use(convert(bodyParser()))
//app.keys = ['some secret hurr']
//app.use(convert(session(app)))

app.use(
  indexRouter.routes(),
/**
 * parse request body into js object
 */
app.use(convert(bodyParser()))

/**
 * connect db
 */
mongoose.connect('127.0.0.1:27017/todosdemo')

/**
 * JWT authentication control
 * all paths protected by default
 */
app.use(convert(koajwt({ secret: JWT_SECRET }).unless({ path: [
  // add unprotected paths here
  // /regex for path/, ...

  /^\/api\/login/,
  /^\/favicon.ico/,
]})))

/**
 * REST routes
 * from routes/index.js
 */
const router = new Router()
routes(router)
app
  .use(router.routes())
Пример #22
0
    const user = await UserModel.findById(ctx.state.jwtdata._id).lean();

    if (!user) throw new HttpError(401, 'User not found by your token ID');

    const logoutedAt = (new Date(user.logoutedAt)).getTime();
    const loggedAt = (new Date(ctx.state.jwtdata.loggedAt)).getTime();

    if (loggedAt < logoutedAt) {
      log.warn(`loggedAt ${loggedAt} < logoutedAt ${logoutedAt}. return 401`);
      throw new HttpError(401, 'User had logged out');
    }

    if (ctx.state.jwtdata.userAgent !== ctx.request.header['user-agent']) {
      log.warn(`user's token userAgent (${ctx.state.jwtdata.userAgent})
        is not equal to request user-agent ${ctx.request.header['user-agent']}. return 401`);
      throw new HttpError(401, 'User had logged out');
    }

    ctx.state.user = user;
  } catch (err) {
    throw err;
  }

  await next();
}

module.exports = compose(
  jwt({ secret: config.secret, key: 'jwtdata' }),
  getUserData
);
Пример #23
0
if (!fs.existsSync(dir)){
  mkdirp.sync(dir);
}


router.use('/api/public', articlesRoute.public.routes(), articlesRoute.public.allowedMethods());
router.use('/api/private', articlesRoute.private.routes(), articlesRoute.private.allowedMethods());
router.use('/api/public', authRoute.public.routes(), authRoute.public.allowedMethods());

app
  .use(logger())
  .use(cors())
  .use(bodyParser())
  .use(serve(staticPath))
  //dont use jwt on public api and files that need to be downloaded from amazon
  .use(jwt({ secret: process.env.SECRET_JWT }).unless({ path: [/^(?!\/api\/private)/] }))
  .use(router.routes())
  .use(router.allowedMethods())
  .use(function *(next) {
    if(this.url.startsWith('/api')) {
      this.status = 404;
    }
    else if(this.url.endsWith('.png')) {
      const regex = /^(.*)\/(.*[^\/])$/;
      const match = regex.exec(this.url);
      const basepath = match[1];
      const filename = match[2];
      console.log('Hello', basepath, filename)

      const params = {Key: filename};
      const file = fs.createWriteStream(`${staticPath}/${basepath}/${filename}`);
Пример #24
0
import { rope } from './utils/db'
import { log } from './utils'
import frontRouter from './routes/front'
import Config from './utils/config'

const router = new Router()
const app = new Koa()

// Loads .env and puts variables into process.env
const envFile = new Config()

app.use(compress())

router.use('/api', convert(jwt({
  secret: process.env.SESSION_SECRET
}).unless({
  path: [/token-auth/, /token-refresh/, /reset-password/]
})))

router.use(convert(bodyParser({
  multipart: true
})))

// Retrieve routes from passed path
const getRouter = (path) => require('./routes/' + path)

const APIroutes = [
  'content',
  'reset-password',
  'token',
Пример #25
0
  } catch(err) {
    this.set( "Access-Control-Allow-Origin", "*");
    this.set("Access-Control-Allow-Credentials", "true");
    this.set("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT");
    this.set("Access-Control-Allow-Headers", "Authorization,Content-Type,Accept");
    this.status = err.status || 500;
    this.body = err.message;
    this.set("Content-Type","application/json");
  }
 

});



app.use(jwt({ secret: secret, key: 'user' }).unless({ path: [/^\/public/, '/'] }));


app
  .use(fishcatchroutes.routes())
  .use(fishcatchroutes.allowedMethods())

app
  .use(userroutes.routes())
  .use(userroutes.allowedMethods())

app
  .use(lakeroutes.routes())
  .use(lakeroutes.allowedMethods())

app.listen(port);
Пример #26
0
  try {
    await next()
  } catch (err) {
    if (err.status === 401) {
      ctx.status = 401
      ctx.body = {
        success: false,
        token: null,
        info: 'Protected resource, use Authorization header to get access'
      }
    } else {
      throw err
    }
  }
})

app.on('error', function (err, ctx) {
  console.log('server error', err)
})

router.use('/auth', auth.routes()) // 挂载到koa-router上,同时会让所有的auth的请求路径前面加上'/auth'的请求路径。
router.use('/api', jwt({secret: 'vue-koa-demo'}), api.routes()) // 所有走/api/打头的请求都需要经过jwt验证。

app.use(router.routes()) // 将路由规则挂载到Koa上。
app.use(historyApiFallback())
app.use(serve(path.resolve('dist'))) // 将webpack打包好的项目目录作为Koa静态文件服务的目录

export default app.listen(port, () => {
  console.log(`Koa is listening in ${port}`)
})
Пример #27
0
module.exports = function (app) {
	// middleware configuration
	app.use(cors({
		maxAge: config.app.cacheTime / 1000,
		credentials: true,
		methods: 'GET, HEAD, OPTIONS, PUT, POST, DELETE',
		headers: 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
	}));

	app.use( function * ( next ) {
		this.req.connection.setTimeout( 0 );
		this.req.connection.setNoDelay( true );
		try {
			yield next;
		} catch( err ) {
			l.error( "Err in processing req ", err );
		}
	});

	app.use(responseTime());
	app.use(compress({
		filter: function (content_type) {
			return /application\/json/i.test(content_type);
		}, threshold: 250
	}));

	let pubRouter = route();
	var secRouter = route();
	fs.readdirSync('./server/controllers').forEach( function (file) {
		let controller = require('../controllers/' + file);

		if( controller.initPub )
			controller.initPub( pubRouter );
		if( controller.initSecured )
			controller.initSecured( secRouter );
	});

	app.use(parse({multipart: true,formidable: {uploadDir: config.app.uploadDir}}));
	app.use( function*( next ) {
		this.log = l;
		l.debug("got req ", this.request);
		yield next;
	});
	app.use(function*(next){
		if(!(/\/v\d+\//i.test(this.request.url)))
			yield send(this, this.path, {root: config.app.root});
		else {
			this.log.debug('JSON api request');
			yield next;
		}
	});
	app.use( pubRouter.routes() );
	app.use( function * ( next ) {
		if( pubRouter.match( this.path, this.method ).pathAndMethod.length )// if already routed, return;
		  return;
		yield next;
	});
	app.use( jwt( { secret : config.app.privateKey, algorithms : [ 'HS256' ] } ) );

	app.use( function*(next) {
		let User = require( 'mongoose' ).model( 'User' );
		let id = this.state.user._id;

		this.passport = {};
		this.passport.user = yield User.findById(id)
			.populate({path:'localities', select:'name users location'})
			.populate({path:'settings', select:'privacy notifications neighbors'})
			.select('-gcmTokens -resetToken -resetTokenExpiry -resetTokenValidated')
			.exec();

		if(!this.passport.user)	{
			this.status = 401;
			return;
		}
		yield next;
	});

	app.use(function * (next){
		let reqId = ++reqCount;

		l.debug({reqId: reqId, req: this.request, body: this.request.body});

		this.log = l.child({reqId: reqId, user: this.passport.user});
		yield next;

		let body = (this.response.header['content-type'] !== 'application/octet-stream')? this.body : "Byte stream";

		l.debug({reqId: reqId, res: this.response});
	});
	app.use(secRouter.routes());
};
Пример #28
0
                this.body = err.message;
                break;
            case 401:
                this.status = 401;
                this.body = err.message;
                break;
            case 400:
                this.status = 400;
                this.body = err.message;
                break;
            case 403:
                this.status = 403;
                this.body = err.message;
                break;
            case 500:
                this.status = 500;
                this.body = err.message;
                break;
        }
    }
});

app.use(jwt({ secret : process.env.APP_JWT_SECRET , passthrough: true}));

app.use(mount(api));


app.listen(4567);
console.log('listening on port 4567');

exports.app = app;
Пример #29
0
const jwt             = require('koa-jwt');
const cors            = require('koa-cors');
const errorMiddleware = require('./middleware/error-middleware');

app.use(koaBody({
    fieldsKey: false,
    filesKey: false,
    multipart: true
}));

// allow cors for now
app.use(cors());

// add error middleware
app.use(errorMiddleware());

// load all routes
require('./routes/public')(app);

// Middleware below this line is only reached if JWT token is valid
app.use(jwt({ secret: config.secretKey }));

// Protected middleware
require('./routes/protected')(app);

app.on('error', err => {
    logger.error(err).catch(err => console.error(err)); // eslint-disable-line
});

app.listen(config.port, () => console.log(`local api:${config.port} - ${process.env.NODE_ENV}`)); // eslint-disable-line
Пример #30
0
app.use((ctx, next) => {
	return next().catch(err => {
		if (401 == err.status) {
			ctx.status = 401;
			ctx.body = '401 Unauthorized - Protected resource, use Authorization header to get access\n';
		} else {
			throw err;
		}
	});
});

// Unprotected middleware
app.use((ctx, next) => {
	if (ctx.url.match(/^\/public/)) {
		ctx.body = 'unprotected\n';
	} else {
		return next();
	}
});

// Middleware below this line is only reached if JWT token is valid
app.use(koajwt({ secret: secretCode }));

app.use(ctx => {
	if (ctx.url.match(/^\/api/)) {
		ctx.body = 'protected\n';
	}
});

app.listen(3000);