gpt4 book ai didi

javascript - Koa Auth 流程与 compose

转载 作者:行者123 更新时间:2023-11-30 00:13:26 25 4
gpt4 key购买 nike

我在 expressjs 中有这个 isAuthenticated 函数。基本上它只是一个将 express 中间件组合成一个中间件的功能。现在我想从 express 迁移到 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]);
}

关于javascript - Koa Auth 流程与 compose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35588868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com