Using Symfony2 I have implemented an AJAX action to manage some bookmarks (add/remove) in my application. So a user needs to be authenticated to proceed. I have a solution that redirects user to login page but I think it would be better to use an event to handle this redirection.
Actual solution :
Check of user's authentication is done the same way that in FOSUserBundle.
Routing :
fbn_guide_manage_bookmark:
path: /bookmark/manage
defaults: { _controller: FBNGuideBundle:Guide:managebookmark }
options:
expose: true
requirements:
_method: POST
Controller :
public function manageBookmarkAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
return new JsonResponse(array('status' => 'login'));
}
// DO THE STUFF
}
}
jQuery :
$(function() {
$('#bookmark').click(function() {
$.ajax({
type: 'POST',
url: Routing.generate('fbn_guide_manage_bookmark'),
data : xxxx, // SOME DATA
success: function(data) {
if (data.status == 'login') {
var redirect = Routing.generate('fos_user_security_login');
window.location.replace(redirect);
} else {
// DO THE STUFF
}
},
});
});
});
Other solution ? :
In order not verify at controller level that user is authenticated, I would protect my route in security configuration file :
Security :
security:
access_control:
- { path: ^/(fr|en)/bookmark/manage, role: ROLE_USER }
Controller :
public function manageBookmarkAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
$user = $this->getUser();
// THIS VERIFCATION SHOULD NOW BE REMOVED
/*
if (!is_object($user) || !$user instanceof UserInterface) {
return new JsonResponse(array('status' => 'login'));
}
*/
// DO THE STUFF
}
}
Basically, when trying this solution, Symfony2 redirects internally ton login page as you can see with Firebug :
So my questions are :
- Does Symfony2 throws an event or an exception before redirection ? This would permits to use a listener to catch the event and set a JSON response for example ?
- In this case, what kind of response should be prepared ? Something like my first solution of something using a HTTP header code like 302 (or something else). How to handle this at AJAX level ?
I could see some exception event solution based but I think it is necessary to throw the exception at controller level and this is what I would like to avoid. Here is an example :