Last active
April 24, 2024 20:17
-
-
Save noahd1/8210adff1021a22336331ecc38939462 to your computer and use it in GitHub Desktop.
csrf_refresh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller } from "@hotwired/stimulus" | |
export default class extends Controller { | |
static values = { | |
wait: Number | |
} | |
connect() { | |
this.refresh = this.debounce(this.refreshNoBounce, this.waitValue || 500); // Default wait time of 500ms if not specified | |
} | |
debounce = (func, wait) => { | |
let timeout; | |
return (...args) => { | |
clearTimeout(timeout); | |
timeout = setTimeout(() => { | |
func.apply(this, args); | |
}, wait); | |
}; | |
} | |
refreshNoBounce = () => { | |
fetch('/refresh_csrf', { | |
method: 'GET', | |
credentials: 'include', | |
headers: { | |
'Accept': 'application/json' | |
} | |
}) | |
.then(response => response.json()) | |
.then(data => { | |
document.querySelector('meta[name="csrf-token"]').setAttribute('content', data.csrf); | |
document.querySelectorAll('input[name="authenticity_token"]').forEach((el) => { | |
el.value = data.csrf; | |
}); | |
}) | |
.catch(error => console.error('Error refreshing CSRF token:', error)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CsrfController < ActionController::Base | |
def refresh | |
render json: { csrf: form_authenticity_token } | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body data-controller="csrf" data-action="focus@window->csrf#refresh"> | |
</body> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rails.application.routes.draw do | |
# ... | |
get '/refresh_csrf', to: 'csrf#refresh' | |
# ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment