Csrf.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. /**
  3. *
  4. * Cube Framework $Id$ fnPGDs0Z/qAwNaUwjcoVbFZRVI6QHZ42WtBl3ze5+HQ=
  5. *
  6. * @link http://codecu.be/framework
  7. * @copyright Copyright (c) 2015 CodeCube SRL
  8. * @license http://codecu.be/framework/license Commercial License
  9. *
  10. * @version 1.4
  11. */
  12. namespace Cube\Validate;
  13. use Cube\Controller\Front,
  14. Cube\Session;
  15. /**
  16. * csrf element validator class
  17. *
  18. * Class Csrf
  19. *
  20. * @package Cube\Validate
  21. */
  22. class Csrf extends AbstractValidate
  23. {
  24. const SESSION_NAMESPACE = 'Csrf';
  25. protected $_message = "The CSRF validation has failed.";
  26. /**
  27. *
  28. * session object
  29. *
  30. * @var \Cube\Session
  31. */
  32. protected $_session;
  33. /**
  34. *
  35. * class constructor
  36. */
  37. public function __construct()
  38. {
  39. $this->setSession();
  40. }
  41. /**
  42. *
  43. * get session object
  44. *
  45. * @return \Cube\Session
  46. */
  47. public function getSession()
  48. {
  49. if (!($this->_session instanceof Session)) {
  50. $this->setSession();
  51. }
  52. return $this->_session;
  53. }
  54. /**
  55. *
  56. * set session object
  57. *
  58. * @param \Cube\Session $session
  59. *
  60. * @return \Cube\Validate\Csrf
  61. */
  62. public function setSession(Session $session = null)
  63. {
  64. if ($session === null) {
  65. $session = Front::getInstance()->getBootstrap()->getResource('session');
  66. }
  67. if (!($session instanceof Session)) {
  68. $session = new Session();
  69. $session->setNamespace(self::SESSION_NAMESPACE);
  70. }
  71. $this->_session = $session;
  72. return $this;
  73. }
  74. /**
  75. *
  76. * checks for a valid csrf field, and resets the csrf field if valid
  77. *
  78. * @return bool return true if the validation is successful
  79. */
  80. public function isValid()
  81. {
  82. $codes = (array)$this->_session->get($this->_name);
  83. if (($key = array_search($this->_value, $codes)) !== false) {
  84. unset($codes[$key]);
  85. $this->_session->set($this->_name, $codes);
  86. return true;
  87. }
  88. else {
  89. return false;
  90. }
  91. }
  92. }