我正在尝试用mongoDB测试REST的身份验证,使用Mongoose (它对已编码的ref用户很好),但我不确定我是否在用我的auth控制器中的登录函数编写
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);那我就有
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 :无法读取空的属性“用户名”
我哪里错了?谢谢你的反馈
发布于 2017-04-10 08:13:19
我的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);
});
},https://stackoverflow.com/questions/43309938
复制相似问题