首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有猫鼬的ES6 REST无法正确登录

带有猫鼬的ES6 REST无法正确登录
EN

Stack Overflow用户
提问于 2017-04-09 17:48:13
回答 1查看 160关注 0票数 0

我正在尝试用mongoDB测试REST的身份验证,使用Mongoose (它对已编码的ref用户很好),但我不确定我是否在用我的auth控制器中的登录函数编写

user.model.js

mport ..。

代码语言:javascript
复制
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);

那我就有

auth.controller.js

代码语言:javascript
复制
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 });
  });
}

我正在用它来测试

auth.test.js

代码语言:javascript
复制
 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);
     });
   });
 });

但是我的身份验证测试失败了,因为我正在从DB获得任何数据。

Uncaught :无法读取空的属性“用户名”

我哪里错了?谢谢你的反馈

EN

回答 1

Stack Overflow用户

发布于 2017-04-10 08:13:19

我的auth.controller中的登录函数应该是:

代码语言:javascript
复制
function login(req, res, next) {
  const { username = req.body.username, password = req.body.password} = req.query;
  User.auth({ username, password })
    .then((user) => {
      const token = jwt.sign({ username: user.username }, config.jwtSecret);
      return res.json({ token, username: user.username });
    })
    .catch( () => {
      return next(new APIError('Authentication error', httpStatus.UNAUTHORIZED, true));
    });
}

我应该在我的用户模型中添加一个auth方法。

代码语言:javascript
复制
  auth(username, password) {
    return this.findOne(username, password)
      .exec()
      .then((user) => {
        if (user) {
          return user;
        }
        const err = new APIError('Authentication error', httpStatus.NOT_FOUND);
        return Promise.reject(err);
    });
  },
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43309938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档