Browse Source

Add CSRF token for Ajax

merge-requests/1/head
Erase 4 years ago
parent
commit
462bda41b2
3 changed files with 42 additions and 3 deletions
  1. +30
    -1
      generate.php
  2. +8
    -1
      index.php
  3. +4
    -1
      js/custom.js

+ 30
- 1
generate.php View File

@ -1,4 +1,34 @@
<?php
//~ Ajax only
if(!array_key_exists('isAjax', $_POST) || $_POST['isAjax'] !== "true"){
exit('No ajax');
}
//~ Check token
session_start();
if(empty($_SESSION['csrf_token'])){
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$headers = apache_request_headers();
if(array_key_exists('CsrfToken', $headers) && isset($headers['CsrfToken'])){
if ($headers['CsrfToken'] !== $_SESSION['csrf_token']) {
//~ Wrong token
$_d['sucess'] = false;
$_d['message'] = "Problème lors de la vérification du token";
header('Content-type: text/json');
echo json_encode($_d);
exit;
}
}else {
//~ No token
$_d['sucess'] = false;
$_d['message'] = "Problème de token";
header('Content-type: text/json');
echo json_encode($_d);
exit;
}
//~ Include RSS Fusion
require_once 'vendor/RSS-Fusion/index.php';
@ -49,7 +79,6 @@
'_badWords' => \Config::get('_badWords')
));
session_start();
$conf_name = str_replace('.', '', uniqid(rand(), true));
$path = TL_ROOT . '/../../c/';


index.html → index.php View File

@ -1,12 +1,19 @@
<?php
//~ Generate token
session_start();
if(empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>RSS-Fusion - Démo</title>
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="chrome=1"><![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="format-detection" content="telephone=no"/>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<meta name="csrf-token" content="<?= $_SESSION['csrf_token'] ?>">
<link rel="dns-prefetch" href="http://fonts.googleapis.com/">
<link rel="dns-prefetch" href="http://ajax.googleapis.com/">
<link rel="dns-prefetch" href="http://html5shim.googlecode.com/">

+ 4
- 1
js/custom.js View File

@ -14,7 +14,10 @@ $(document).ready(function(){
$.ajax({
type: 'POST',
url: 'generate.php',
data: $('#contact_form').serialize(),
data: $('#contact_form').serialize()+'&isAjax=true',
headers : {
'CsrfToken': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
$this.removeAttr('disabled');
if(!data || !data.sucess){


Loading…
Cancel
Save