Question

I'm using AngularJS, django rest framework, and Django. I would like to make it so that a anon user cannot access a view in the angularjs side. The rest framework disallows an anon user from actually doing anything from the angularjs veiw, however, the anon user still can get to it, and I want to disallow that. So basically I want to set up login_required functionality that django has in my angularjs routes.

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>

So the solution I've been debating over is just pass in the user status into a JavaScript var, and make it global for all my apps. And then just check the var for any app that requires special treatment.. Yah it works, but it really doesn't seem the most elegant.

Était-ce utile?

La solution

You can use the resolve method of $routeProvider to check for a logged in user before the view even loads. If unauthenticated you can raise an arbitrary event that another part of your app listens to and redirects the user to a log in view

$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');
    });
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top