livestatus: Stop relying on broken short-cut
[ninja.git] / application / helpers / csrf.php
blob1049140ea6ba36194dd0a0729c6916460c4e654a
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3 * CSRF helper class.
4 */
5 class csrf_Core {
7 /**
8 * Generate new token
9 * Save token to session together with time for generation
11 * @return str $token
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());
24 return $token;
27 /**
28 * Checks if current token has expired
30 * @return boolean
31 **/
32 public static function current_token_expired() {
33 if (csrf::current_token() !== false && csrf::current_timestamp() + csrf::lifetime() < time()) {
34 return true;
36 return false;
39 /**
40 * Validate token
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) {
48 return false;
50 return true;
53 /**
54 * Return current csrf token
56 public static function current_token()
58 return Session::instance()->get(Kohana::config('csrf.csrf_token'), false);
61 /**
62 * Return current csrf timestamp
64 public static function current_timestamp()
66 return Session::instance()->get(Kohana::config('csrf.csrf_timestamp'), false);
69 /**
70 * Return lifetime for current csrf token
72 public static function lifetime()
74 return (int)Kohana::config('csrf.csrf_lifetime');
77 /**
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) {
83 return;
86 if (empty($name)) $name = Kohana::config('csrf.csrf_token');
87 return '<input type="hidden" name="'.$name.'" value="'.self::token(true).'">';