我有一个向Vue前端提供数据的Node / Express API,现在正在添加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 =(要求,要求,下一项)=> { 返回authHelpers .createUser(req,res) .then(response => { Passport.authenticate('local',(err,user,info)=> { 如果(错误){ console.error(err); console.info(info); handleResponse(res,500,'错误'); 返回next(err); } 如果(!回应){ console.error(err); console.info(info); handleResponse(res,500,'no user'); 返回next(err); } 如果(响应){ handleResponse(res,200,'success'); 下一个(); } })(req,res,next); }) .catch(err => { console.error(err); console.info(info); handleResponse(res,500,'错误'); 返回next(err); }); };
[1]: https://meta.stackexchange.com/users/461693/cantuket
答案 0 :(得分:1)
不是答案:
我要做的第一件事是检查Dictionary<string, string> dict = new Dictionary<string, string>
{
{ "Config0", "0" },
{ "Config1", "1" },
{ "AnotherKey", "2" },
{ "SomeOtherKey", "3" }
};
Dictionary<string, string> configOnlyDictionary = dict.Where(x => x.Key.Contains("Config")).ToDictionary(x => x.Key, x => x.Value);
返回的内容是什么。
createUser() -> knex().insert()
答案 1 :(得分:0)
我可以看到您正在验证护照而不是注册用户。确保在您的主条目文件中使用通行证,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 函数:
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 上查看护照文件