Created
July 21, 2023 16:49
-
-
Save johndwells/cadad15112c0aa5915e5590ad47f92d2 to your computer and use it in GitHub Desktop.
Refreshing Craft CSRF tokens using Unpoly
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 "unpoly"; | |
/** | |
* Helper to fetch user session info | |
* https://craftcms.com/docs/4.x/dev/controller-actions.html#ajax | |
*/ | |
const getSessionInfo = function() { | |
return fetch('/actions/users/session-info', { | |
headers: { | |
'Accept': 'application/json', | |
}, | |
}) | |
.then(response => response.json()); | |
}; | |
/** | |
* CSRF injection | |
* When any fragment is inserted into the DOM, query for any hidden CSRF inputs. | |
* If one or more found, get user session info via AJAX, and then update all inputs | |
* with the csrf token value contained in the response. | |
*/ | |
up.on('up:fragment:inserted', function(event, fragment) { | |
var inputs = fragment.querySelectorAll('[name=' + window.CSRF_TOKEN_NAME + ']'); | |
if( ! inputs) { | |
return; | |
} | |
try { | |
getSessionInfo() | |
.then(session => { | |
inputs.forEach(function(el) { | |
el.value = session.csrfTokenValue; | |
}); | |
}); | |
} catch (error) { | |
console.error('Error fetching 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
<script type="text/javascript"> | |
window.CSRF_TOKEN_NAME = '{{ craft.app.config.general.csrfTokenName|e('js') }}'; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment