How to combine passport and angular-ui routing How to combine passport and angular-ui routing angularjs angularjs

How to combine passport and angular-ui routing


One way to start is by creating a service in Angular that uses $http to hit your endpoint in Express. $http returns a promise with success and error methods you can use to change state. If you're building a Single Page App (SPA) this is probably all you need to know. For example:

// An Angular service that talks to ExpressUserService.$inject = ['$http', '$state']; function UserService($http, $state) {    this.loginUser = function (user) {      $http.post("/api/login", user)        .success(function (data, status) {          console.log('Successful login.');          console.log('data = ' + data);           console.log('status = ' + status);           $state.go('welcome'); //       })        .error(function (data) {          console.log('Error: ' + data);          $state.go('somewhereelse');       });  }; 

$state.go is a UI Router convenience method that will render your defined state.

In Express you'll want to write your own callback function for Passport to control what is returned. For example:

 // Express Route with passport authentication and custom callback  app.post('/api/login', function(req, res, next) {      passport.authenticate('local-login', function(err, user, info) {        if (err) {        return next(err);       }      if (user === false) {        res.status(401).send(info.message);        } else {        res.status(200).send(info.message);       }    })(req, res, next);   });

In this example, I'm using a 'local-login' Passport strategy that's working it's magic in the background. If the user is authenticated it will send a 200 back to Angular, which will in turn trigger .success. Otherwise it will send a 401 Unauthorized and fire off .error.