我是NodeJS的新手。我使用Express进行了基本的CRUD应用验证。注册成功,但登录失败。我正在使用护照和bcryptjs进行身份验证。
这是返乡路线。由于index是自动调用的,因此不会被调用。对于其他路由,仅在将函数ensureAuthenticated
手动传递给其参数时才有效,如下所示。我希望它能在所有端点上正常工作,而无需手动操作。
app.get("/", ensureAuthenticated, function (req, res) {
res.render('index');
});
下面是登录功能。
app.get("/login", function (req, res) {
const loginPath = path.join(__dirname, '/login.html');
res.sendFile(loginPath);
});
passport.use(new localStrategy({
usernameField: 'adminUsername',
passwordField: 'password',
session: false
},
function (adminUsername, password, done) {
Admin.getAdminByAdminUsername(adminUsername, function (err, admin) {
if (err) throw err;
console.log('getAdmin called');
if (!admin) {
console.log('Admin Not Found');
return done(null, false);
}
Admin.comparePassword(password, admin.password, function (err, isMatch) {
console.log('comparePassword called');
if (err) throw err;
if (isMatch) {
return done(null, admin);
} else {
console.log('Wrong Password!');
return done(null, false);
}
});
});
}));
passport.serializeUser(function (admin, done) {
done(null, admin.id);
});
passport.deserializeUser(function (id, done) {
Admin.getAdminById(id, function (err, admin) {
done(err, admin);
console.log('findById called');
});
});
app.post('/login', passport.authenticate('local', {
failureRedirect: '/login'}), function(req, res){
console.log('login called');
res.redirect('/');
});
app.get('/logout', function(req,res){
req.logout();
res.redirect('/login');
});
function ensureAuthenticated(req, res, next){
if (req.isAuthenticated()) {
return next();
} else {
res.redirect('/login');
}
}
问题是即使没有身份验证,我仍然可以通过URL端点进行访问。
这是管理架构文件。
const mongoose = require("mongoose");
const bcrypt = require('bcryptjs');
const schema = new mongoose.Schema({
adminEmail: {
type: String,
unique: true,
required: true
},
adminUsername:{
type: String,
unique: true,
required: true
},
password:{
type: String,
required: true
}
});
const Admin = mongoose.model('Admin', schema);
module.exports = Admin;
module.exports.getAdminByAdminUsername = function (adminUsername, callback) {
const query = {adminUsername: adminUsername};
Admin.findOne(query, callback);
}
module.exports.getAdminById = function (adminId, callback) {
Admin.findById(adminId, callback);
}
module.exports.comparePassword = function (password, hash, callback) {
bcrypt.compare(password, hash, function (err, isMatch) {
if (err) throw err;
callback(null, isMatch);
});
}