Test Failed
Push — master ( bca30b...29fe32 )
by Jean-Christophe
22:16
created

VerifyCsrfToken   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 26
c 1
b 0
f 0
dl 0
loc 44
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 4 1
A clear() 0 5 2
A start() 0 13 4
A __construct() 0 2 1
A csrfErrorLog() 0 7 1
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.0
15
 *
16
 */
17
class VerifyCsrfToken implements VerifySessionCsrfInterface {
18
	private AbstractSession $sessionInstance;
19
	private const TOKEN_KEY = 'X-XSRF-TOKEN';
20
21
	public function __construct(AbstractSession $sessionInstance) {
22
		$this->sessionInstance = $sessionInstance;
23
	}
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
	public function init() {
35
		$token = new CsrfToken ();
36
		$this->sessionInstance->set ( self::TOKEN_KEY, $token );
37
		UCookie::set ( $token->getName (), $token->getValue (), null );
38
	}
39
40
	public function clear() {
41
		$token = $this->sessionInstance->get ( self::TOKEN_KEY );
42
		$this->sessionInstance->delete ( self::TOKEN_KEY );
43
		if (isset ( $token )) {
44
			UCookie::delete ( $token->getName () );
45
		}
46
	}
47
48
	public function start() {
49
		$token = $this->sessionInstance->get ( self::TOKEN_KEY );
50
		if (isset ( $token )) {
51
			if (! hash_equals ( $token->getValue (), UCookie::get ( $token->getName () ) )) {
0 ignored issues
show
Bug introduced by
It seems like Ubiquity\utils\http\UCoo...:get($token->getName()) can also be of type array; however, parameter $user_string of hash_equals() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

51
			if (! hash_equals ( $token->getValue (), /** @scrutinizer ignore-type */ UCookie::get ( $token->getName () ) )) {
Loading history...
52
				if (Logger::isActive ()) {
53
					$this->csrfErrorLog ();
54
				}
55
				$this->sessionInstance->terminate ();
56
			} else {
57
				return;
58
			}
59
		}
60
		$this->init ();
61
	}
62
}
63
64