Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…o kazimentou-token-2003
  • Loading branch information
pedrocadete committed Mar 11, 2020
2 parents 893f602 + 2e8037e commit 2f6beed
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions core/lib/class.plx.token.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,52 @@
* @author Stephane F
**/
class plxToken {
const TEMPLATE = 'abcdefghijklmnpqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const LIFETIME = 3600; // seconds

/**
* Méthode qui affiche le champ input contenant le token
*
* @return stdio/null
* @author Stephane F
* @author J.P. Pourrez, Stephane F
**/
public static function getTokenPostMethod() {

$token = sha1(mt_rand(0, 1000000));
public static function getTokenPostMethod($length=32, $html=true) {
$range = strlen(plxToken::TEMPLATE);
$result = array();
mt_srand((float)microtime() * 1000000);
for($i=0; $i<$length; $i++) {
$result[] = self::TEMPLATE[mt_rand() % $range];
}
$token = implode('', $result);
$_SESSION['formtoken'][$token] = time();
return '<input name="token" value="'.$token.'" type="hidden" />';

return ($html) ? '<input name="token" value="'.$token.'" type="hidden" />' : $token;
}

/**
* Méthode qui valide la durée de vide d'un token
*
* @param $request (deprecated)
* @return stdio/null
* @author Stephane F
* @author J.P. Pourrez, Stephane F
**/
public static function validateFormToken($request='') {

if($_SERVER['REQUEST_METHOD']=='POST' AND isset($_SESSION['formtoken'])) {
$limit = time() - self::LIFETIME;

if(empty($_POST['token']) OR plxUtils::getValue($_SESSION['formtoken'][$_POST['token']]) < time() - 3600) { # 3600 seconds
if(empty($_POST['token']) OR plxUtils::getValue($_SESSION['formtoken'][$_POST['token']]) < $limit) {
unset($_SESSION['formtoken']);
die('Security error : invalid or expired token');
}
unset($_SESSION['formtoken'][$_POST['token']]);
// autoclean up !
if(!empty($_SESSION['formtoken'])) {
foreach($_SESSION['formtoken'] as $token=>$lifetime) {
if($lifetime < $limit) {
unset($_SESSION['formtoken'][$token]);
}
}
}
}

}
Expand All @@ -63,4 +78,4 @@ public static function generateTokenExperyDate($hours = 24) {
return date('YmdHis', mktime(date('H')+$hours, date('i'), date('s'), date('m'), date('d'), date('Y')));
}

}
}

0 comments on commit 2f6beed

Please sign in to comment.