Skip to content

7. Social Passport Integration

Jonathan Casarrubias edited this page Feb 24, 2017 · 6 revisions

LoopBack SDK Builder

##Setting Up LoopBack Component Passport

1.- Follow the loopback-component-passport Documentation.

It will create the endpoints according your configuration. e.g /auth/facebook.

server/providers.json

{
  "facebook-login": {
    "provider": "facebook",
    "module": "passport-facebook",
    "clientID": "",
    "clientSecret": "",
    "callbackURL": "https://www.myproject.com/auth/facebook/callback",
    "authPath": "/auth/facebook",
    "callbackPath": "/auth/facebook/callback",
    "successRedirect": "/auth/success",
    "scope": [
      "email"
    ],
    "failureFlash": true
  }
}

2.- So literally in your ng2 app you just need a regular link that points to that endpoint.

<a href="https://api.myproject.com/auth/facebook" >FACEBOOK LOGIN</a>

3.- Then the success callback path should point to a service path you create in the backend using a boot script, in there you will have access the accessToken and newly created userId.

server/boot/passport.js

module.exports = function(server) {
  var router = server.loopback.Router();
  router.get('/auth/success', function (req, res, next) {
    res.redirect('https://www.myproject.com/passport/' + req.accessToken.id + '/' +  req.accessToken.userId);
  });
  server.use(router);
};

NOTE: I'm using this redirection fix because I had lots of troubles with query params and angular 2, so I prefer using route params instead. May be unnecessary when Angular 2 is stable release

4.- Setup your Angular 2 Application adding a new route for passport.

const appRoutes: Routes = [
  { path: 'passport/:id/:userId', component: PassportComponent }
];

5.- In that point you will have access to an AccessToken Instance in Angular2, but you still need to locally persist it with localStorage.

For that you can use the LoopBackAuth service provided by the SDK Builder

import { SDKToken } from './shared/sdk/models';
import { LoopBackAuth } from './shared/sdk/services';
import { Router, ActivatedRoute } from '@angular/router';

@component(...)
class PassportComponent {

  constructor(
    private auth: LoopBackAuth,
    private route: ActivatedRoute,
    private router: Router
  ) {
    this.route.params.subscribe((token: SDKToken) => {
      if (token.id && token.userId) {
        this.auth.setToken(token);
        this.auth.setRememberMe(true);
        this.auth.save();
        this.router.navigate(['/account']);
      }
    });
  }
}

Enjoy!!!

Clone this wiki locally