2016-02-23 3 views
2

У меня есть функция isAuthenticated in expressjs. В основном это просто функция, которая объединяет прямое промежуточное ПО в одно промежуточное ПО. С каких пор я хочу перейти из экспресса в koa, как мне сделать то же самое в koa?Koa Auth flow with compose

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)); 
    }); 
} 

ответ

1

Отвечая на мой собственный вопрос здесь, оказывается, не так уж трудно

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]); 
}