0

I am new to this whole node thing, and password is quite intriguing and seems to quite work for many of the authentications, so it looked cool.

Scenario: I wanted to say, /profile to proceed, only when user is logged in.

Here is the route I made,

var express = require('express');
var router = express.Router();

the rest is in the file called router/index.js

var passport = require('passport');
var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;


router.post('/login', passport.authenticate('login', {
    successRedirect: '/home',
    failureRedirect: '/',
    failureFlash : true  
}));


router.get('/profile', ensureLoggedIn('/'), function(req, res){
    res.json({ user: req.user });
});

So, based on my understanding and willingness, when I did GET /profile, it had to go to login page, and then redirect to GET /profile. Unfortunately, since the login page is supposed to return home, it does so.

connect-ensure-login is what I expected to solve the problem, but it hasn't. How do I make it work as I needed?

Rockink
  • 180
  • 4
  • 17
  • Possible duplicate of [Redirecting to previous page after authentication in node.js using passport.js](http://stackoverflow.com/questions/13335881/redirecting-to-previous-page-after-authentication-in-node-js-using-passport-js) – gevorg Jun 04 '16 at 20:56
  • 1
    @gevorg I agree that this question is a duplicate, it's just that the accepted answer (with 38 upvotes!) isn't Passport-specific at all. The second answer ([this one](http://stackoverflow.com/a/36708483/893780)) is the good one, I should probably have linked to it in a comment instead of posting an answer... – robertklep Jun 04 '16 at 21:03
  • @robertklep agree, your answer is the best choice for this question. – gevorg Jun 04 '16 at 21:05

1 Answers1

4

You should use successReturnToOrRedirect instead of successRedirect:

router.post('/login', passport.authenticate('login', {
  successReturnToOrRedirect : '/home',
  failureRedirect           : '/',
  failureFlash              : true  
}));
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • Why wouldn't this be discussed in their documentation? – Rockink Jun 04 '16 at 20:58
  • That's where I found it ([here](https://github.com/jaredhanson/connect-ensure-login#log-in-and-return-to) specifically), although I have to admit that it's not pointed out very clearly. – robertklep Jun 04 '16 at 21:00
  • @robertklep I think that is, because they didn't use proper formatting on their `README` page for particular example https://github.com/jaredhanson/connect-ensure-login/pull/22 – gevorg Jun 04 '16 at 21:08
  • 1
    @gevorg great idea, that PR. That's the place in the docs where I found the solution, but it's all on one line, not very readable at all. – robertklep Jun 05 '16 at 17:48