0
votes

Using node.js with an express server, my intention is to save on session the local user that has been logged in so i can call it from the front end and get the user information if the user is actually logged in.

For that I am using express-session and passport. The following code returns the user if correctly logged in and saving the session in req.

I've debuged the query and returns correctly the data.

passport.use('local-login', new LocalStrategy({
  usernameField: 'email',
  passwordField: 'pass',
  passReqToCallback: true
},
function(req, email, pass, done) {

 return modelUsers.login(email, pass, done);

}));

This is my session configuration.

 app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: 'strongertogether',
  cookie: { secure: false }
 } )); // session secret
app.use(passport.initialize());
app.use(passport.session());   // Persistent login sessions
app.use(cors());               //Required for signin facebook

As far as i know, once the login is done the user is saved on session and the function req.isAuthenticated() should return a true value but instead is false, req.user is undefined.

Matter fact twitter and facebook sessions work correctly.

From the front end (Angular.js) i'm calling to

app.get('/api/loggedin', usersController.loggedin);

That goes to

function loggedin(req, res) {
 res.send(req.isAuthenticated() ? req.user : '0');
}

Versions:

"express": "^4.9.3"

"express-session": "^1.11.3"

"passport-local": "^1.0.0"

"passport": "^0.2.2"

1
i did not go through your code but my be this scotch useful to understand your problem https://scotch.io/tutorials/easy-node-authentication-setup-and-local. I am using same method and work fine for me. Go through link may me use are missing something.Yogesh Patel

1 Answers

0
votes

have you read a passport-local documentations ?

passport-local npm

and have you use route like snippets bellow in your route ?

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login' }),
   function(req, res) {
  res.redirect('/');
});

you can find code above on documentations passport-local.

or maybe you can try to check on here : https://github.com/egin10/login-passport/blob/master/routes/users.js