1 <?php
defined('SYSPATH') OR die('No direct access allowed.');
9 * Save token to session together with time for generation
13 public static function token($force = false)
15 if (($token = csrf
::current_token()) === FALSE ||
$force === true || csrf
::current_token_expired() === true) {
17 # save token to session
18 Session
::instance()->set(Kohana
::config('csrf.csrf_token'), ($token = text
::random('alnum', 41)));
20 # save session timestamp to session
21 Session
::instance()->set(Kohana
::config('csrf.csrf_timestamp'), time());
28 * Checks if current token has expired
32 public static function current_token_expired() {
33 if (csrf
::current_token() !== false && csrf
::current_timestamp() + csrf
::lifetime() < time()) {
41 * @param $token The csrf token
42 * @return true if validation was successful, false otherwise
44 public static function valid($token)
46 # not valid if tokens differ or has expired
47 if ($token !== csrf
::current_token() || csrf
::current_token_expired() === true) {
54 * Return current csrf token
56 public static function current_token()
58 return Session
::instance()->get(Kohana
::config('csrf.csrf_token'), false);
62 * Return current csrf timestamp
64 public static function current_timestamp()
66 return Session
::instance()->get(Kohana
::config('csrf.csrf_timestamp'), false);
70 * Return lifetime for current csrf token
72 public static function lifetime()
74 return (int)Kohana
::config('csrf.csrf_lifetime');
78 * Return a string representation of a form element with the current CSRF token
79 * @param $name The name of the form element
81 public static function form_field($name='') {
82 if (Kohana
::config('csrf.csrf_token')=='' || Kohana
::config('csrf.active') === false) {
86 if (empty($name)) $name = Kohana
::config('csrf.csrf_token');
87 return '<input type="hidden" name="'.$name.'" value="'.self
::token(true).'">';