56 lines
1.8 KiB
JavaScript
56 lines
1.8 KiB
JavaScript
// app/javascript/controllers/logout_controller.js
|
|
import { Controller } from "@hotwired/stimulus";
|
|
|
|
export default class extends Controller {
|
|
static values = {
|
|
url: String,
|
|
};
|
|
|
|
connect() {
|
|
// Optional: Add confirmation message
|
|
//console.log("Hello LogoutController, Stimulus!", this.element);
|
|
// this.element.dataset.confirm = "Êtes-vous sûr de vouloir vous déconnecter ?";
|
|
}
|
|
|
|
signOut(event) {
|
|
event.preventDefault();
|
|
console.log("LogoutController#signOut mounted");
|
|
|
|
// Ensure user wants to disconnect with a confirmation request
|
|
// if (this.hasUrlValue && !confirm(this.element.dataset.confirm)) { return; }
|
|
|
|
// Retrieve the csrf token from header
|
|
const csrfToken = document.querySelector("[name='csrf-token']").content;
|
|
|
|
// Define url to redirect user when action is valid
|
|
const url = this.hasUrlValue ? this.urlValue : this.element.href;
|
|
|
|
// Use fetch to send logout request
|
|
fetch(url, {
|
|
method: "DELETE",
|
|
headers: {
|
|
"X-CSRF-Token": csrfToken,
|
|
Accept: "application/json",
|
|
"Content-Type": "application/json",
|
|
},
|
|
credentials: "same-origin",
|
|
})
|
|
.then((response) => {
|
|
// console.log(this.element.dataset.loginUrlValue); // By default, we does not return anything.
|
|
|
|
// By default the response does not include any url.
|
|
// Redirect to default login page (loginUrlValue)
|
|
if (response.redirected) {
|
|
window.location.href = response.url;
|
|
} else if (this.element.dataset.loginUrlValue) {
|
|
window.location.href = this.element.dataset.loginUrlValue;
|
|
return;
|
|
}
|
|
window.location.href = "/";
|
|
})
|
|
.catch((error) => {
|
|
console.error("Error during sign out:", error);
|
|
});
|
|
}
|
|
}
|