Skip to content

Commit dfafd99

Browse files
committed
add csrf token in headers
1 parent d756141 commit dfafd99

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

Ajax/JsUtils.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ public function config($config=NULL) {
173173
*/
174174
public function __construct($params=array(),$injected=NULL) {
175175
$ajaxDefault=['ajaxTransition'=>null,'attr'=>'','historize'=>false,'jsCallback'=>null,'hasLoader'=>true,'jqueryDone'=>'html',
176-
'async'=>true,'params'=>null,'headers'=>null,'jsCondition'=>null,'ajaxLoader'=>null];
176+
'async'=>true,'params'=>null,'headers'=>null,'jsCondition'=>null,'ajaxLoader'=>null,'csrf'=>false];
177177
$defaults=['debug'=>true,'defer'=>false,'ajax'=>$ajaxDefault,
178178
'historize'=>true,'autoActiveLinks'=>true
179179
];
@@ -201,6 +201,9 @@ public function __construct($params=array(),$injected=NULL) {
201201
if($params["ajax"]["historize"]){
202202
$params["historize"]=true;
203203
}
204+
if($params["ajax"]["csrf"]){
205+
$this->exec($this->addCsrf(),true);
206+
}
204207
}
205208
if($params["historize"]){
206209
$this->execAtLast($this->onPopstate());

Ajax/common/traits/JsUtilsAjaxTrait.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ protected function _ajax($method, $url, $responseElement = '', $parameters = [ ]
5252
if (isset ( $headers )) {
5353
$ajaxParameters ["headers"] = $headers;
5454
}
55+
if ($csrf) {
56+
$csrf=(is_string($csrf))?$csrf:'csrf-token';
57+
$parameters ["beforeSend"] = "jqXHR.setRequestHeader('{$csrf}', $('meta[name=\"{$csrf}\"]').attr('content'));";
58+
}
5559
if (isset ( $partial )) {
5660
$ajaxParameters ["xhr"] = "xhrProvider";
5761
$retour .= "var xhr = $.ajaxSettings.xhr();function xhrProvider() {return xhr;};xhr.onreadystatechange = function (e) { if (3==e.target.readyState){let response=e.target.responseText;" . $partial . ";}; };";
@@ -820,4 +824,16 @@ public function postFormOn($event, $element, $url, $form, $responseElement = "",
820824
public function postFormOnClick($element, $url, $form, $responseElement = "", $parameters = array ()) {
821825
return $this->postFormOn ( "click", $element, $url, $form, $responseElement, $parameters );
822826
}
827+
828+
public function addCsrf($name='csrf-token'){
829+
return "
830+
$.ajaxSetup({
831+
beforeSend: function(xhr, settings) {
832+
let csrfSafeMethod=function(method) { return (/^(GET|HEAD|OPTIONS)$/.test(method));};
833+
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
834+
xhr.setRequestHeader('{$name}', $('meta[name=\"{$name}\"]').attr('content'));
835+
}
836+
}
837+
});";
838+
}
823839
}

0 commit comments

Comments
 (0)