2014-03-02 69 views
0

我使用AngularJS,Django rest框架和Django。我想使它成爲匿名用戶無法訪問angularjs端的視圖。其餘的框架不允許匿名用戶實際上從angularjs veiw做任何事情,但是,匿名用戶仍然可以訪問它,並且我想禁止它。所以基本上我想設置django在我的angularjs路由中的login_required功能。AngularJS和Django只允許在用戶登錄時訪問角度視圖

var app = angular.module('mostAwesomeApp', ['restangular', 'ngRoute']) 

app.config(function($routeProvider){ 
    var base_dir = STATIC_URL + 'js/ng-coolest-app-ever/templates/'; 

    $routeProvider.when('/', 
     { 
      templateUrl: base_dir + 'list.html', 
      controller: 'listViewCtrl' 
     }) 
     .when('/edit/:pk',{ 
      templateUrl: base_dir + 'update.html', 
      controller: 'editCtrl' 
     }) 
}) 

// any one can see this ctrl/view 
app.controller('listViewCtrl', function($scope){ 
    $scope.doSomethingAwesome = function(){//doing something awesome} 
}) 
// only authed users should be able access this ctrl and view attached to it 
app.controller('editCtrl', function($scope){ 
    $scope.onlyAuthedUsersCanDoAndSee = function(){ 
     // doing something awesome for authed peeps} 
    } 
}) 
<div ng-app='mostAwesomeApp'> 
    // This is the issue. If i'm using ng-view that means I cant just do a 
    // Django if user.auth... statements to dictate what a anon user can or 
    // cannot see 
    <ng-view></ng-view> 
</div> 

所以我一直爭論不休只是通過在用戶狀態轉換爲JavaScript變種,並使其全球爲我所有的應用程序的解決方案。然後,只需檢查該var是否需要特殊處理的應用程序。是的它的工作原理,但它似乎並不是最優雅的。

回答

1

您可以使用$ routeProvider的resolve方法在視圖加載之前檢查登錄用戶。如果未經身份驗證,則可以引發應用程序的另一部分偵聽並將用戶重定向到登錄視圖的任意事件

$routeProvider.when('/edit/:pk',{ 
     templateUrl: base_dir + 'update.html', 
     controller: `enter code here`'editCtrl', 
     resolve: { 
      currentUser: function(MyUserAuthService, $rootScope) { 
       var u = MyUserAuthService.getCurrentUser(); 
       if (u === null) $rootScope.$broadcast('noauth'); 
       return u; 
      } 
     } 
    }) 

app.run(function($rootScope, $location) { 
    $rootScope.$on('noauth', function() { 
     $location.path('/loginpage'); 
    }); 
}); 
相關問題