Created
March 9, 2016 09:04
-
-
Save lapin-b/1ecb5df2d16bfed9f92a to your computer and use it in GitHub Desktop.
Spoofs a request method for RESTful controllers
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
function getRandomInt(min, max) { | |
return Math.floor(Math.random() * (max - min)) + min; | |
} | |
var links = document.querySelectorAll('a[data-method]'); | |
var csrf = document.querySelector('meta[name=csrf]').content; // Change if needed | |
var body = document.querySelector('body'); | |
// Spoof delete method | |
// USAGE: <a href="..." data-method="<method>">...</a> | |
Array.prototype.forEach.call(links, function(link){ | |
// Create form | |
var form_id = 'l-form-' + getRandomInt(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); | |
var form = document.createElement('form'); | |
form.id = form_id; | |
form.method = 'POST'; | |
form.action = link.href; | |
var csrf_token = document.createElement('input'); | |
csrf_token.name = '_token'; | |
csrf_token.type = 'hidden'; | |
csrf_token.value = csrf; | |
var method = document.createElement('input'); | |
method.name = '_method'; | |
method.type = 'hidden'; | |
method.value = link.getAttribute('data-method').toUpperCase(); | |
form.appendChild(csrf_token); | |
form.appendChild(method); | |
link.setAttribute('onclick', 'document.querySelector("#'+ form_id +'").submit(); return false;'); // Not the cleanest JS ever | |
body.appendChild(form); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment