I think you should better check is the user doesn't have the anonymous role.
if ($app['security']->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
// do action while the user isn't logged in
}
Question
When I log in and show no actions for two hours I will automatically log out. But when I refresh the page I get the error that Silex can't find the attribute displayName on a null attribute. Because in my layout view I have: {{ app.user.displayName }}
.
Now I would like to check in my $app->before if someone is logged in, and if not redirect to root. This is what I have now:
$app->before(function (Request $request) use($app) {
if ($request->getMethod() === "OPTIONS") {
$response = new Response();
$response->headers->set("Access-Control-Allow-Origin","*");
$response->headers->set("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
$response->headers->set("Access-Control-Allow-Headers","Content-Type");
$response->headers->set("Access-Control-Expose-Headers","handshake");
$response->setStatusCode(200);
$response->send();
}
$token = $app['security']->getToken();
if (null === $token) {
die;
}
});
The problem is that it's never null, also when I'm not logged in. I've made a dump from the $token variable from when I'm not logged in and I get this:
object(Symfony\Component\Security\Core\Authentication\Token\AnonymousToken)#525 (5) {
["key":"Symfony\Component\Security\Core\Authentication\Token\AnonymousToken":private] => string(12) "secured_area"
["user":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private] => string(5) "anon."
["roles":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private] => array(0) { }
["authenticated":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private] => bool(true)
["attributes":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private] => array(0) { }
}
My login route is defined like this:
$controllers->get('/', 'user.controller:loginAction')
->bind('user.login');
How can I redirect to that route?
Solution
I think you should better check is the user doesn't have the anonymous role.
if ($app['security']->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) {
// do action while the user isn't logged in
}
OTHER TIPS
Try:
if(null == $app['security']->getToken()->getUser()){
die;
}
Really you shouldnt use die though. You should redirect or throw some exception. But for debugging die is fine.
Not a symphony user, but i imagine the following will work:
if ($token->user=='anon') {
die;
}