2017-09-26 61 views
4

我正在構建一個名爲under-construction的包。當該配置文件在配置文件 中被激活時,該網站將被構建,只有擁有正確代碼的人才能訪問 應用程序。Laravel包會話變量不保存與ajax調用

https://github.com/larsjanssen6/underconstruction

,我現在所擁有的問題:

當輸入的代碼,我做的Ajax調用襲擊的這種控制方法(稱爲檢查):

https://github.com/larsjanssen6/underconstruction/blob/master/src/Controllers/CodeController.php

如果代碼是正確的會話變量被設置:

session(['can_visit' => true]); 

然後在我的vue.js代碼我重定向到/。它會再次打我的中間件。在這裏我檢查是否存在一個名爲can_visit的會話。

return session()->has('can_visit'); 

https://github.com/larsjanssen6/underconstruction/blob/master/src/UnderConstruction.php

但是會話變量can_visit總是不見了!這怎麼可能?

感謝您的時間。

+1

檢查是否調用了中間件「web」。其初始化會話的中間件 –

+0

是的路由在web.php中,因此他們使用網絡中間件。 – Jenssen

回答

2

您沒有加載會話中間件,因此會話未啓動且沒有值持續存在。

正如在評論中指出的,即使你的保護路由(/)是網絡中間件(讀會話),服務供應商的路由(/under/construction/under/check)不(不寫會話)內。

簡單的修復方法是添加會話,甚至更好的是整個web中間件。

$routeConfig = [ 
    'namespace' => 'LarsJanssen\UnderConstruction\Controllers', 
    'prefix' => 'under', 
    'middleware' => [ 
     'web', // add this 
     // DebugbarEnabled::class, // leaving this dead code behind despite vcs 
    ], 
]; 

然而,如果用戶將您的中間件到他們的Web中間件組無限循環重定向你可能會很快遇到麻煩。所以我會添加一些支票,以確保您不在現有的underconstruction路線之一。

public function handle($request, Closure $next) 
{ 
    // check this isn't one of our routes 
    // too bad router hasn't loaded named routes at this stage in pipeline yet :(
    // let's hope it doesn't conflict with user's routes 
    if ($request->is('under/*')) { 
     return $next($request); 
    } 

    if (! $this->config['enabled']) { 
     return $next($request); 
    } 

    if (!$this->hasAccess($request)) { 
     return new RedirectResponse('/under/construction'); 
    } 

    return $next($request); 
} 

最終從這個項目的背景猜測,我希望大多數人會想要堅持這個全球中間件。但是,您將遇到同一個會話 - 尚未開始 - 但仍然存在問題,因爲這不會在全局中間件中運行。所以還有更多要咀嚼。快樂的編碼!

+0

非常感謝您的時間。真的很感激它!最後在做了大量的研究之後得到一個解決方案。 – Jenssen