Somename Somename -4 years ago 98
AngularJS Question

Query the db from Angular to Nodejs with passportjs

I am able to authenticate with passport-facebook and store the userid and username from facebook to my db. I am querying nodejs from angular controller :

MyApp.controller("FacebookLogin", function($scope, $http){

$scope.login = function(){
$http.get("/facebooklogin").then(function(response){
if(response.data){
console.log(response.data); // nothing is logged here
} else {
console.log("No Data");
}
});
}
});


In node :

app.get('/facebooklogin', passport.authenticate('facebook'));

app.get('/auth/facebook/callback', passport.authenticate('facebook', function(err, user, info){
console.log(err, user, info);
if(err) throw err;
// res.send(user); //Do I send the user info from here?
}));


I want to send the userid to angular to store in localStorage and use that to query the db for future requests. Is that the proper way to do it? It's a SPA. I see a
connect.sid
cookie is created in my browser. How do i extract the
userid
from it if it has the
userid
or what do i send in my
post
/
get
that nodejs recognizes thru the session?

I did read but did not understand what these two things do exactly :

passport.serializeUser(function(user, done) {
done(null, user.id);
});


passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});


Many Thanks.

Answer Source

The facebook Auth mechanism (oAuth) is asynchronous, and so it works differently to what you are expecting.

You don't do a $http.get("/facebooklogin"). Rather you should redirect your browser to '/facebooklogin'

The way the oauth process works in a nutshell is

  1. User clicks a 'Login with facebook' button, which should do a hard redirect to 'http://youserver/facebooklogin' (you can also do fancy stuff with iframes, dialogs, etc.)
  2. The server side call app.get('/facebooklogin', passport.authenticate('facebook')); will respond with a redirect to facebook.com passing through your apps credentials. At this stage, the user has effectively left your application. Facebook handles the login for the user so that you never get to see their username/password etc.
  3. If successful, facebook will redirect the browser back to your callback URL, passing through a session id. This is received at http://yourserver/facebook/callback. The server side code would then typically store this in the user session in some way, ie. in the DB, a cookie, or just redirect to a page in your app that can receive the session info and save it in local storage.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download