MkFramework
 All Data Structures Functions
plugin_xsrf.php
1 <?php
2 /*
3 This file is part of Mkframework.
4 
5 Mkframework is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation, either version 3 of the License.
8 
9 Mkframework is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
13 
14 You should have received a copy of the GNU Lesser General Public License
15 along with Mkframework. If not, see <http://www.gnu.org/licenses/>.
16 
17 */
24 
25  private $sSalt;
26  private $iLifetime;
27  private $sMsg;
28  private $bUseSession;
29 
30  private $sSessionVar;
31 
37  public function __construct(){
38  $this->sSalt='fdsfA34T679hjfdsAfef';
39  $this->iLifetime= _root::getConfigVar('security.xsrf.timeout.lifetime');
40  $this->bUseSession=_root::getConfigVar('security.xsrf.session.enabled',0);
41 
42  $this->sSessionVar='xsrfTokenArray';
43  }
44 
49  public function enableSession(){
50  $this->bUseSession=1;
51  }
56  public function disableSession(){
57  $this->bUseSession=0;
58  }
59 
60  private function genToken($iTime){
61  return sha1($this->sSalt.$iTime);
62  }
63 
64 
70  public function getMessage(){
71  return $this->sMsg;
72  }
78  public function getToken(){
79  $iTime=time();
80  $sToken=$iTime.'####'.$this->genToken( $iTime );
81 
82  if($this->bUseSession){
83  $this->saveToken($iTime.'####'.$this->genToken( $iTime ));
84  }
85 
86  return $sToken;
87  }
88 
89  private function saveToken($InputToken){
90  if(!isset($_SESSION[$this->sSessionVar])){
91  $_SESSION[$this->sSessionVar]=array();
92  }
93 
94  $_SESSION[$this->sSessionVar]=$InputToken;
95  }
96 
97  private function isTokenSaved($sToken){
98  if($_SESSION[$this->sSessionVar]==$sToken){
99  return true;
100  }
101  }
102 
103  private function unsaveToken(){
104  $_SESSION[$this->sSessionVar]=null;
105  }
106 
113  public function checkToken($sInputToken){
114  $tToken=preg_split('/####/',$sInputToken);
115  $iTime=$tToken[0];
116  $sToken=$tToken[1];
117  if( (time()-$iTime) >= $this->iLifetime ){ //verifie si la token est valide
118  $this->sMsg='msg_tokenInvalidTimeout';
119  return false;
120  }
121  if($sToken!=$this->genToken($iTime)){ //verifie si ce n'est pas un faux token
122  $this->sMsg='msg_tokenInvalidCorrupt';
123  return false;
124  }
125  if($this->bUseSession){
126  if(!$this->isTokenSaved($sInputToken)){
127  $this->sMsg='msg_tokenUnknown';
128  return false;
129  }else{
130  $this->unsaveToken($sInputToken);
131  }
132  }
133  return true;
134  }
135 
136 
137 }
138 
static getConfigVar($sCatAndVar, $uDefaut=null)
Definition: class_root.php:654
checkToken($sInputToken)