2014-04-14 70 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(.....) 
});