Passed
Push — master ( 7d615b...d4db62 )
by Jean-Christophe
09:33
created

VerifyCsrfToken   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 52.94%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 27
c 1
b 0
f 0
dl 0
loc 48
ccs 18
cts 34
cp 0.5294
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 4 1
A __construct() 0 2 1
A csrfErrorLog() 0 7 1
A getLevel() 0 2 1
A clear() 0 5 2
A start() 0 13 5
1
<?php
2
3
namespace Ubiquity\utils\http\session\protection;
4
5
use Ubiquity\utils\http\session\AbstractSession;
6
use Ubiquity\utils\http\UCookie;
7
use Ubiquity\log\Logger;
8
9
/**
10
 * Ubiquity\utils\http\session\protection$VerifyCsrfToken
11
 * This class is part of Ubiquity
12
 *
13
 * @author jc
14
 * @version 1.0.1
15
 *
16
 */
17
class VerifyCsrfToken implements VerifySessionCsrfInterface {
18
	private AbstractSession $sessionInstance;
19
	private const TOKEN_KEY = 'X-XSRF-TOKEN';
20
21 1
	public function __construct(AbstractSession $sessionInstance) {
22 1
		$this->sessionInstance = $sessionInstance;
23 1
	}
24
25
	protected function csrfErrorLog() {
26
		$context = array ();
27
		$context ['HOST'] = $_SERVER ['HTTP_HOST'];
28
		$context ['REQUEST_URI'] = $_SERVER ['REQUEST_URI'];
29
		$context ['REQUEST_METHOD'] = $_SERVER ['REQUEST_METHOD'];
30
		$context ['cookie'] = $_COOKIE;
31
		Logger::error ( 'Session', 'CSRF protector validation failure!', 'startSession', $context );
32
	}
33
34 2
	public function init() {
35 2
		$token = new CsrfToken ();
36 2
		$this->sessionInstance->set ( self::TOKEN_KEY, $token );
37 2
		UCookie::set ( $token->getName (), $token->getValue (), null );
38 2
	}
39
40 1
	public function clear() {
41 1
		$token = $this->sessionInstance->get ( self::TOKEN_KEY );
42 1
		$this->sessionInstance->delete ( self::TOKEN_KEY );
43 1
		if (isset ( $token )) {
44
			UCookie::delete ( $token->getName () );
45
		}
46 1
	}
47
48 2
	public function start() {
49 2
		$token = $this->sessionInstance->get ( self::TOKEN_KEY );
50 2
		if (isset ( $token )) {
51
			if (! $token instanceof CsrfToken || ! hash_equals ( $token->getValue (), '' . UCookie::get ( $token->getName () ) )) {
52
				if (Logger::isActive ()) {
53
					$this->csrfErrorLog ();
54
				}
55
				$this->sessionInstance->terminate ();
56
			} else {
57
				return;
58
			}
59
		}
60 2
		$this->init ();
61 2
	}
62
63
	public static function getLevel() {
64
		return 1;
65
	}
66
}
67
68