I am using the codeigniter framework and I am trying to implement the tankauth authentication. It works well for regular pages. In the __construct of the controller, I put the
if (!authenticated) { redirect('auth'); }
there so that it protects all of the functions in the controller. This works fine if the user’s credentials time out and they try to load a new page, it just redirects them to the auth page so they can login again. However, I get an infinite loop if the function in the controller is called via ajax. I assume because it is trying to send the redirect headers when the page is already loaded.
What is the correct way to protect ajax calls and redirect the user to the auth page when someone who is no logged in tries to call the function?
Thanks!
I am not familiar with tankauth in general, so there may be a better way, but in general, instead of calling the redirect from the controller, you need to return a message (e.g. in JSON) and then terminate the script, rather than redirecting.
The client side Javascript that made the Ajax call, then checks the response and if it indicates the user was logged out, use javascript to redirect to the login (
window.location). If you send a redirect on a page that was requested via Ajax, it doesn’t cause the browser to redirect, the Ajax call simply follows the redirect and the result of the Ajax call is whatever HTML your login page returns.So it might look like this:
The the Javascript checks to see if the response contains an
errorkey, and if it isloggedout, it should redirect the user’s browser to your login page.