我正在尝试使用本地护照猫鼬对用户进行身份验证。每次尝试登录时,我始终收到验证错误,提示用户密码丢失。我的app.js文件内容如下:
const express = require('express');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');
const url = `mongodb://127.0.0.1:27017/secretsDB`;
const port = process.env.PORT ? process.env.PORT : 4000;
require('dotenv').config();
const app = express();
app.use(express.static(`${__dirname}/public`));
app.use(bodyParser.urlencoded({extended: true}))
app.set('view engine', 'ejs');
app.use(session({
secret: process.env.SECRET,
resave:false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect(url, {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.set('useCreateIndex', true);
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model('User', userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.get('/', (req, res) => {
res.render('home');
});
app.get('/login', (req, res) => {
res.render('login');
});
app.get('/register', (req, res) => {
res.render('register');
});
app.get('/secrets', (req, res) => {
if(req.isAuthenticated()) {
res.render('secrets');
} else {
res.redirect('/login');
}
});
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
app.post('/register', (req, res) => {
User.register({username: req.body.username}, req.body.password, (err, user) => {
if(err) {
console.log(err);
res.redirect('/register');
} else {
passport.authenticate('local')(req, res, () => {
res.redirect('/secrets');
});
}
});
});
app.post('/login', (req, res) => {
const user = new User({
username: req.body.username,
password: req.body.password
});
req.login(user, (err) => {
if(err) {
console.log(err);
} else {
passport.authenticate('local')(req, res, () => {
res.redirect('/secrets');
});
}
})
});
app.listen(port, () => {
console.log(`app is listening on ${port}`);
});
我的github repository包含了整个项目
The error in the console is as follows:
Error: User validation failed: password: Path `password` is required.
at ValidationError.inspect (/home/anthony/Documents/Code/Angela/Secrets/node_modules/mongoose/lib/error/validation.js:48:26)
at formatValue (internal/util/inspect.js:703:31)
at inspect (internal/util/inspect.js:272:10)
at formatWithOptions (internal/util/inspect.js:1887:40)
at Object.Console.<computed> (internal/console/constructor.js:284:10)
at Object.log (internal/console/constructor.js:294:61)
at /home/anthony/Documents/Code/Angela/Secrets/app.js:80:21
at /home/anthony/Documents/Code/Angela/Secrets/node_modules/passport-local-mongoose/index.js:247:59
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
errors: {
password: ValidatorError: Path `password` is required.
at validate (/home/anthony/Documents/Code/Angela/Secrets/node_modules/mongoose/lib/schematype.js:1178:13)
at /home/anthony/Documents/Code/Angela/Secrets/node_modules/mongoose/lib/schematype.js:1161:7
at Array.forEach (<anonymous>)
at SchemaString.SchemaType.doValidate (/home/anthony/Documents/Code/Angela/Secrets/node_modules/mongoose/lib/schematype.js:1106:14)
at /home/anthony/Documents/Code/Angela/Secrets/node_modules/mongoose/lib/document.js:2387:18
at processTicksAndRejections (internal/process/task_queues.js:79:11) {
properties: [Object],
kind: 'required',
path: 'password',
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}
我已经查看了我的代码,完成了google搜索,但似乎找不到答案。谁能帮忙。
答案 0 :(得分:0)
代替passport.use(User.createStrategy());
做这样的事情:
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
然后,您可以验证受保护的路由,例如:
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
答案 1 :(得分:0)
今天早上,我想到了在猫鼬模式中使用required属性的想法,因此我从密码字段中删除了required属性,瞧,代码可以正常工作了。这很有趣。您为什么认为需要密码字段导致此错误?我想我找到了原因,但是如果有其他原因,请随时让我知道,在数据库中,passport创建了一个盐和哈希条目,而不是密码条目,因此通过在模式中输入必需的密码,代码将错误,因为它不再存在。