2017-08-03 19 views
0
  • ジャンゴ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に必要な重要な手順がありません。

とにかく、私は2つのURLを持っている:

/

/dashboard

前者はログインが/dashboardが認証を必要とし、/へのルートは、人がログインしていないかどうかを、である前に、I。これを実装しようとすると、認証されずに/dashboardと入力するだけでそれを見ることができます。私は、DRF-JWTを介してトークンにログインすると、成功したログイン時に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

まあ、私のために働いているようだが、ややシンプルな解決策を見つけた。それにはいくつかの問題がある可能性があるので、これをやらない理由についてのフィードバックは非常に高く評価されます。 '/''/dashboard'

私はかなり繰り返しますが、私は実際には2つのURLを持っているなど

インターセプタ、サービスを、不時着します。前者はログインであり、後者はユーザーが利用できるすべてのツール(最終的には数十のツール)ですが、親の子ビューである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を移動しようと、それはルートあなたの意志

  • // 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にルーティングされている場合、ログイン画面に

  • を入力すると、URLに/dashboardと入力できますあなたがログアウトした場合、それは
  • 、それはあなたがそれを入力するか、それは私が考えている、直接サブビューへのアクセスを許可していません
  • ブラウザの[戻る]ボタンを押すことで/dashboardを表示することはできませんisplaysはちょうどルーティングによるものです:親ビューができない場合、サブビューはレンダリングできません。

とにかく、フィードバックは非常に高く評価されます。

EDIT:これは私がコピーしているプロジェクトとどれほど似ているかを認識しますが、インターセプタの代わりにダッシュボードコンポーネントに入れています。

関連する問題