summaryrefslogtreecommitdiffstats
path: root/CSRF
blob: ae6b8e8db0cdc135085bf15e921da132cdddc672 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// This code is brought to you by Sean Coates (seancoates.com):

<?php

namespace app\extensions\helper;
use \app\extensions\storage\Session;
use \lithium\util\String;

class Form extends \lithium\template\helper\Form
{
	protected function _render($method, $string, $params, array $options = array()) {
		if ($docsrf = isset($params['options']['docsrf'])) {
			unset($params['options']['docsrf']);
		}
 
		// get default
		$ret = parent::_render($method, $string, $params, $options);
 
		// if we're not already in a create chain, and if we're docsrf...
		if (((get_parent_class($this) . '::create') == $method
			|| (get_class($this) . '::create') == $method)
			&& $docsrf) {
			// append a hidden field with the token
			$ret .= $this->hidden(
				\app\extensions\action\Request::CSRF_TOKEN_FIELD_NAME,
				array('value' => Session::get_csrf_token())
			);
		}
 
		return $ret;
	}
}

?>

<?php

namespace app\extensions\storage;

class Session extends \lithium\storage\Session
{
	public static function get_csrf_token($replace = false)
	{
		$token = null;
		if (!$replace) {
			$token = self::read('csrf_token');
		}
		if ($token) {
			return $token;
		}
 
		// not found (or replacing); generate a new token
		$token = md5(uniqid(microtime(true)));
 
		self::write('csrf_token', $token);
 
		return $token;
	}
 
	public static function check_csrf_token($token)
	{
		return $token === self::read('csrf_token');
	}
 
}

?>