使用Satellizer和Laravel

时间:2016-06-09 12:57:07

标签: angularjs laravel authentication jwt satellizer

我正在尝试使用Angular,尝试设置一个由laravel后端(REST API)驱动的Angular前端。对于身份验证,我想使用json web令牌。对于Angular,我使用Satellizer(https://github.com/sahat/satellizer)和Laravel JWT(https://github.com/tymondesigns/jwt-auth)。

目前,我已经可以使用存储在Laravel中的正确凭据登录AngularJS。用户信息和令牌存储在localStorage中。

我想实现某种Angular服务,可以检查用户是否经过身份验证,以保护ui-router状态。我已经尝试了几个但是我无法让它工作。有人能指出我正确的方向吗?太棒了!

loginController(Angular)

.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-router,Angular)

.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(Angular)

....
// 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
    ]);

}

我想要完成的是为Angular创建一个laravel Middleware,以便我们可以检查用户是否经过身份验证,并且将来他或她具有加载Angular状态的正确用户角色。

感谢您抽出时间解决我的问题。我很期待看到你如何处理这个:)

1 个答案:

答案 0 :(得分: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();
                  }


                 }
              })
        })

Auth服务:

 .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('/');
        }
    });
  })