Add a CSRF verification class

This commit is contained in:
2012-01-16 00:18:44 +00:00
parent c4c262a6c3
commit 0d722f98d5
2 changed files with 50 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
<?php
class SihnonFramework_CSRF {
protected $session;
public function __construct() {
$main = SihnonFramework_Main::instance();
$this->session = $main->session();
$this->prepareSession();
}
public function prepareSession() {
if ( ! $this->session->exists('csrf')) {
$this->session->set('csrf', uniqid(), true);
}
}
public function generate() {
$key = uniqid();
$check = $this->generateCheck($key);
return "{$key}:{$check}";
}
protected function generateCheck($key) {
return sha1($key . $this->session->get('csrf'));
}
public function validate($token) {
list($key, $check) = explode(':', $token);
if ($check != $this->generateCheck($key)) {
throw new SihnonFramework_Exception_CSRFVerificationFailure();
}
return true;
}
public function validatePost() {
$token = SihnonFramework_Main::issetelse($_POST['csrftoken'], 'SihnonFramework_Exception_CSRFVerificationFailure');
return $this->validate($token);
}
}
?>

View File

@@ -57,4 +57,7 @@ class SihnonFramework_Exception_LDAPConnectionFailed extends SihnonFramework_E
class SihnonFramework_Exception_LDAPSecureConnectionFailed extends SihnonFramework_Exception_LDAPException {};
class SihnonFramework_Exception_LDAPBindFailed extends SihnonFramework_Exception_LDAPException {};
class SihnonFramework_Exception_CSRFException extends SihnonFramework_Exception {};
class SihnonFramework_Exception_CSRFVerificationFailure extends SihnonFramework_Exception_CSRFException {};
?>