2016-01-27 2 views
0

Я хотел бы иметь возможность добавлять роль пользователя в раздел Полезной нагрузки JWT с использованием Satellizer, так что я могу получить доступ к нему через $ rootScope через мою страницуSatellizer JWT маркер добавить пользователь информации в полезную нагрузку

это мой контроллер Auth

function() { 

'use strict'; 

angular 
    .module('app') 
    .controller('AuthController', AuthController); 


function AuthController($auth, $state, $http, $rootScope) { 

    var vm = this; 
    vm.loginErrorText; 

    vm.login = function() { 

     var credentials = { 
      email: vm.email, 
      password: vm.password 
     } 

     // Use Satellizer's $auth service to login 
     $auth.login(credentials).then(function(data) { 

      return $http.get('api/authenticate/user'); 


     }).catch(function(response) { 

       vm.loginErrorText = response.statusText 

     }).then(function(response){ 

      // Stringify the returned data to prepare it 
      // to go into local storage 
      var user = JSON.stringify(response.data.user); 

      // Set the stringified user data into local storage 
      localStorage.setItem('user', user); 

      // The user's authenticated state gets flipped to 
      // true so we can now show parts of the UI that rely 
      // on the user being logged in 
      $rootScope.authenticated = true; 

      // Putting the user's data on $rootScope allows 
      // us to access it anywhere across the app 
      $rootScope.currentUser = response.data.user; 

      // Everything worked out so we can now redirect to 
      // the users state to view the data 
      console.log(response.data.user.role); 
      $state.go('dashboard');     
     }); 
    } 

} 

})(); 

и здесь выполняется метод на который проверяет для роли пользователя, я могу получить доступ к идентификатор пользователя через суб, но есть ли способ я могу передать рулон пользователя в JWT полезной нагрузки секции?

.run(function($rootScope, $state, $auth) { 

     $rootScope.$on('$stateChangeStart', function(event, toState) { 

      // Grab the user from local storage and parse it to an object 
      var user = JSON.parse(localStorage.getItem('user')); 


      if(user) { 

       // The user's authenticated state gets flipped to 
       // true so we can now show parts of the UI that rely 
       // on the user being logged in 
       $rootScope.authenticated = true; 

       // Putting the user's data on $rootScope allows 
       // us to access it anywhere across the app. Here 
       // we are grabbing what is in local storage 
       $rootScope.currentUser = user; 

       //getting user ID from JWT 
       console.log('Payload : ' + $auth.getPayload().sub); 

       // If the user is logged in and we hit the auth route we don't need 
       // to stay there and can send the user to the main state 
       if(toState.name === "login") { 

        // Preventing the default behavior allows us to use $state.go 
        // to change states 
        event.preventDefault(); 

        // go to the "main" state which in our case is users 
        $state.go('dashboard'); 
       }  
      } 
     }); 
    }); 

ответ

0

Полезная нагрузка определяется в конце (Laravel). Я предполагаю, что вы следуете этому руководству http://ryanchenkie.com/token-based-authentication-for-angularjs-and-laravel-apps/. В AuthenticateController, вместо:

//AuthenticateController.php 
    public function authenticate(Request $request) 
    { 
     $credentials = $request->only('email', 'password'); 

     try { 
      if (! $token = JWTAuth::attempt($credentials)) { 
       return response()->json(['error' => 'invalid_credentials'], 401); 
      } 
    ... 

Я использую:

//AuthenticateController.php 
    public function authenticate(Request $request) 
    { 
     $credentials = $request->only('email', 'password');  
     try{ 
      if (! \Auth::once($credentials)){     
        return response()->json(['error' => 'invalid_credentials'], 401); 
       }else{ 
        $user = \Auth::user(); 
        $customClaims = ['utype' => $user->getUserType()]; 
        $token = JWTAuth::fromUser($user, $customClaims); 
       } 
    ... 

Таким образом, вы должны определить getUserType() в классе модели (User.php), или получить UserType непосредственно из объект $ user в AuthenticateController. Затем используйте JWTAuth :: fromUser, как описано в разделе «Создание токена на основе объекта пользователя» от https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens.