-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathProtectedControllerTrait.php
More file actions
67 lines (60 loc) · 2.21 KB
/
ProtectedControllerTrait.php
File metadata and controls
67 lines (60 loc) · 2.21 KB
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
<?php
declare(strict_types=1);
/**
* This file is part of the Linna Framework.
*
* @author Sebastian Rapetti <sebastian.rapetti@tim.it>
* @copyright (c) 2018, Sebastian Rapetti
* @license http://opensource.org/licenses/MIT MIT License
*/
namespace Linna\Authentication;
use Linna\Authentication\Authentication;
use Linna\Authentication\Exception\AuthenticationException;
/**
* Help protect a controller with login.
*
* <p>This trait add to a controller the ability to interrupt its own execution, in case authentication is required.</p>
*
* <p>This trait contains only private mothods.</p>
*/
trait ProtectedControllerTrait // @phpstan-ignore trait.unused
{
/** @var bool Contain login status. */
private bool $authentication = false;
/**
* Allow access to controller class or methods only if logged.
*
* <p>Return a status code, useful with AJAX requests.</p>
*
* @param Authentication $authentication <code>Authentication</code> class instance.
* @param string $route Valid route path for <code>AuthenticationException</code>.
*
* @return void
*
* @throws AuthenticationException if user not authenticathed.
*/
private function protect(Authentication $authentication, string $route): void
{
if (($this->authentication = $authentication->isLogged()) === false) {
throw new AuthenticationException($route);
}
}
/**
* Allow access to controller class or methods only if logged and do an HTTP redirection if not.
*
* @param Authentication $authentication <code>Authentication</code> class instance.
* @param string $location Valid url for Location header.
* @param string $route Valid route path for <code>AuthenticationException</code>.
*
* @return void
*
* @throws AuthenticationException if user not authenticathed.
*/
private function protectWithRedirect(Authentication $authentication, string $location, string $route): void
{
if (($this->authentication = $authentication->isLogged()) === false) {
\header('Location: '.$location);
throw new AuthenticationException($route);
}
}
}