2017-08-03 69 views
0
  • Django的1.11
  • Django的REST框架(DRF)3.6
  • DRF-JWT 1.10
  • AngularJS 1.6.5
  • UI路由器保護的頁面時工作1.0.3

對於所有這些技術來說都是新鮮事物,並且已經爲這個問題困擾了好幾天了。得知這個堆棧(減UI路由器,我只是切換到一個星期前)通過下面的類和資源庫:試圖讓需要登錄試圖訪問

https://www.udemy.com/django-angularjs/learn/v4/overview

https://github.com/codingforentrepreneurs/Django-AngularJS/tree/master/src

這些是可能是最相關的目錄我的問題:

配置和JS:https://github.com/codingforentrepreneurs/Django-AngularJS/tree/master/src/static/js/app

登錄,需要攔截:https://github.com/codingforentrepreneurs/Django-AngularJS/tree/master/src/static/js/app/core/interceptors

服務,在需要登錄,並攔截網頁被利用:https://github.com/codingforentrepreneurs/Django-AngularJS/tree/master/src/static/js/app/core/comment

我試圖適應它爲我的項目。

我已經閱讀了純粹爲此目的而使用ui-router的幾個教程,但他們似乎沒有使用DRF-JWT或缺少像我這樣的newb需要的重要步驟。

無論如何,我有兩個網址:

/

/dashboard

前者是登錄,/dashboard需要授權,並應以/途徑,如果這個人是不是在登錄之前我。開始試圖實現這一點,只需鍵入/dashboard而不需要進行身份驗證並查看它。我已經證實,當一個人通過DRF-JWT登錄令牌時,它會被生成並寫入cookie,因爲我可以在成功登錄時使用console.log

由於我一直在試圖實現這一點,我甚至不能得到/加載。我收到了我無法解決的$injector:modulerr問題。

代碼時間:

我得到$injector:modulerr一次我改變:

// dashboard.module.js 

angular.module('dashboard', ['chart.js']); 

// dashboard.module.js 

angular.module('dashboard', ['chart.js', 'interceptors']); 

其他必要的JS:

// login_required.service.js 

'use strict'; 

angular. 
    module('interceptors'). 
     factory('LoginRequiredInterceptor', function($cookies, $location) { 
      return function(response) { 
       console.log('working') 
       console.log('interceptor error') 
       console.log(response) 
       if (response.status == 401){ 
        var currentPath = $location.path(); 
        console.log(currentPath) 
        if (currentPath == '/') { 
         $location.path('/') 
        } else { 
         $location.path('/').search('next', currentPath) 
        } 
       } 
      } 
     }) 

-

// interceptors.module.js 

'use strict'; 

angular.module('interceptors', ['ngCookies']); 

-

// dashboard.component.js 

'use strict'; 

angular.module('dashboard'). 
    component('dashboard', { 
     templateUrl: '/api/templates/dashboard.html', 
     controller: function($cookies, $location, $stateParams, $rootScope, $scope) { 
      // Nothing at this point 
     } 
    }); 

真的沒有更新下面從我克隆它從上面的項目:

// dashboard.service.js 

'use strict'; 

angular. 
    module('dashboard'). 
     factory('Dashboard', function(LoginRequiredInterceptor, $cookies, $httpParamSerializer, $location, $resource){ 

      var token = $cookies.get("token") 
      if (token){ 
       commentCreate["headers"] = {"Authorization": "JWT " + token} 
       commentDelete["headers"] = {"Authorization": "JWT " + token} 
       commentUpdate["headers"] = {"Authorization": "JWT " + token} 
      } 

      return $resource(url, {}, { 
       query: commentQuery, 
       get: commentGet, 
       create: commentCreate, 
       delete: commentDelete, 
       update: commentUpdate, 
      }) 

     }); 

最後,主要配置:

// app.config.js 

'use strict'; 

