CSRF 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // This code is brought to you by Sean Coates (seancoates.com):
  2. <?php
  3. namespace app\extensions\helper;
  4. use \app\extensions\storage\Session;
  5. use \lithium\util\String;
  6. class Form extends \lithium\template\helper\Form
  7. {
  8. protected function _render($method, $string, $params, array $options = array()) {
  9. if ($docsrf = isset($params['options']['docsrf'])) {
  10. unset($params['options']['docsrf']);
  11. }
  12. // get default
  13. $ret = parent::_render($method, $string, $params, $options);
  14. // if we're not already in a create chain, and if we're docsrf...
  15. if (((get_parent_class($this) . '::create') == $method
  16. || (get_class($this) . '::create') == $method)
  17. && $docsrf) {
  18. // append a hidden field with the token
  19. $ret .= $this->hidden(
  20. \app\extensions\action\Request::CSRF_TOKEN_FIELD_NAME,
  21. array('value' => Session::get_csrf_token())
  22. );
  23. }
  24. return $ret;
  25. }
  26. }
  27. ?>
  28. <?php
  29. namespace app\extensions\storage;
  30. class Session extends \lithium\storage\Session
  31. {
  32. public static function get_csrf_token($replace = false)
  33. {
  34. $token = null;
  35. if (!$replace) {
  36. $token = self::read('csrf_token');
  37. }
  38. if ($token) {
  39. return $token;
  40. }
  41. // not found (or replacing); generate a new token
  42. $token = md5(uniqid(microtime(true)));
  43. self::write('csrf_token', $token);
  44. return $token;
  45. }
  46. public static function check_csrf_token($token)
  47. {
  48. return $token === self::read('csrf_token');
  49. }
  50. }
  51. ?>