58 lines
1.8 KiB
JavaScript
Executable File
58 lines
1.8 KiB
JavaScript
Executable File
import { Controller } from "@hotwired/stimulus";
|
|
|
|
export default class extends Controller {
|
|
static values = {
|
|
url: String,
|
|
};
|
|
|
|
connect() {
|
|
// Display a message when the controller is mounted
|
|
console.log("LogoutController mounted", this.element);
|
|
}
|
|
|
|
signOut(event) {
|
|
event.preventDefault();
|
|
console.log("User clicked on logout button.");
|
|
|
|
// 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
|
|
let url = this.hasUrlValue ? this.urlValue : this.element.href;
|
|
// Ensure the URL is using the correct path prefix
|
|
if (url && !url.includes('/auth/sign_out')) {
|
|
url = url.replace('/users/sign_out', '/auth/sign_out');
|
|
}
|
|
|
|
// 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);
|
|
});
|
|
}
|
|
}
|