Koa Authstream动与撰写

在expressjs中我有这个authentication函数。 基本上这只是一个将中间件组合成一个中间件的function。 从现在开始,我想从快递到koa,我怎样在koa做同样的事情呢?

import compose from 'composable-middleware'; export function isAuthenticated() { return compose() // Validate JWT .use(function(req, res, next) { if (req.query && req.query.hasOwnProperty('access_token')) { req.headers.authorization = 'Bearer ' + req.query.access_token; } validateJwt(req, res, next); }) // Attach user to request .use(function(req, res, next) { User.findByIdAsync(req.user._id) .then(user => { if (!user) { return res.status(401).end(); } req.user = user; next(); }) .catch(err => next(err)); }); } 

在这里回答我自己的问题并不困难

 import compose from 'koa-compose'; import convert from 'koa-convert'; import User from '../api/user/user.model'; const validateJwt = convert(koaJwt({ secret: config.secrets_session })); /** * Attaches the user object to the request if authenticated * Otherwise returns 403 */ export function isAuthenticated() { function authentication(ctx, next) { // allow access_token to be passed through query parameter as well if (ctx.query && ctx.query.hasOwnProperty('access_token')) { ctx.headers.authorization = `Bearer ${ctx.query.access_token}`; } validateJwt(ctx, next); } function attachUserToContext(ctx, next) { User.findById(ctx.state.user._id) .then(user => { if (!user) { return ctx.status = 401; } ctx.state.user = user; next(); }) .catch(err => next(err)); } return compose([authentication, attachUserToContext]); }