How to combine passport and angular -ui routing

I am wondering how I can combine angular -ui-routing with a passport. All the examples that I find use node.js routing there.

var routerApp = angular.module('routerApp', ['ui.router']);

routerApp.config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('/home');

$stateProvider

    .state('home', {
        url: '/home',
        templateUrl: 'partial-home.html'
    })

    .state('about', {
        // for example just show if is loggedIn       
    });

How to implement this function in the above snippet?

function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/');
}

Thanks for every hint.

+4
source share
1 answer

One way to get started is to create a service in Angular that uses $ http to reach your endpoint in Express. $ http returns a promise with success and error methods that you can use to change state. If you are building a single page application (SPA), this is probably all you need to know. For instance:

// An Angular service that talks to Express
UserService.$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 - UI Router, .

Express Passport . :

 // 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); 
  });

Passport , . , 200 Angular, .success. 401 Unauthorized .error.

+9

All Articles