With devise one uses before_filter :authenticate_user!
to restrict access to authenticated users only.
When an unauthenticated user tries to visit a restricted page anyways, devise automatically causes a redirect to the sign in page.
So trying to open http://localhost:3000/users/edit will result in a redirect to http://localhost:3000/users/sign_in.
Now, if I define the link http://localhost:3000/users/edit as :remote => true
, devise will only issue a 401 status code via JS.
How can I elegantly cope with that situation and display the login dialog in an overlay OR redirect as the non-remote variant would do it?
Does devise offer a default strategy for that situation which I'd simply need to activate?
This is the solution I chose for now (in CoffeeScript syntax):
$ ->
$("a").bind "ajax:error", (event, jqXHR, ajaxSettings, thrownError) ->
if jqXHR.status == 401 # thrownError is 'Unauthorized'
window.location.replace('/users/sign_in')
However this (on it's own) just forgets about the page the user wanted to visit initially, which confines usability.
Additional (controller) logic is required for more elegant handling.
UPDATE: correct redirect
Within the function, this
holds the initial URL the user intended to go to.
By calling window.location.replace(this)
(instead of explicitly redirecting to the sign in page), the app will try to redirect the user to the initially intended destination.
Although still impossible (unauthorized), this will now be a GET call (instead of JS/AJAX). Therefore Devise is able to kick in and redirect the user to the sign in page.
From there on, Devise operates as usual, forwarding the user to the originally intended URL after successful sign in.