我是新手,對整個用戶進行身份驗證,並嘗試學習如何使用Passport的LocalStrategy將用戶添加到Mongo數據庫。Nodejs護照本地策略總是失敗
我想跟隨一個特定的教程,出於某種原因,事情不會計劃。每當我提交註冊表單時,策略總是失敗(重定向到失敗頁面)。我有一種感覺,這與他請求的身體沒有被傳遞有關(因爲我放置在聲明策略的日誌未運行)。但是,目前的基礎設施似乎很難重構。此代碼是否可以重構,以便在將請求交給護照之前手動解析請求(例如,request.body。* name *)?
除非問題是完全不同的東西,在這種情況下,我不知道......
index.js:
// Use middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(expressSession({ secret: 'whatkindofgamedoyouthinkthisishey',
cookie: {maxAge:null},
resave: false,
saveUninitialized: false}));
require("./config/passport")(passport);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// Obtain application modules
var userModels = require("./schemas/user")(mongoose);
var loginPage = require("./routes/login")(passport, userModels);
// Initialize Routes
app.use("/", loginPage);
passport.js(應該拿出一個更好的名字):
var LocalStrategy = require("passport-local").Strategy,
User = require("../schemas/user");
module.exports = function (passport) {
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
passport.use("local-signup", new LocalStrategy({
email: "email",
password: "password",
passReqToCallback: true
},
function (request, email, password, done) {
console.log("message sent to sign up"); // log not running
process.nextTick(function() {
User.findOne({email: email}, function (err, user) {
if (err) {
return done(err);
}
if (user) {
return done(null, false, request.flash("signupMessage", "That email is already taken"));
} else {
var newUser = new User();
newUser.email = email;
newUser.password = password;
newUser.save(function (err) {
if (err) {
throw err;
} else {
return done(null, newUser);
}
});
}
});
});
}
));
};
login.js(路由器被導出)
router.post("/register", passport.authenticate("local-signup", {
successRedirect: "/loggedIn",
failureRedirect: "/connectFailed",
failureFlash: false
}));
HTML表單:
<form class="form-signin" action="/register" method="POST">
<div class="logoContainer">
<img src="images/LogoWithoutText.png" class="image image-responsive" id="loginImage">
</div>
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" name="email" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" name="password" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
在html窗體標記中嘗試使用action =''/ routes/login/register「 –
我測試過路由器配置了」非護照「路由,並且它工作正常。問題(嘗試過你的解決方案,它沒有工作) – user2795329