2014-04-14 201 views
1

我想要做的是檢查某人是否在登錄時是否有cookie。當他們有我想重定向到$cookie_data/dashboard登錄成功後重定向+ Silex

因爲當您在我的服務器上選擇一種語言時,會設置一個cookie。所以我想將它們重定向到$language/dashboard

我現在有:

$app['security.authentication.success_handler.secured_area'] = $app->share(function() use ($app) { 
    $request = $app['request']; 
    $cookies = $request->cookies; 
    if($cookies->has("language")) 
    { 
     return $app->redirect('/nl/dashboard'); 
    } 
}); 

但是這給了我的錯誤:

Warning: array_map(): An error occurred while invoking the map callback in /Applications/MAMP/htdocs/pst/vendor/silex/silex/src/Silex/Provider/SecurityServiceProvider.php on line 264 

Fatal error: Uncaught exception 'RuntimeException' with message 'Accessed request service outside of request scope. Try moving that call to a before handler or controller.' in /Applications/MAMP/htdocs/pst/vendor/silex/silex/src/Silex/Application.php:141 Stack trace: #0 /Applications/MAMP/htdocs/pst/vendor/pimple/pimple/lib/Pimple.php(83): Silex\Application->Silex\{closure}(Object(Silex\Application)) #1 /Applications/MAMP/htdocs/pst/app/bootstrap.php(67): Pimple->offsetGet('request') #2 /Applications/MAMP/htdocs/pst/vendor/pimple/pimple/lib/Pimple.php(126): {closure}(Object(Silex\Application)) #3 /Applications/MAMP/htdocs/pst/vendor/pimple/pimple/lib/Pimple.php(83): Pimple::{closure}(Object(Silex\Application)) #4 /Applications/MAMP/htdocs/pst/vendor/silex/silex/src/Silex/Provider/SecurityServiceProvider.php(409): Pimple->offsetGet('security.authen...') #5 /Applications/MAMP/htdocs/pst/vendor/pimple/pimple/lib/Pimple.php(126): Silex\Provider\SecurityServiceProvider->Silex\Provider\{closure}(Object(Silex\Application)) #6 /A in /Applications/MAMP/htdocs/pst/vendor/silex/silex/src/Silex/Application.php on line 141 

我怎樣才能使這項工作或什麼是最好的做法是什麼?

回答

3

我不知道這是正確的,但我相信你必須回到另一個實例對象,見this question的細節(igorw特別的答案)

另一種選擇是攔截的的AUTHENTICATION_SUCCESS事件調度員,我試過如下:

$app['dispatcher']->addListener(AuthenticationEvents::AUTHENTICATION_SUCCESS 
     , function($authEvent) use ($app) { 
    $request = $app['request']; 
    $cookieKeys = $request->cookies->keys(); 
    $app['monolog']->addInfo('Available cookies are: ' . implode(', ', $cookieKeys)); 
    return $app->redirect('SOME_URL_HERE'); 
}); 

在日誌中我看到成功的餅乾,沒有任何錯誤,但重定向也不管用!檢查日誌(獨白)後,我看到了下面的路線被稱爲試圖訪問我的保護區域是/admin當:

  1. http://localhost:8888/silex-skeleton/web/index_dev.php/loginGET(重定向到登錄表單)
  2. http://localhost:8888/silex-skeleton/web/index_dev.php/admin/login_checkPOST (驗證)
  3. http://localhost:8888/silex-skeleton/web/index_dev.php/adminGET(重定向回最初請求的URL)

認證事件在中間的/login_check請求上被調用,返回不同的值對總體結果似乎沒有任何影響,至少我沒有設法做到這一點。我想知道的是爲什麼不在你的ROUTE HANDLER函數中重定向?結果將是一樣的,至少如果我正確地理解了這個問題。例如,將您的代碼放在安全區域的處理程序中,如:

$app->get('/dashboard', function() use ($app) { 
    $request = $app['request']; 
    $cookies = $request->cookies; 
    if($cookies->has("language")) 
    { 
     return $app->redirect('/nl/dashboard'); 
    } 
    return new Response(.....) 
});