Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Passport.js and Node for Single Page App

I don't think a problem has ever annoyed me like this. Seems like there are literally 0 places to look or answers to this. All I want to do is get passport to intercept a call to '/login' and '/getloginStatus'.

When logging in I just want to use a Json object as parameters for {username/password}. When I am logged in I simply want to return true/false if the user has an auth ticket in their browser.

This is what I have but it doesn't work in the slightest, half the problem seems to be that my local strategy implementation NEVER gets called....

var passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
    function(username, password, done) {

        console.log('this NEVER gets called');

    }
));

app.post('/api/authentication/login', function(req, res, next) {
            passport.authenticate('local', function(err, user, info) {

            console.log('this does get called but so what?');

            if (err) { return next(err); }

            if (!user) { return res.redirect('/login'); }
            req.logIn(user, function(err) {

                console.log('this does get called but so what am I logged in?');

                next();

            });
        })(req, res, next);
});

app.get('/api/authentication/getloginStatus', function(req, res, next) {
            passport.authenticate('local', function(err, user, info) {

             //what do I return here? !!!?

        })(req, res, next);
});

Any help greatly appreciated!

like image 886
Exitos Avatar asked Jul 09 '14 21:07

Exitos


1 Answers

Passport.js populates the request.user with currently authenticated user. So, to get the info about current user, you can do this

app.get('/api/authentication/getloginStatus', function(request, response) {
  if(request.user) {
    response.json(request.user);
  } else {
    response.status(401); //Authorization required
    response.json({"error":"Authorization required!", "code":401"})'
  }
});
like image 169
vodolaz095 Avatar answered Nov 15 '22 07:11

vodolaz095