Skip to content

Commit cdf167d

Browse files
committed
Added wrapper to submit method for HTMLFormElements
form.submit() calls were not being intersepted by the library. Added a wrapper method to deal with it.
1 parent 6992a02 commit cdf167d

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

js/csrfprotector.js

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,8 @@ var CSRFP = {
8080
*/
8181
_getInputElt: function() {
8282
var hiddenObj = document.createElement("input");
83-
hiddenObj.name = CSRFP.CSRFP_TOKEN;
83+
hiddenObj.setAttribute('name', CSRFP.CSRFP_TOKEN);
84+
hiddenObj.setAttribute('class', CSRFP.CSRFP_TOKEN);
8485
hiddenObj.type = 'hidden';
8586
hiddenObj.value = CSRFP._getAuthKey();
8687
return hiddenObj;
@@ -174,6 +175,7 @@ function csrfprotector_init() {
174175
//==================================================================
175176
// Adding csrftoken to request resulting from <form> submissions
176177
// Add for each POST, while for mentioned GET request
178+
// TODO - check for method
177179
//==================================================================
178180
for(var i = 0; i < document.forms.length; i++) {
179181
document.forms[i].addEventListener("submit", function(event) {
@@ -186,9 +188,24 @@ function csrfprotector_init() {
186188
});
187189
}
188190

191+
//==================================================================
192+
// Adding csrftoken to request resulting from direct form.submit() call
193+
// Add for each POST, while for mentioned GET request
194+
// TODO - check for form method
195+
//==================================================================
196+
HTMLFormElement.prototype.submit_ = HTMLFormElement.prototype.submit;
197+
HTMLFormElement.prototype.submit = function() {
198+
// check if the FORM already contains the token element
199+
if (!this.getElementsByClassName(CSRFP.CSRFP_TOKEN).length)
200+
this.appendChild(CSRFP._getInputElt());
201+
this.submit_();
202+
}
203+
204+
189205
/**
190206
* Add wrapper for HTMLFormElements addEventListener so that any further
191207
* addEventListens won't have trouble with CSRF token
208+
* todo - check for method
192209
*/
193210
HTMLFormElement.prototype.addEventListener_ = HTMLFormElement.prototype.addEventListener;
194211
HTMLFormElement.prototype.addEventListener = function(eventType, fun, bubble) {
@@ -202,6 +219,8 @@ function csrfprotector_init() {
202219

203220
/**
204221
* Add wrapper for IE's attachEvent
222+
* todo - check for method
223+
* todo - typeof is now obselete for IE 11, use some other method.
205224
*/
206225
if (typeof HTMLFormElement.prototype.attachEvent !== 'undefined') {
207226
HTMLFormElement.prototype.attachEvent_ = HTMLFormElement.prototype.attachEvent;

0 commit comments

Comments
 (0)