js: redirect to sign-in when a ujs link_to receives a 401

Before, when a 401 was received by a ujs-enabled link (like `link_to …,
method: :delete, data: { remote: true }`, rails-ujs tried to insert the
response text as a Javascript script.

As the script was something like `Please sign-in`, which is not valid
Javascript, the browser would throw an "Unexpected token" error.

The typical use-case is:

1. The user open a form in a tab,
2. The user disconnects in another tab,
3. In the first tab, the user clicks on a remote "Delete" link_to

In that case the browser raised an error in the console (and in Sentry),
but the user would see nothing.

With this commit, all 401 ujs errors are turned into redirects to the
sign-in page.

Fix 2522512693/activity/
This commit is contained in:
Pierre de La Morinerie 2021-09-07 21:18:17 +00:00
parent 1f7c4422b5
commit 8dce7d59ed
2 changed files with 9 additions and 0 deletions

View file

@ -11,6 +11,7 @@ import '../shared/safari-11-file-xhr-workaround';
import '../shared/remote-input';
import '../shared/franceconnect';
import '../shared/toggle-target';
import '../shared/ujs-error-handling';
import '../new_design/chartkick';
import '../new_design/dropdown';

View file

@ -0,0 +1,8 @@
// For links and requests done through rails-ujs (mostly data-remote links),
// redirect to the sign-in page when the server responds '401 Unauthorized'.
document.body.addEventListener('ajax:error', (event) => {
const [, , xhr] = event.detail;
if (xhr && xhr.status == 401) {
location.reload(); // reload whole page so Devise will redirect to sign-in
}
});