2017-04-09 19 views
0

我想用mongoDB使用Mongoose來測試REST API的身份驗證(它可以正常編碼ref用戶),但我不確定我是在用我的登錄函數在我的身份驗證控制器ES6 REST API與Mongoose無法正確登錄

user.model.js

M端口...

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

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

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 TypeError:無法讀取屬性'用戶名'null

我在哪裏錯了?感謝您的反饋

+0

有三個'username'特性,這種特性引起它:'req.body.username','user.username'或'decoded.username'。哪一個導致錯誤? – robertklep

+0

感謝您的反饋...我發現這個問題,它與Promise用法相關聯 我的登錄函數寫錯了... – erwin

回答

0

我auth.controller登錄功能應該是:

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方法

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

FWIW,User.auth()的參數與您在內部調用它的方式不匹配登錄功能:)此外,而不是返回一個被拒絕的承諾,你可以'扔err'。 – robertklep

+0

謝謝..我確實注意到它afterfter .. – erwin