我目前正在使用Express,Node,Mongoose和Passport.js进行注册和登录系统,并且该注册器大多数都可以正常工作(除了successRedirect不起作用),但是登录系统存在很大问题。由于某种原因,在我创建的护照方法中,无法读取未定义的“密码”,因此出现了一些未定义的密码,但我似乎无法弄清楚。另外,如果有人知道为什么我在注册路由上的successRedirects无法正常工作,将不胜感激!
护照配置文件:
var LocalStrategy = require("passport-local").Strategy;
const User = require("../user");
const passport = require("passport");
const crypto = require("crypto");
//Signup method
module.exports = (passport) => {
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
};
passport.use(
"local-signup",
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
passReqToCallback: true,
},
(req, email, password, done) => {
process.nextTick(() => {
User.findOne({ email: email }, (err, user) => {
if (err) {
return done(err);
}
if (user) {
return done(
null,
false,
req.flash("signupMessage", "That email is already taken.")
);
} else {
let token = crypto.randomBytes(64).toString("hex");
const user = new User();
user.name = req.body.username;
user.email = email;
user.password = user.generateHash(password);
user.verificationHash = token;
user.save();
}
});
});
}
)
);
// Login method
passport.use(
"local-login",
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
passReqToCallback: true,
},
(req, email, password, done) => {
User.findOne({ email: email }, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, req.flash("loginMessage", "No user found."));
}
if (!user.validPassword(password)) {
return done(
null,
false,
req.flash("loginMessage", "Oops! Wrong password")
);
}
return done(null, user);
});
}
)
);
index.js路由:
app
.route("/register")
.get((req, res) => {
res.render("register", { message: req.flash("signupMessage") });
})
.post(
passport.authenticate("local-signup", {
successRedirect: "/verify/emailSent",
failureRedirect: "/register",
failureFlash: true,
}),
(req, res) => {
}
);
app
.route("/login")
.get((req, res) => {
res.render("login", { message: req.flash("loginMessage") });
})
.post(
passport.authenticate("local-login", {
successRedirect: "/verify/emailSent",
failureRedirect: "/login",
failureFlash: true,
}),
(req, res) => {
//if this gets called authentication was succesful.
//req.user is the authenticated user
}
);
登录文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<% if (message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
<form action="/login" method="POST">
<label for="email">Email</label>
<input type="email" name="email" id="email" required />
<label for="password">Password</label>
<input type="password" name="password" id="password" required />
<button type="submit">Log in</button>
</form>
<a href="/register">Register</a>
<a href="/">Home</a>
</body>
</html>