ctx.passport在使用koa使用护照时尝试生成jsonwebtoken时未定义?

时间:2017-07-04 10:28:38

标签: node.js jwt passport.js koa2

我正在尝试使用Koa 2和护照创建一个简单的用户注册/登录api。

尝试登录时出现问题。

以下是路线的代码;

import {
    authEmail,
    generateToken
} from '../../auth';

import User from '../../models/user';

export default (router) => {
    router.post('/auth/email', authEmail(), generateToken());
    router.post('/auth/register', register, generateToken());
};

async function register(ctx, next) {
    const { name, email, password } = ctx.request.body;

    // TODO - improve validation
    if (name && email && password) {
        let user = await User.findOne({ email });

        if (!user) {
            user = new User({
                name,
                email
            });
            user.password = user.generateHash(password);
            await user.save();

            ctx.passport = {
                user: user._id,
            };

            console.log(ctx.passport)

            await next();

        } else {
            ctx.status = 400;
            ctx.body = { status: 'error', message: 'E-mail already registered' };
        }
    } else {
        ctx.status = 400;
        ctx.body = { status: 'error', message: 'Invalid email or password' };
    }
}

这是authEmail()+ GenerateToken函数;

export function authEmail() {
    return passport.authenticate('email');
}

/** After autentication using one of the strategies, generate a JWT token */
export function generateToken() {
    return async ctx => {
        console.log('generating token....')
        console.log(ctx.passport)
        const { user } = ctx.passport;
        if (user === false) {
            ctx.status = 401;
        } else {
            const _token = jwt.sign({id: user}, config.secret);
            const token = `JWT ${_token}`;

            const currentUser = await User.findOne({_id: user});

            ctx.status = 200;
            ctx.body = {
                token,
                user: currentUser,
            };
        }
    };
}

最后是护照电子邮件策略:

import User from '../../models/user';
import { Strategy as CustomStrategy } from 'passport-custom';

export default new CustomStrategy(async(ctx, done) => {
    console.log('Email Strategy: ', ctx.body);
    try {
        /** Test whether is a login using email and password */
        if (ctx.body.email && ctx.body.password) {
            const user = await User.findOne({ email: ctx.body.email.toLowerCase() });

            if (!user) { done(null, false, {'message': 'User not found.'}); }
            const password = ctx.body.password;
            if (!user.validPassword(password))
                return done(null, false, {'message': 'Password not correct.'});

            done(null, user);

        } else {
            done(null, false, {'message': 'Email and Password are required.'});
        }
    } catch (error) {
        done(error);
    }
});

尝试向/auth/email发送帖子请求时,我收到以下错误;

  

生成令牌....
undefined
xxx POST / api / auth / email 500 124ms
  TypeError:无法读取未定义的属性“user”...

这是我第一次使用koa和护照,所以我一直在努力清理我找到的github回购。 (https://github.com/zombiQWERTY/koa2-starter-kit),代码大部分都是从这里改编的。

非常感谢任何有关问题的建议,如果您需要更多信息/希望我分享服务器代码的更多部分,请告诉我们。

编辑:

这是堆栈跟踪:

   TypeError: Cannot read property 'user' of undefined
      at _callee2$ (C:\api/app/auth/index.js:45:12)
      at tryCatch (C:\api\node_modules\regenerator-runtime\runtime.js:65:40)
      at Generator.invoke [as _invoke] (C:\api\node_modules\regenerator-runtime\runtime.js:303:22)
      at Generator.prototype.(anonymous function) [as next] (C:\api\node_modules\regenerator-runtime\runtime.js:117:21)
      at step (C:\api\app\auth\index.js:39:191)
      at C:\api\app\auth\index.js:39:437
      at Promise (<anonymous>)
      at C:\api\app\auth\index.js:39:99
      at C:\api/app/auth/index.js:45:5
      at dispatch (C:\api\node_modules\koa-router\node_modules\koa-compose\index.js:44:32)
      at next (C:\api\node_modules\koa-router\node_modules\koa-compose\index.js:45:18)
      at p.then.cont (C:\api\node_modules\koa-passport\lib\framework\koa.js:144:16)
      at <anonymous>
      at process._tickDomainCallback (internal/process/next_tick.js:208:7)

将当前代码上传到repo:https://github.com/alexc101/koa-api

1 个答案:

答案 0 :(得分:3)

根据koa-passport文档,使用v3,您应该将用户保存到ctx.state.user而不是ctx.passport.user

https://github.com/rkusa/koa-passport

我撤下了您的回购并将ctx.passport的所有引用更改为ctx.state,而/email路径现在提供了200。