2017-06-21 68 views
0

我正在開發一個使用Vue2,VueRouter和Laravel 5.4的項目。這是一個單頁面應用程序。用於API認證的Laravel Passport(來自我的Vue組件的AXIOS調用)。SPA,中間件和VueRouter

大多數應用程序從一個刀片文件(像這樣)服務:

<?php 
//styling and the like 
//... 
//components being loaded here 
<router-view></router-view> 

//pull in the app.js file with vue router instantiation and routes 
<script src="..."></script> 

所有組件和航線在app.js文件中定義的,就是在這個文件中拉出。

通過此刀片文件服務的組件都需要身份驗證;用戶必須登錄並註冊。

但是,應用程序將有一個頁面,非註冊用戶可以訪問該頁面。任何具有該URL的人都可以訪問該頁面;但是,在給予訪問頁面之前,他們需要輸入安全密碼。

該頁面基本上是用戶填寫並提交的表單。它還會事先從數據庫中提取一些數據,以在頁面上填充一些細節。

我還沒有着手做這種性質的任何事情,並且無法找到如何這樣做的例子。雖然我對如何解決這個問題有一些想法,但這是我的最佳猜測:

  1. 創建一個新的JS文件,它將託管一個新的路由器。
  2. 創建一個新的刀片文件,該文件將承載router-view element。它將拉入新創建的JS文件。
  3. 將新創建的刀片文件添加到web.php文件;創建中間件,該中間件將攔截任何嘗試訪問URL test/{id}。如果中間件檢查成功,並且用戶輸入有效的密碼,則中間件將傳遞請求以查看資源。否則,一個錯誤的重定向。

web.php文件:

//Route for those people who are taking a test 
Route::get('/test/{id}', '[email protected]'); 

//The authenticate view 
Route::get('/authenticate/{id}', '[email protected]') 
      ->name('authenticate') 
      ->middleware('auth.test'); 

測試控制器文件:

<?php 
namespace App\Http\Controllers; 
use Illuminate\Http\Request; 
use App\Test; 

class TestController extends Controller 
{ 
    public function serveTest(Request $request) { 
     return View('layouts.test'); 
    } 

    public function serveAuthenticate() { 
     return View('authenticate'); 
    } 
} 

中間件:

<?php 

namespace App\Http\Middleware; 

use Closure; 
use App\Test; 

class verifyTestAccess { 
    public function handle($request, Closure $next) { 
     //Calculate some conditions here 
     //... 

     //Direct user to the authentication view if some condition is true 
     if($hasPasscode) { 
      return redirect()->route('authenticate', ['id' => $request->route('id')]); 
     } 

     //Let user access resource since it must not be password protected 
     return $next($request); 
    } 
} 

新的刀片服務器文件:

<?php 
//Load the one component 
<router-view></router-view> 

//pull in the protectedPage.js file with vue router instantiation and routes 
//this is a different file than in the first blade view 
<script src="..."></script> 

這是一個很好的方法嗎?我想這種方法存在一些問題,並且創建一個vue-router來拉入一個組件是不理想的。

回答

1

最好的做法是分開前端和後端。由於您使用的是Laravel Passport,因此您將使用JWT從VueJS登錄用戶。

所以Laravel基本上將充當API,這意味着它不應該保持任何狀態。一切都將與的access_token檢查(產生,並通過API客戶端提供)

受限頁面

  • Laravel將有middlware檢查用戶是否可以檢索信息(使用令牌)
  • VueRouter將有一個導航警衛以防止用戶訪問受限制的頁面(可以通過檢查是否存在令牌或其他屬性)