2014-08-28 52 views
1

用戶登錄/路由。如何在登錄後將用戶引導至新路線?

  1. 如何從/視圖我的應用程序

    /packages/system/public/views/index.html 
    

    另一種觀點認爲/app的引導他們走?

    /packages/system/public/views/app.html 
    
  2. 我想這個觀點/app是安全的,所以只有登錄的用戶可以訪問它。未登錄的用戶應發回/

回答

1

在/packages/users/controllers/meanUser.js

// Register the login() function 
    $scope.login = function() { 
    $http.post('/login', { 
     email: $scope.user.email, 
     password: $scope.user.password 
    }) 
     .success(function(response) { 
     // authentication OK 
     $scope.loginError = 0; 
     $rootScope.user = response.user; 
     $rootScope.$emit('loggedin'); 
     if (response.redirect) { 
      if (window.location.href === response.redirect) { 
      //This is so an admin user will get full admin page 
      window.location.reload(); 
      } else { 
      window.location = response.redirect; 
      } 
     } else { 
      // Redirect Here 
      $location.url('/'); 
      $location.url('/articles'); // Will take you to the articles view after login 
     } 
     }) 
     .error(function() { 
     $scope.loginerror = 'Authentication failed.'; 
     }); 
    }; 

如果你需要一個用戶被重定向到另一個頁面,當他們試圖訪問受保護的路徑沒有被登錄即可請參閱/packages/articles/public/routes/articles.js中的代碼。

// This function checks if the user is logged in and redirects to the login page. 
var checkLoggedin = function($q, $timeout, $http, $location) { 
    // Initialize a new promise 
    var deferred = $q.defer(); 

    // Make an AJAX call to check if the user is logged in 
    $http.get('/loggedin').success(function(user) { 
    // Authenticated 
    if (user !== '0') $timeout(deferred.resolve); 

    // Not Authenticated 
    else { 
     $timeout(deferred.reject); 
     $location.url('/login'); 
    } 
    }); 

    return deferred.promise; 
}; 

// These are your defined routes. 
$stateProvider 
    .state('all articles', { 
    url: '/articles', 
    templateUrl: 'articles/views/list.html', 
    // This resolve runs the checkLoggedin function as the route is accessed 
    // and redirects if the user isn't logged in. 
    resolve: { 
     loggedin: checkLoggedin 
    } 
    }); 
+0

好的,太棒了。如果用戶沒有登錄並且他們訪問/ app,我該如何將他們發送到/ auth/login? – 2014-08-28 22:03:56

+0

@MichaelCole我編輯了我的原始答案,包括重定向,如果沒有授權的代碼。希望這可以幫助。 – itaylorweb 2014-08-29 08:45:45

+0

任何人都有更好的解決方案? – 2016-01-06 19:36:20

相關問題