Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Login by facebook in angular app with loopback backend

I'm making an angular application with strongloop loopback backend.

Also I integrating a third party login by facebook using loopback-passport module.

everything was fine in loopback-example-passport and everything is fine in my app right before the moment of redirecting to my app. User and Access-token created.

the code:

app.get('/auth/login', ensureLoggedIn('/#login'), function(req, res, next) {
    console.log('LOOGED IN!!');
console.log(req.user);

  res.redirect('/#auth/login');
});

works fine. But i can't understand. how to give authenticated state to my angular application.

i tried to make a controller to route '/#auth/login':

.controller('AuthCalbackCtrl', function($scope, $cookies, $location, AppAuth, $http, User, LoopBackAuth) {
//analogue of User.login responce interceptor
   LoopBackAuth.currentUserId = $cookies['userId'] || null;
   LoopBackAuth.accessTokenId = $cookies['access-token'] || '';
   LoopBackAuth.rememberMe = false;
   LoopBackAuth.save();
   //asking for currentUser
   User.getCurrent(function(user) {
     console.log('ser.getCurrent ', user);
   });
   $location.path('/');
  })

This code makes a request GET /api/users/2 but receives 401 error.

If I tweak the file /loopback/lob/models/user.js setting permission:

  principalType: ACL.ROLE,
  // principalId: Role.OWNER,
  principalId: Role.EVERYONE,
  permission: ACL.ALLOW,
  property: "findById"

Then the request GET /api/users/2 receives 200 and everything ok.

I'm a little confused. I can`t understand how to make my angular app authenticate to loopback, although i know access-token and userId

Have anybody any ideas how to do it?

like image 227
chilicoder Avatar asked Jun 13 '14 21:06

chilicoder


1 Answers

Here is a valid code.

app.get('/auth/login', function(req, res, next) {
  //workaround for loopback-password 
  //without this angular-loopback would make incorrect authorization header
  res.cookie('access-token', req.signedCookies['access-token']);
  res.cookie('userId', req.user.id);
  res.redirect('/#auth/login');
});

The problem is that loopback-passport signs cookie:

         res.cookie('access-token', info.accessToken.id, { signed: true,
           maxAge: info.accessToken.ttl });

In string it looks something like the following "s:.eBvo8bpo9Q9wnNrPjjlG%2FAcYqWkxEgNFqn%2FO54rdGwY"

But loopback-angular just copies the access-token to header.authorization, so we need to put there plain cookie.

like image 87
chilicoder Avatar answered Oct 05 '22 11:10

chilicoder