创建用户时 Passport-local 超时(Node、Express、Postgres、Knex)
Passport-local times out on create user (Node, Express, Postgres, Knex)
我有一个 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 正在 returning 生成用户对象,该对象正确插入到数据库中:
//console.log('res: ', 结果)
{ id: 30,
email: 'boooya@dubay.com',
password:
'a$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) => {
return authHelpers
.createUser(请求,资源)
.then(响应=> {
passport.authenticate('local', (err, user, info) => {
如果(错误){
console.error(错误);
console.info(信息);
handleResponse(res, 500, 'error');
return 下一个(错误);
}
如果(!响应){
console.error(错误);
console.info(信息);
handleResponse(res, 500, 'no user');
return 下一个(错误);
}
如果(响应){
handleResponse(res, 200, 'success');
下一个();
}
})(要求,资源,下一个);
})
.catch(错误 => {
console.error(错误);
console.info(信息);
handleResponse(res, 500, 'error');
return 下一个(错误);
});
};
[1]: https://meta.stackexchange.com/users/461693/cantuket
不是答案:
我要做的第一件事是检查 createUser() -> knex().insert()
返回了什么...
.then(result => {
console.log('createUser:', result)
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(err=> {
console.log('err createUser:', err)
next();
});
我可以看到您正在验证护照而不是注册用户。确保在您的主要条目文件中使用护照,app.js 像这样。
const passport = require('passport')
app.use(passport.initialize())
app.use(passport.session())
passport.use(User.createStrategy())
passport.serializeUser((user, done)=>done(null, user.id));
passport.deserializeUser((id, done)=>User.findById(id, (err, user)=>done(err, user)))
app.use((req, res, next)=>{
res.locals.currentUser = req.user;
res.locals.title = 'Conforti';
res.locals.success = req.session.success || '';
delete req.session.success;
res.locals.error = req.session.error || '';
delete req.session.error;
res.locals.csrfToken= req.csrfToken();
req.session.cookie.expires = new Date(Date.now() + 3600000)
req.session.cookie.maxAge = 3600000
next();
});
在您的控制器中,您应该导入用户模型并像这样对其进行身份验证:
const User = require('../models/users')
这是登录后函数:
postLogin: async (req, res, next)=>{
const {username, password} = req.body;
const {user, error} = await User.authenticate()(username, password);
if(!user && error) return next(error);
req.login(user, (err)=>{
if(err) return next(err);
req.session.success = `Welcome back, ${user.username}`;
const redirectUrl = req.session.redirectTo || '/';
delete req.session.redirectTo;
res.redirect(redirectUrl);
});
},
这可能不是完整的代码,但它可能会帮助您发现错误。
您还可以在 npmjs.com
上查看护照文件
我有一个 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 正在 returning 生成用户对象,该对象正确插入到数据库中:
//console.log('res: ', 结果)
{ id: 30,
email: 'boooya@dubay.com',
password:
'a$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) => { return authHelpers .createUser(请求,资源) .then(响应=> { passport.authenticate('local', (err, user, info) => { 如果(错误){ console.error(错误); console.info(信息); handleResponse(res, 500, 'error'); return 下一个(错误); } 如果(!响应){ console.error(错误); console.info(信息); handleResponse(res, 500, 'no user'); return 下一个(错误); } 如果(响应){ handleResponse(res, 200, 'success'); 下一个(); } })(要求,资源,下一个); }) .catch(错误 => { console.error(错误); console.info(信息); handleResponse(res, 500, 'error'); return 下一个(错误); }); };
[1]: https://meta.stackexchange.com/users/461693/cantuket
不是答案:
我要做的第一件事是检查 createUser() -> knex().insert()
返回了什么...
.then(result => {
console.log('createUser:', result)
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(err=> {
console.log('err createUser:', err)
next();
});
我可以看到您正在验证护照而不是注册用户。确保在您的主要条目文件中使用护照,app.js 像这样。
const passport = require('passport')
app.use(passport.initialize())
app.use(passport.session())
passport.use(User.createStrategy())
passport.serializeUser((user, done)=>done(null, user.id));
passport.deserializeUser((id, done)=>User.findById(id, (err, user)=>done(err, user)))
app.use((req, res, next)=>{
res.locals.currentUser = req.user;
res.locals.title = 'Conforti';
res.locals.success = req.session.success || '';
delete req.session.success;
res.locals.error = req.session.error || '';
delete req.session.error;
res.locals.csrfToken= req.csrfToken();
req.session.cookie.expires = new Date(Date.now() + 3600000)
req.session.cookie.maxAge = 3600000
next();
});
在您的控制器中,您应该导入用户模型并像这样对其进行身份验证:
const User = require('../models/users')
这是登录后函数:
postLogin: async (req, res, next)=>{
const {username, password} = req.body;
const {user, error} = await User.authenticate()(username, password);
if(!user && error) return next(error);
req.login(user, (err)=>{
if(err) return next(err);
req.session.success = `Welcome back, ${user.username}`;
const redirectUrl = req.session.redirectTo || '/';
delete req.session.redirectTo;
res.redirect(redirectUrl);
});
},
这可能不是完整的代码,但它可能会帮助您发现错误。
您还可以在 npmjs.com
上查看护照文件