diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 56e3de4..eade67f 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -22,7 +22,7 @@ def require_user if current_user cookies.encrypted[:user_id] = current_user&.id else - redirect_to root_path + redirect_to root_path, status: :unauthorized end end end diff --git a/app/javascript/controllers/chat_controller.js b/app/javascript/controllers/chat_controller.js index 1c41aa0..5ab1ef5 100644 --- a/app/javascript/controllers/chat_controller.js +++ b/app/javascript/controllers/chat_controller.js @@ -6,7 +6,7 @@ export default class extends ApplicationController { console.log('Chat controller connected', this.element) this.element.focus() var submitButton = document.getElementById('prompt_submit') - if(submitButton) { + if (submitButton) { submitButton.addEventListener('click', this.prompt.bind(this)) } } @@ -17,7 +17,7 @@ export default class extends ApplicationController { } keydown(event) { - if(event.keyCode === 13) { + if (event.keyCode === 13) { if (event.metaKey || (!this.element.dataset.grow && !event.shiftKey)) { event.preventDefault(); this.prompt(event) @@ -29,7 +29,28 @@ export default class extends ApplicationController { if (this.element.value.length === 0) { return; } - this.stimulate('ChatReflex#prompt') + + const xhr = new XMLHttpRequest(); + xhr.open("GET", "/chats"); + xhr.setRequestHeader("Content-Type", "application/json"); + + const token = document.head.querySelector( + 'meta[name="csrf-token"]' + ).content; + + xhr.setRequestHeader("X-CSRF-Token", token); + + xhr.onreadystatechange = () => { + if (xhr.readyState === XMLHttpRequest.DONE) { + if (xhr.status === 200) { + this.stimulate('ChatReflex#prompt'); + } else if (xhr.status === 401) { + window.location.href = "/"; + } + } + }; + + xhr.send(); } beforePrompt(element, reflex, noop, reflexId) {