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

AuthMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 6
dl 0
loc 36
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A __invoke() 0 12 4
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