lynndylanhurley / ng-token-auth

Token based authentication module for angular.js.
Do What The F*ck You Want To Public License
1.8k stars 234 forks source link

Problems implementing routing with ui-router #291

Open buccfer opened 8 years ago

buccfer commented 8 years ago

On read me:

$auth.validateUser This method returns a promise that will resolve if a user's auth token exists and is valid. This method does not accept any arguments. Later on read me:

The following API methods accept a config option that can be used to specify the desired configuration.

$auth.authenticate $auth.validateUser $auth.submitRegistration $auth.submitLogin $auth.requestPasswordReset All other methods ($auth.signOut, $auth.updateAccount, etc.) derive the configuration type from the current signed-in user.

I have:

.config(($stateProvider) ->
  $stateProvider
    .state('admin', {
      url: '/admin'
      abstract: true
      template: '<div ui-view></div>'
      resolve: {
        auth: ($auth) -> $auth.validateUser({config: 'admin'})
      }
    })
    # Invoice states
    .state('admin.invoices', {
      url: '/facturas'
      templateUrl: '/app/components/admin/invoices/invoices.html'
      controller: 'AdminInvoicesController'
    })

But if I log in not as and admin user (i.e. A dispatcher user), then this promise is being resolved anyway allowing the user to access routes that he shouldn't. Is there any kind of solution for this?

buccfer commented 8 years ago

I came up with a workaround to this problem. I created a service that checks the user role.

auth-helper.coffee

angular.module('shared').factory('AuthHelper', ($q, $auth, $log) ->
  hasRole = (role) ->
    deferred = $q.defer()

    onValidateSuccess = (userData) ->
      if userData.configName is role
        $log.debug "Access allowed"
        deferred.resolve("Allowed") 
      else 
        $log.debug "Access denied. User doesn't have role " + role
        deferred.reject("Denied")

    onValidateError = ->
      $log.debug "Access denied. User couldn't be validated"
      deferred.reject("Denied")

    $auth.validateUser({config: role}).then(onValidateSuccess, onValidateError)

    deferred.promise

  return {
    hasRole: hasRole
  }
)

And in the configs..

.config(($stateProvider) ->
  $stateProvider
    .state('admin', {
      url: '/admin'
      abstract: true
      template: '<div ui-view></div>'
      resolve: {
        auth: (AuthHelper) -> AuthHelper.hasRole('admin')
      }
    })