Search code examples
node.jsjwtpassport.jskoa2

ctx.passport undefined when trying to generate a jsonwebtoken when using passport with koa?


I'm trying to create a simple user register/login api using Koa 2 and passport.

The trouble comes when trying to login.

Here is the code for the route;

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

Here is the authEmail() + GenerateToken functions;

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

and finally the passport email strategy:

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

When trying to run a post request to /auth/email I get the following error;

generating token....
undefined
xxx POST /api/auth/email 500 124ms
TypeError: Cannot read property 'user' of undefined...

This is the first time I'm using koa and passport, so I've been trying to clean up a github repo I found. (https://github.com/zombiQWERTY/koa2-starter-kit) and the code is mostly adapted from here.

Any advice on what the problem could be is much appreciated, and if you need any more information / want me to share more parts of the server code please let me know.


EDIT:

Here is the stack trace:

   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)

Uploaded current code to repo: https://github.com/alexc101/koa-api


Solution

  • According to the koa-passport docs, with v3, you should be saving your user to ctx.state.user instead of ctx.passport.user.

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

    I pulled down your repo and changed all references of ctx.passport to ctx.state and the /email route gives a 200 now.