gluon-web-remote

Web remote Administration for big size of gluon routers
git clone git://archive.git.mtrnord.blog/MTRNord/gluon-web-remote.git
Log | Files | Refs | README

Csrf.php (1366B)


      1 <?php
      2 
      3 /**
      4  * Cross Site Request Forgery Class
      5  *
      6  */
      7 
      8 /**
      9  * Instructions:
     10  *
     11  * At your form, before the submit button put:
     12  * <input type="hidden" name="csrf_token" value="<?= Csrf::makeToken(); ?>" />
     13  *
     14  * This validation needed in the controller action method to validate CSRF token submitted with the form:
     15  * if (!Csrf::isTokenValid()) {
     16  *      Login::logout();
     17  *  }
     18  * And that's all
     19  */
     20 class Csrf {
     21 
     22     /**
     23      * get CSRF token and generate a new one if expired
     24      *
     25      * @access public
     26      * @static static method
     27      * @return string
     28      */
     29     public static function makeToken() {
     30 
     31         $max_time    = 60 * 60 * 24; // token is valid for 1 day
     32         $stored_time = Session::get('csrf_token_time');
     33         $csrf_token  = Session::get('csrf_token');
     34 
     35         if($max_time + $stored_time <= time() || empty($csrf_token)){
     36             Session::set('csrf_token', md5(uniqid(rand(), true)));
     37             Session::set('csrf_token_time', time());
     38         }
     39 
     40         return Session::get('csrf_token');
     41     }
     42 
     43     /**
     44      * checks if CSRF token in session is same as in the form submitted
     45      *
     46      * @access public
     47      * @static static method
     48      * @return bool
     49      */
     50     public static function isTokenValid(){
     51         $token = Request::post('csrf_token');
     52         return $token === Session::get('csrf_token') && !empty($token);
     53     }
     54 }