javascript - Protecting routes with authentication in an AngularJS app -


some of angularjs routes pages require user authenticated api. in cases, i'd user redirected login page can authenticate. example, if guest accesses /account/settings, should redirected login form.

from brainstorming came listening $locationchangestart event , if it's location requires authentication redirect user login form. can simple enough in applications run() event:

.run(['$rootscope', function($rootscope) {     $rootscope.$on('$locationchangestart', function(event) {         // decide if location required authenticated user , redirect appropriately     }); }]); 

the next step keeping list of applications routes require authentication, tried adding them parameters $routeprovider:

$routeprovider.when('/account/settings', {templateurl: '/partials/account/settings.html', controller: 'accountsettingctrl', requiresauthentication: true}); 

but don't see way requiresauthentication key within $locationchangestart event.

am overthinking this? tried find way angular natively couldn't find anything.

what did implement angularjs interceptor handles http request errors. basically, when 401 (unauthorized) backend, save current url , redirect user login page. when user login successfully, retrieve saved url set path $location.

app.config(function ($routeprovider, $locationprovider, $httpprovider) {      /* global interceptor 401 - not authorized */     var interceptor = ['$location', '$q', 'authorizationservice', function ($location, $q, authorizationservice) {          function success(response) {             return response;         }          function error(response) {             if (response.status === 401) {                 authorizationservice.saveurl($location.path());                 $location.path('/logon');                 return $q.reject(response);             }             else {                 return $q.reject(response);             }         }          return function (promise) {             return promise.then(success, error);         };     } ]; }); 

in logon controller (on successful logon) set location this:

$location.path(authorizationservice.geturl()); 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -