Completed
Pull Request — master (#2)
by Tomáš
09:49
created

TLogoutPresenter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 1
dl 0
loc 78
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
triggerLoggedOut() 0 1 ?
A triggerUserNotLoggedIn() 0 4 1
A triggerInvalidToken() 0 4 1
A injectCsrfTokenFactory() 0 4 1
A startup() 0 23 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SixtyEightPublishers\User\Authentication\UI;
6
7
use Nette;
8
use SixtyEightPublishers;
9
10
/**
11
 * Use in Presenter!
12
 *
13
 * For link creation use:
14
 *
15
 * <code>
16
 * $this->link(':My:Logout:Presenter', [
17
 *      '_sec' => $csrfTokenFactory->create(My\Logout\Presenter::class),
18
 * ]);
19
 * </code>
20
 *
21
 *
22
 * @method Nette\Security\User getUser()
23
 * @method mixed getParameter($key)
24
 * @method
25
 */
26
trait TLogoutPresenter
27
{
28
	/** @var string  */
29
	protected $tokenName = '_sec';
30
31
	/** @var string  */
32
	protected $tokenComponent = __CLASS__;
33
34
	/** @var NULL|\SixtyEightPublishers\User\Authentication\Csrf\ICsrfTokenFactory */
35
	private $csrfTokenFactory;
36
37
	/**
38
	 * Do redirect in this method, you can also add flash messages etc.
39
	 *
40
	 * @return void
41
	 */
42
	abstract protected function triggerLoggedOut(): void;
43
44
	/**
45
	 * Use can override the default behavior
46
	 *
47
	 * @return void
48
	 */
49
	protected function triggerUserNotLoggedIn(): void
50
	{
51
		throw new Nette\Application\ForbiddenRequestException();
52
	}
53
54
	/**
55
	 * Use can override the default behavior
56
	 *
57
	 * @return void
58
	 * @throws \Nette\Application\ForbiddenRequestException
59
	 */
60
	protected function triggerInvalidToken(): void
61
	{
62
		throw new Nette\Application\ForbiddenRequestException();
63
	}
64
65
	/**
66
	 * @internal
67
	 *
68
	 * @param \SixtyEightPublishers\User\Authentication\Csrf\ICsrfTokenFactory $csrfTokenFactory
69
	 *
70
	 * @return void
71
	 */
72
	public function injectCsrfTokenFactory(SixtyEightPublishers\User\Authentication\Csrf\ICsrfTokenFactory $csrfTokenFactory): void
73
	{
74
		$this->csrfTokenFactory = $csrfTokenFactory;
75
	}
76
77
	/**
78
	 * {@inheritdoc}
79
	 */
80
	public function startup(): void
81
	{
82
		/** @noinspection PhpUndefinedClassInspection */
83
		parent::startup();
84
85
		$user = $this->getUser();
86
87
		if (!$user->isLoggedIn()) {
88
			$this->triggerUserNotLoggedIn();
89
		}
90
91
		if ($this->getParameter($this->tokenName) !== $this->csrfTokenFactory->create($this->tokenComponent)) {
92
			$this->triggerInvalidToken();
93
		}
94
95
		$user->logout();
96
		$this->triggerLoggedOut();
97
98
		throw new SixtyEightPublishers\User\Common\Exception\RuntimeException(sprintf(
99
			'Method %s::triggerLoggedOut() must redirects when user is logged in.',
100
			__CLASS__
101
		));
102
	}
103
}
104