angular.module('app'). 
    config(
     function(
      $locationProvider, 
      $resourceProvider, 
      $stateProvider, 
      $urlRouterProvider, 
      $authProvider 
      ) { 

      // Enable HTML5 mode 
      $locationProvider.html5Mode({ 
       enabled:true 
      }) 

      // Remove trailing slashes to avoid API issues 
      $resourceProvider.defaults.stripTrailingSlashes = false; 

      // Route handling if the URL does not match any of the below 
      // it will send the user to the login screen 
      $urlRouterProvider.otherwise('/'); 

      $stateProvider 
       // The top URL (app/) is the login screen 
       .state('/', { 
        url: '/', 
        views: { 
         '[email protected]': { 
          component: 'login' 
         } 
        } 
       }) 

       // Logout and reroute to the login screen 
       .state('logout', { 
        redirectTo: '/' 
       }) 

       // After successful login, the user is brought to the dashboard 
       // Parent of the states below it 
       .state('dashboard', { 
        url: '/dashboard', 
        views: { 
         '[email protected]': { 
          component: 'dashboard' 
         } 
        }, 
       }) 

       // Test State1 
       .state('dashboard.test1', { 
        views: { 
         '[email protected]': { 
          template: '<p style="position: absolute;top: 110%; left: 50%">Test1</p>' 
         } 
        } 
       }) 

       // Test State2 
       .state('dashboard.test2', { 
        views: { 
         '[email protected]': { 
          template: '<p style="position: absolute;top: 50%; left: 50%">Test2</p>' 
         } 
        } 
       }) 
    }); 

另外,<scripts>我正在閱讀(在t他下我<body>標籤):

<!-- base.html --> 

<!-- Angular 1.x and Bootstrap UI libraries --> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js" integrity="sha256-zBy1l2WBAh2vPF8rnjFMUXujsfkKjya0Jy5j6yKj0+Q=" crossorigin="anonymous"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-cookies.min.js" integrity="sha256-tVvnbUkwgprwLlmcKyx6/dz+KifqSSJ41vvUGvL72QM=" crossorigin="anonymous"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-resource.min.js" integrity="sha256-J9EYt6krcoClMPGCdI0BA5vhMVHU/lu9vSnhbx0vfAI=" crossorigin="anonymous"></script> 
<!-- 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.min.js" integrity="sha256-E6XubcgT4a601977ZZP4Yw/0UCB2/Ex+Bazst+JRw1U=" crossorigin="anonymous"></script> 
--> 

<!-- UI libraries --> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.js" integrity="sha256-w3THDDhkzdjMczax74BBlkhjBxWIGisjArsP5wIQSHc=" crossorigin="anonymous"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js" integrity="sha256-tyfWW2LtJQNI+l3F0h6xDV/ij6Mfn8lwSKHWOsmEgXM=" crossorigin="anonymous"></script> 

<!-- Misc 3rd Part Libraries --> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/satellizer/0.14.1/satellizer.min.js" integrity="sha256-pcZRGEYkbl74zjS+YusQRvVWoFcwZTHLjmDCvbdX2ec=" crossorigin="anonymous"></script> 

<!-- Chart related libraries --> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js" integrity="sha256-SiHXR50l06UwJvHhFY4e5vzwq75vEHH+8fFNpkXePr0=" crossorigin="anonymous"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-chart.js/1.1.1/angular-chart.min.js" integrity="sha256-ydmVOl8gRR1E4yD1OC/aQdLNPCIKXSHIpl9yOu8EWek=" crossorigin="anonymous"></script> 

<!-- Core application settings --> 
<script src='{% static "js/app.module.js" %}' ></script> 
<script src='{% static "js/app.config.js" %}' ></script> 

<!-- Global application components --> 
<script src='{% static "js/navbar/navbar.module.js" %}' ></script> 
<script src='{% static "js/navbar/navbar.directive.js" %}' ></script> 
<script src='{% static "js/sidebar/sidebar.module.js" %}' ></script> 
<script src='{% static "js/sidebar/sidebar.directive.js" %}' ></script> 

<!-- Page specific application componenets --> 
<script src='{% static "js/login/login.module.js" %}' ></script> 
<script src='{% static "js/login/login.component.js" %}' ></script> 
<script src='{% static "js/dashboard/dashboard.module.js" %}' ></script> 
<script src='{% static "js/dashboard/dashboard.component.js" %}' ></script> 

讓我知道你什麼都將是有益的。

回答

0

嗯,我找到了一個解決方案,似乎爲我工作,而且很簡單。可能有幾個問題,所以爲什麼不這樣做的反饋將不勝感激。

我幾乎拋棄了攔截,服務等

同樣,我真的只有2個網址:'/''/dashboard'。前者是登錄名,後者是用戶可以使用的所有工具(最終是幾十個工具),但是它們將是父代dashboard的子視圖。您可以從這裏開始看到:

// app.config.js 

'use strict'; 

