【发布时间】:2019-07-23 19:20:02
【问题描述】:
我有一个 Node/Express API 为 Vue 前端提供数据,现在我正在添加 Passport 以进行身份验证和授权。我有一个 createUser 函数,它成功添加了用户,但是这样做时函数挂起。我确定这只是我错过的一件愚蠢的事情,比如不打电话给next()(虽然我这样做了),我会很感激有头脑更清晰的人看看。
//authRoutes.js
const router = require('express').Router();
const { createUser } = require('../controllers/authController');
router.route('/auth/register').post(createUser);
module.exports = router;
//authController.js
'use strict';
const authHelpers = require('../auth/_helpers');
const passport = require('../auth/local');
const handleResponse = (res, code, statusMsg) => {
res.status(code).json({ status: statusMsg });
};
const createUser = (req, res, next) => {
// passes correct user and pass
console.log(req.body);
return authHelpers
.createUser(req, res, next)
.then(() => {
passport.authenticate('local', (err, user, info) => {
if (err) {
handleResponse(res, 500, 'error');
console.log(info);
}
if (user) {
handleResponse(res, 200, 'success');
console.log(info);
}
})(req, res, next);
})
.catch(next);
};
module.exports = {
createUser,
};
//auth/_helpers.js
const bcrypt = require('bcryptjs');
const knex = require('../db/connection');
const comparePass = (userPassword, databasePassword) =>
bcrypt.compareSync(userPassword, databasePassword);
const createUser = req => {
const salt = bcrypt.genSaltSync();
const hash = bcrypt.hashSync(req.body.password, salt);
return knex('users')
.insert({
email: req.body.email,
password: hash,
})
.returning('*');
};
module.exports = {
comparePass,
createUser,
};
编辑 1:
根据@cantuket 的建议,记录 createUser 返回的内容会生成用户对象,该对象会正确插入数据库:
//console.log('res: ', 结果)
{ id: 30,
email: 'boooya@dubay.com',
password:
'$2a$10$WNX.9ur7PlS9ZZvZlJk9Tu9j3lWMjaTlUQ1v7i84dqgHscDupIowW',
admin: false,
created_at: 2019-03-01T18:22:53.120Z,
updated_at: 2019-03-01T18:22:53.120Z,
last_login: null }
```
EDIT 2:
Thanks to [@cantuket][1] for reminding me to get dirty with console logs, I figured it out by switching 'user' with the returned value (here response), and returning nexts. See below for the fix that worked:
const createUser = (req, res, next) => { 返回 authHelpers .createUser(req, res) .then(响应 => { passport.authenticate('local', (err, user, info) => { 如果(错误){ 控制台.错误(错误); 控制台信息(信息); handleResponse(res, 500, '错误'); 返回下一个(错误); } 如果(!响应){ 控制台.错误(错误); 控制台信息(信息); handleResponse(res, 500, '没有用户'); 返回下一个(错误); } 如果(响应){ handleResponse(res, 200, '成功'); 下一个(); } })(req, res, next); }) .catch(错误 => { 控制台.错误(错误); 控制台信息(信息); handleResponse(res, 500, '错误'); 返回下一个(错误); }); };
[1]: https://meta.stackexchange.com/users/461693/cantuket
【问题讨论】:
标签: node.js express passport.js knex.js passport-local