Sunday, 9 April 2017

ES6 REST API with Mongoose cannot login correctly

I am trying to test authentication of the REST API with a mongoDB using Mongoose ( it works fine with had coded ref users) but I'm not sure I am doing write with my login function in my auth controller

user.model.js

mport ...

const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true
  },
  pwd: {
    type: String,
    required: true
  }
});

UserSchema.method({
});

UserSchema.statics = {
  /**
   * Get user
   * @param {ObjectId} id - The objectId of user.
   * @returns {Promise<User, APIError>}
   */
  get(id) {
    return this.findById(id)
      .exec()
      .then((user) => {
        if (user) {
          return user;
        }
        const err = new APIError('No such user exists!', httpStatus.NOT_FOUND);
        return Promise.reject(err);
      });
  },

  /**
   * List users in descending order of 'createdAt' timestamp.
   * @param {number} skip - Number of users to be skipped.
   * @param {number} limit - Limit number of users to be returned.
   * @returns {Promise<User[]>}
   */
  list({ skip = 0, limit = 50 } = {}) {
    return this.find()
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit)
      .exec();
  }
};
export default mongoose.model('User', UserSchema);

then I have

auth.controller.js

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

function login(req, res, next) {
  User.findOne({ username: req.body.username, password: req.body.password }, (err, user) => {
    if (err) {
      return next(new APIError('Authentication error', httpStatus.UNAUTHORIZED, true));
    }
    const token = jwt.sign({ username: user.username }, config.jwtSecret);
    return res.json({ token, username: user.username });
  });
}

which I am testing with

auth.test.js

 import ...

 describe('## Auth APIs', () => {
   const validUserCredentials = {
     username: 'testUser',
     password: 'testUserPwd'
   };

   let jwtToken;

   describe('# POST /api/v1/auth/login', () => {
     it('should get valid JWT token', (done) => {
       request(app)
         .post('/api/v1/auth/login')
         .send(validUserCredentials)
         .expect(httpStatus.OK)
         .then((res) => {
           expect(res.body).to.have.property('token');
           jwt.verify(res.body.token, config.jwtSecret, (err, decoded) => {
             expect(err).to.not.be.ok; // eslint-disable-line no-unused-expressions
             expect(decoded.username).to.equal(validUserCredentials.username);
             jwtToken = `Bearer ${res.body.token}`;
             done();
           });
         })
         .catch(done);
     });
   });
 });

But my authentification test is failing as I am getting any data from the DB

Uncaught TypeError: Cannot read property 'username' of null

where am I wrong ? thanks for feedback



via erwin

No comments:

Post a Comment