title: Angular JS authorization - check user role before loading the page
body: <p>I'm writing cms front-end in Angular JS and I don't know how to deal with authorize user to see particular content when user first load the app. I have working solution when user is already log in and just navigate from page to page. I do it this way:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>angular.module("myApp")
  .run ($rootScope, AUTH_EVENTS, AuthServ) -&gt;
      $rootScope.$on '$stateChangeStart', (event, next) -&gt;
        if next.data
          authorizedRoles = next.data.authorizedRoles
          unless AuthServ.isAuthorized(authorizedRoles)
            event.preventDefault()
            if AuthServ.isAuthenticated()
              $rootScope.$broadcast(AUTH_EVENTS.notAuthorized)
            else
              $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated)  </code></pre>
  </div>
  </div>
  </p>
  
  <p>When user change the route, the AuthServ.isAuthorized(authorizedRoles) is fired. </p>
  
  <p>When user logs in I get token and user data from server. Token is stored in local storage and user data are stored in memory (in the scope of top level controller). In the user data I have an info about his role, so I can check if he's authorized to see particular content.</p>
  
  <p>Now let's assume that user is logged in and he reload the page. I still have the token as this is in localStorage but I loose user data (so I don't know what is his role). I don't want to show any content to user before I get his data again from server. So my question is how to resolve this ? Where and when should I make the request to server for user data ?</p>
  
  <p>I thought that solution could be to manually bootstrap the app. I tried to do something like this:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>app = angular.module('myApp', [])
  
  fetchData = -&gt;
   injector = angular.injector(['ng'])
   $http = injector.get('$http')
   API_URI = injector.get('API_URI')
   $localStorage = injector.get('$localStorage')
  
   $http.get("#{API_URI}/users/me?token=#{$localStorage.token}")
    .success (data) -&gt;
     app.constant('USER_DATA', data)
  
  bootstrapApplication = -&gt;
   angular.element(document).ready -&gt;
    angular.bootstrap(document, ['myApp'])
  
  fetchData().then(bootstrapApplication)</code></pre>
  </div>
  </div>
  </p>
  
  <p>The problem with this code is that I don't have access to $localStorage service and API_URI constant. I need them to get token and to dynamically change url (development, production).</p>
  
  <p>So what is the best solution ? Maybe storing user role in local storage as well ?</p>
  
  <p>Any help would appreciated, Thanks.</p>