angular.module('app'). 
    config(
     function(
      $locationProvider, 
      $resourceProvider, 
      $stateProvider, 
      $urlRouterProvider, 
      $authProvider 
      ) { 

      // Enable HTML5 mode 
      $locationProvider.html5Mode({ 
       enabled:true 
      }) 

      // Remove trailing slashes to avoid API issues 
      $resourceProvider.defaults.stripTrailingSlashes = false; 

      // Route handling if the URL does not match any of the below 
      // it will send the user to the login screen 
      $urlRouterProvider.otherwise('/'); 

      $stateProvider 
       // The top URL (app/) is the login screen 
       .state('/', { 
        url: '/', 
        views: { 
         '[email protected]': { 
          component: 'login' 
         } 
        } 
       }) 

       // Logout and reroute to the login screen 
       .state('logout', { 
        redirectTo: '/' 
       }) 

       // After successful login, the user is brought to the dashboard 
       // Parent of the states below it 
       .state('dashboard', { 
        url: '/dashboard', 
        views: { 
         '[email protected]': { 
          component: 'dashboard' 
         } 
        }, 
       }) 

       // Test child State1 
       .state('dashboard.test1', { 
        views: { 
         '[email protected]': { 
          template: '<p style="position: absolute;top: 110%; left: 50%">Test1</p>' 
         } 
        } 
       }) 

       // Test child State2 
       .state('dashboard.test2', { 
        views: { 
         '[email protected]': { 
          template: '<p style="position: absolute;top: 50%; left: 50%">Test2</p>' 
         } 
        } 
       }) 
    }); 

以下是將JWT令牌寫入cookie的登錄名。

// login.component.js 

'use strict'; 

angular.module('login'). 
    component('login', { 
     templateUrl: 'api/templates/login.html', 
     controller: function($cookies, $http, $location, $stateParams, $rootScope, $scope) { 
      var loginUrl = 'api/users/login/' 
      $scope.loginError = {} 
      $scope.user = {} 

      $scope.$watch(function() { 
       if ($scope.user.password) { 
        $scope.loginError.password = '' 
       } else if ($scope.user.username) { 
        $scope.loginError.username = '' 
       } 
      }) 

      var tokenExists = $cookies.get('token') 
      if (tokenExists) { 
       // verify token 
       $scope.loggedIn = true; 
       $cookies.remove('token') 
       $scope.user = { 
        username: $cookies.get('username') 
       } 
       // window.location.reload() 
      } 

      // Main login handling for user 
      $scope.doLogin = function(user) { 
       // console.log(user) 
       if (!user.username) { 
        $scope.loginError.username = ['This field may not be blank.'] 
       } 

       if (!user.password) { 
        $scope.loginError.password = ['This field is required.'] 
       } 

       // If both the username and the password are supplied then POST it to the login API URL 
       if (user.username && user.password) { 
        $http({ 
         method: 'POST', 
         url: loginUrl, 
         data: { 
          username: user.username, 
          password: user.password        
         }, 
         headers: {} 
        }).then(function successCallback(r_data, r_status, r_headers, r_config) { 
         // console.log(r_data.data) 
         $cookies.put('token', r_data.data.token) 
         $cookies.put('username', r_data.data.username) 
         var token = $cookies.get('token') 
         // console.log(token) 

         $location.path('/dashboard') 
         // window.location.reload()      
        }, function errorCallback(e_data, e_status, e_headers, e_config) { 
         // Check if this is a 400 error which is related to an invalid password 
         if (e_data.status == 400) { 
          $scope.loginError.invalid = ['The credentials entered are invalid.'] 
         } 
        })  
       } 
      } 
     } 
    }) 

那麼對於儀表盤我只是做了以下內容:

// dashboard.component.js 

'use strict'; 

angular.module('dashboard'). 
    component('dashboard', { 
     templateUrl: '/api/templates/dashboard.html', 
     controller: function($cookies, $location, $stateParams, $rootScope, $scope) { 
      var token = $cookies.get('token') 
      console.log(token) 
      if (token) { 
       $location.path('/dashboard') 
      } else { 
       $location.path('/') 
      } 
     } 
    }); 

看來工作我如何指望它:

  • ,如果你嘗試去/dashboard它就會經過登錄屏幕
  • 如果您登錄並路由到/dashboard您可以輸入/dashboard到該URL並且它d isplays它
  • ,如果你退出,它不會讓你在打字,或打在瀏覽器的後退按鈕
  • 它不允許訪問子視圖直接,我想查看/dashboard僅僅是由於路由:如果父視圖不能呈現,則不能呈現子視圖。

無論如何,反饋將不勝感激。

編輯:實現與我正在複製的項目有多相似,但不是攔截器,而是將其放在儀表板組件中。