Trouble authenticating with passport after refacto

2019-07-27 09:46发布

问题:

I am building out a RESTful app using node.js, mongoose, express & passport using .ejs as a front end. I'm trying to add authentication back in with passport. With the current code I can register a new user, but that new user does not remain logged in, and after creating the user, I cannot login to do activities requiring authorization. There is no persistent user it seems. I'm using express-session as well.

I've searched for similar issues but any "fixes" have not seemed to help. I have nearly identical code in a similar app with the same stack...the main difference being the names of the resources (ie races instead of projects for example)

This will be the 3rd application I've used passport with, so it's not 100% new and with similar / same code, it has worked on my local installation. in this case, it was working fine including showing and hiding the login/logout buttons in my .ejs file.

Then I refactored the routes and now I cannot get passport to work at all. I have compared code, placed the auth routes back into the app.js file, tried to console.log the req.user with and without logging in and it just won't work anymore...none of the passport routes seem to function.

I've reinstalled the node modules from my package.json file, copied & pasted the passport setup from previously working files, and the req.user is always undefined, and I'm unable to register a new user.

I've essentially reinstalled all of the passport stuff, short of deleting the auth file and app.js lines and restarting...but I should be able to trouble shoot this without deleting content.

Sadly I did not save a version prior to refactoring. :(

Any suggestions on why this may have occurred AFTER I refactored the routes files when it was working well just prior? As far as I can tell I have reconstructed things as they were prior to refactoring.

Here is my app.js passport setup

//setup passport
app.use(require("express-session")({
  secret: "Fig is the best puppy ever",
  resave: false,
  saveUninitialized: false
}))


app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.use(function(req, res, next){
  console.log("Current User: " + req.user)
  res.locals.currentUser = req.user;
  next();
});

and my auth routes:

//Authentication Routes
//show signup form
app.get('/register', function(req,res){
  res.render("register")
})


//user signup
app.post("/register", function(req,res){
  //res.send("Signing you up")
  console.log(req.body)
  var newUser = new User({username: req.body.username})
  User.register(newUser, req.body.password, function(err, user){
    if(err) {
      console.log(err);
      return res.render('register')
    } else {
      passport.authenticate("local")(req,res, function(){
        console.log("Created new user")
        res.redirect("/projects")
      })
    }
  })
})

//LOGIN ROUTES
//render login form
app.get("/login", function(req,res){
  res.render("login")
})

app.post("/login", passport.authenticate("local",
  {
    successRedirect: "/projects",
    failureRedirect: "/login"
  }), function(req,res) {
  // console.log("Logged in" +currentUser)
  // res.redirect("/projects")
})

//Logout Routes
app.get("/logout", function(req,res) {
  req.logout()
  res.redirect("/projects")
})

回答1:

It looks like you're missing the req.login call on authenticate. Try adding this to your else in your register middleware.

passport.authenticate("local")(req, res, function() {
  req.login(user, function(err) {
    if (err) {
      console.log(err);
      res.redirect('/register');
    } else {
      res.redirect('/projects')
    }
  })
})


回答2:

Solution by OP.

Solved by reordering my route requirements and the passport set up. The correct sequence is below.

//setup passport
app.use(require("express-session")({
  secret: "Fig is the best puppy ever",
  resave: false,
  saveUninitialized: false
}))


app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

//I MOVED THESE LINES TO BELOW THE PASSPORT SETUP
// Route setup
app.use("/users", userRoutes)
app.use(authRoutes)