Completed
Push — master ( 2c69ad...5eb3ba )
by Alexis
01:46
created

AuthMiddleware::__invoke()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 3
nop 3
1
<?php
2
3
namespace Security\Middleware;
4
5
use App\Middleware\Middleware;
6
use Psr\Container\ContainerInterface;
7
use Security\Exception\AccessDeniedException;
8
use Slim\Http\Request;
9
use Slim\Http\Response;
10
11
class AuthMiddleware extends Middleware
12
{
13
    /**
14
     * @var string
15
     */
16
    protected $role;
17
18
    /**
19
     * Constructor.
20
     *
21
     * @param ContainerInterface $container
22
     * @param string             $role
23
     */
24
    public function __construct(ContainerInterface $container, $role = null)
25
    {
26
        parent::__construct($container);
27
28
        $this->role = $role;
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function __invoke(Request $request, Response $response, callable $next)
35
    {
36
        if (!$this->auth->check()) {
37
            $this->flash->addMessage('error', 'You must be logged in to access this page!');
38
39
            return $response->withRedirect($this->router->pathFor('login'));
40
        } elseif ($this->role && !$this->auth->inRole($this->role)) {
41
            throw new AccessDeniedException();
42
        }
43
44
        return $next($request, $response);
45
    }
46
}
47