2016-06-09 91 views
1

我正在嘗試使用Angular,試圖設置由laravel後端(REST API)支持的Angular前端。對於身份驗證,我想使用json Web令牌。對於Angular,我使用Satellizer(https://github.com/sahat/satellizer)和Laravel JWT(https://github.com/tymondesigns/jwt-auth)。AngularJS身份驗證服務使用Satellizer和Laravel

目前,我已經可以使用存儲在Laravel中的正確證書通過AngularJS進行登錄。用戶信息和令牌存儲在localStorage中。

我想實現某種Angular服務,可以檢查用戶是否通過身份驗證,以保護狀態形成ui-router。我已經嘗試了幾次,但我無法使它工作。有人能指引我朝着正確的方向嗎?會很棒!

的LoginController(角)

.controller('loginCtrl', [ 
    '$scope', 
    '$rootScope', 
    'utils', 
    '$auth', 
    '$location', 
    'SweetAlert', 
    function ($scope,$rootScope,utils, $auth, $location, SweetAlert) { 


     $scope.login = function() { 

      var credentials = { 
       email:  $scope.email, 
       password: $scope.password 
      }; 

      $auth.login(credentials) 
       .then(function (response) { 
        var user = JSON.stringify(response.data.user); 
        localStorage.setItem('currentUser', user); 
        $location.path('/restricted.dashboard'); 
       }) 
       .catch(function (response) { 
        SweetAlert.swal("Inloggen mislukt.", "Controleer je email adres en wachtwood en probeer opnieuw.", "warning"); 
        console.log("LOGIN NOT OK" + response); 
       }); 
     }; 

app.states.js(UI-路由器,角)

.config([ 
    '$stateProvider', 
    '$urlRouterProvider', 
    function ($stateProvider, $urlRouterProvider) { 

     // Use $urlRouterProvider to configure any redirects (when) and invalid urls (otherwise). 
     $urlRouterProvider 
      .when('/dashboard', '/') 
      .otherwise('/'); 

     $stateProvider 
      .state("error.404", { 
       url: "/404", 
       templateUrl: 'app/componentsOld/pages/error_404View.html' 
      }) 
      .state("error.500", { 
       url: "/500", 
       templateUrl: 'app/componentsOld/pages/error_500View.html' 
      }) 

      // -- LOGIN PAGE -- 
      .state("login", { 
       url: "/login", 
       templateUrl: 'app/components/auth/loginView.html', 
       controller: 'loginCtrl', 
       resolve: { 

        deps: ['$ocLazyLoad', function ($ocLazyLoad) { 
         return $ocLazyLoad.load([ 
          'lazy_uikit', 
          'lazy_iCheck', 
          'app/components/auth/loginController.js', 
          'sweetAlert' 
         ]); 
        }] 
       } 
      }) 


      // -- RESTRICTED -- 
      .state("restricted", { 

       abstract: true, 
       url: "", 
       views: { 
        'main_header': { 
         templateUrl: 'app/shared/header/headerView.html', 
         controller: 'main_headerCtrl' 
        }, 
        'main_sidebar': { 
         templateUrl: 'app/shared/main_sidebar/main_sidebarView.html', 
         controller: 'main_sidebarCtrl' 
        }, 
        '': { 
         templateUrl: 'app/views/restricted.html' 
        } 
       }, 
       resolve: { 

        deps: ['$ocLazyLoad', function ($ocLazyLoad) { 
         return $ocLazyLoad.load([ 
          'lazy_uikit', 
          'lazy_selectizeJS', 
          'lazy_switchery', 
          'lazy_prismJS', 
          'lazy_autosize', 
          'lazy_iCheck', 
          'lazy_themes', 
          'lazy_style_switcher', 
          'sweetAlert' 
         ]); 
        }] 
       } 
      }) 

app.js(角)

.... 
// Satellizer configuration that specifies which API 
// route the JWT should be retrieved from 
$authProvider.loginUrl = 'zz/zz/laravel/public/api/authenticate'; 

// Redirect to the auth state if any other states 
// are requested other than users 
$urlRouterProvider.otherwise('/auth'); 
.... 

Laravel authenticateController(Laravel 5.2)

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

    try { 
     // verify the credentials and create a token for the user 
     if (!$token = JWTAuth::attempt($credentials)) { 
      return response()->json(['error' => 'invalid_credentials'], 401); 
     } 
    } catch (JWTException $e) { 
     // something went wrong 
     return response()->json(['error' => 'could_not_create_token'], 500); 
    } 
    $user = Auth::user(); 
    //$user->company; 
    //$street = $user->company->street; 
    // if no errors are encountered we can return a JWT 

    return response()->json([ 
     "token" => $token, 
     "user" => $user 
    ]); 

} 

什麼,我想做到的是創造角一個laravel中間件,使我們可以檢查是否有用戶進行身份驗證,並在未來他或她有權利用戶角色加載角度狀態。

感謝您抽出時間解決我的問題。我期待看到你將如何處理這個:)

回答

1

我發現這個解決方案的某個地方在一段時間以前,它適合我的需求(不能提供原始答案,信用原始答案)。我用$ routeProvider事件霍夫,我覺得你可以採用相同的邏輯與$ stateProvider

.config(function ($routeProvider) { 
    $routeProvider 
    .when('/awesomeRoute', { 
      templateUrl: 'views/view.tpl.html', 
      controller: 'someAwesomeCtrl', 
      controllerAs: 'someCtrl', 
      resolve : { 
        //This function is injected with the AuthService where you'll put your authentication logic 
        'auth' : function(AuthService){ 
         return AuthService.authenticate(); 
        } 


       } 
       }) 
     }) 

的驗證服務:

.factory('AuthService', function($q, Service, $window, $location){ 
      return { 
       authenticate : function(){ 
        //Authentication logic here, some service to check 
against backend if token you provided is valid and/or you are authorized to enter those sections of application, 
or in your case with satellizer you can use `$auth.isAuthenticated()` method. 

        Service.isTokenValid(_yourToken).then((res) => { 
         if(res.data === true){ 
         return true; 
         } else { 
         return $q.reject('Not Authenticated'); 
         } 
        }, (err) => { 
         $location.path('/'); 
         return $q.reject('Not Authenticated'); 
        }) 
        } else { 
        return $q.reject('Not Authenticated'); 
        } 
       } 
      }; 
     }) 

最後的「路線錯誤捕手」的時候,有什麼不對,返回首頁或/ auth路線

.run(function($rootScope, $location){ 
    //If the route change failed due to authentication error, redirect them out 
    $rootScope.$on('$routeChangeError', function(event, current, previous, rejection){ 
     if(rejection === 'Not Authenticated'){ 
      $location.path('/'); 
     } 
    }); 
    })