今天,我遇到了一个全新的问题! 首先,我有两个重要文件:
passport.js本地注册部分
passport.use('local-signup', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function(req, res) {
var password = req.body.password;
var email = req.body.email;
var generateHash = function(password) {
return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null);
};
User.find({
where: {
email: email
}
}).then(function(user) {
if (user) {
return res.json('That email is already taken');
} else {
var userPassword = generateHash(password);
var data = {
username: req.body.username,
name: req.body.name,
firstname: req.body.firstname,
email: req.body.email,
location: req.body.location,
type: req.body.type,
password: userPassword
};
db.users.create({
username: data.username,
name: data.name,
firstname: data.firstname,
email: data.email,
location: data.location,
type: data.type,
password: data.password
}).then(newUser => {
return res.json(newUser)
});
}
});
}
));
我正在做认证部分。首先,我要创建一个帐户并使用护照:注册。
我也在使用Sequelize来管理我的数据模型。 但是,当我通过POST请求调用此localStrategy时(我的身体在邮递员中一切正常),我会遇到此错误:
未处理的拒绝TypeError:res.json不是函数 返回res.json(newUser)
有人可以帮我吗? 请注意,由于passReqToCallback,done()无法正常工作(但我需要使用它来获取密码和电子邮件)
答案 0 :(得分:1)
护照localStrategy
在回调中没有res
。它的要求,用户名,密码和完成。这是一个例子。
passport.use('local-signup', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
// request object is now first argument
// ...
}
));
答案 1 :(得分:1)
您正在req.json中传递字符串。您需要使用req.send作为字符串。 示例:
替换此行:
return res.json('That email is already taken');
到
return res.send('That email is already taken');
如果您想使用JSON,请使用此格式。
return res.json({msg:'That email is already taken'});
或使用此条件
if (req.xhr) { return res.json({msg:'That email is already taken'}) }
答案 2 :(得分:1)
您可能会有些困惑,但是护照没有实现注册方法。这只是授权库。因此,您必须自行处理该用例。
首先,创建负责注册和检查的路由:
app.post('/signup', (req, res) => {
User.findOne({ $or: [{'local.email': req.body.email},{'local.username': req.body.username}]}, function(err, user){
if(err){
return res.send(err);
}
if(user){
if(user.local.email == req.body.email){
return res.send("This email is already taken.")
}
return res.send("This username is already taken.")
}
else{
var userData = new User();
userData.local.name = req.body.name;
userData.local.email = req.body.email;
userData.local.username = req.body.username;
userData.local.password = req.body.password;
userData.save()
.then(item => {
res.send("item saved to database")
// `req.user` contains the authenticated user.
//res.redirect('/profile/' + req.body.username);
})
.catch(err => {
console.log(err);
res.status(400).send("unable to save to database");
})
}
})
})
上面的示例基于express框架,但是您可以根据自己的情况毫无问题地将其安装。
下一步是包括护照本地化策略。 //加载我们需要的所有东西 var LocalStrategy = require('passport-local')。Strategy;
//加载用户模型 var User = require('../ models / user');
///使用module.exports向我们的应用程序公开此功能 module.exports = function(passport){
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, {message: 'User not found.'}); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, {message: 'Incorrect password.'}); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
return done(null, user);
});
}));
};
我们现在只有登录任务。很简单。
app.post('/login', function(req, res, next) {
passport.authenticate('local-login', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.send(info.message); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.send(user.local.username);
});
})(req, res, next);
});