我正在构建一个简单的应用程序,一旦用户注册,该应用程序将被定向到登录页面以再次输入其凭据。完成此操作后,将带他们到主页。但是,这没有发生。
我的护照配置
passport.use(new localStrategy(
{
usernameField: "email"
},
function(email, password, done) {
db.User
.findOne({where: {email: email}})
.then((dbUser) => {
if(!dbUser) {
return done (null, false, {
message: "We couldn't find that email"
});
}
else if (!dbUser.validPassword(password)) {
return done (null, false, {
message: "Password incorrect"
});
}
return done(null, dbUser);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
db.User.findById(id, function(err, user) {
if (err) {return done(err)}
done(null, user);
});
});
module.exports = passport;
我的模特
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
firstname: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING
}, {});
User.prototype.validPassword = function(password){
return bcrypt.compareSync(password, this.password);
};
User.addHook("beforeCreate", function(user) {
user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(10), null);
});
return User;
};
登录页面路线
module.exports = function(app) {
app.get('/login', (req, res, next) => {
console.log(req.user);
if (req.user) {
res.redirect('/home');
}
res.sendFile(path.join(__dirname, "../views/login.html"))
});
app.post('/login',
passport.authenticate('local', {
failureRedirect: '/registration',
failureFlash: true
}),
function(req, res) {
console.log(req.user);
res.redirect('/home')
}
);
};
首页路线
module.exports = function(app) {
app.get('/', (req, res) => {
res.redirect('/home');
})
app.get('/home', isAuthenticated, function(req, res) {
res.sendFile(path.join(__dirname, "../views/index.html"))
});
app.get('/logout', (req, res) => {
req.logout();
req.session.destroy();
return res.redirect("/login");
})
};
isAuthenticated.js
module.exports = function(req, res, next) {
if(req.isAuthenticated()) {
return next();
}
return res.redirect("/login");
}
app.js文件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static('public'));
app.use(session({secret: "guineapigs"}));
app.use(passport.initialize());
app.use(passport.session());
require('./routes/index')(app);
require('./routes/registration')(app);
require('./routes/login')(app);
app.listen(PORT, function(err) {
if (err) throw err;
console.log("Magic is happening at http://localhost:"+ PORT);
})
我可以看到用户名,电子邮件和哈希密码在数据库中。
但是,当我尝试输入数据库中已经存在的电子邮件和密码时,我会被重定向到登录页面,上面带有“错误”字样。 我在终端中得到了这个:
POST /login 500 19.576 ms - 5
Passport本身不记录配置文件中包含的任何消息。也不处理失败重定向到注册页面。
我在这里尝试了答案 Just can't get Passport.js to work
..这里 Problems getting Passport.js to authenticate user
我想念什么?