Completed
Push — master ( 14d94b...a31156 )
by Nicolas
02:43
created

Authorization   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
c 1
b 0
f 0
lcom 1
cbo 4
dl 0
loc 50
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A handle() 0 8 2
A handleUnauthorizedRequest() 0 13 3
1
<?php namespace Modules\Core\Http\Middleware;
2
3
use Illuminate\Http\Request;
4
use Illuminate\Http\Response;
5
use Modules\Core\Contracts\Authentication;
6
7
/**
8
 * Class Authorization
9
 * Inspired by : https://github.com/spatie/laravel-authorize
10
 * @package Modules\Core\Http\Middleware
11
 */
12
class Authorization
13
{
14
    /**
15
     * @var Authentication
16
     */
17
    private $auth;
18
19
    /**
20
     * Authorization constructor.
21
     * @param Authentication $auth
22
     */
23
    public function __construct(Authentication $auth)
24
    {
25
        $this->auth = $auth;
26
    }
27
28
    /**
29
     * @param $request
30
     * @param \Closure $next
31
     * @param $permission
32
     * @return \Illuminate\Http\RedirectResponse|Response
33
     */
34
    public function handle($request, \Closure $next, $permission)
35
    {
36
        if ($this->auth->hasAccess($permission) === false) {
37
            return $this->handleUnauthorizedRequest($request, $permission);
38
        }
39
40
        return $next($request);
41
    }
42
43
    /**
44
     * @param Request $request
45
     * @param $permission
46
     * @return \Illuminate\Http\RedirectResponse|Response
47
     */
48
    private function handleUnauthorizedRequest(Request $request, $permission)
49
    {
50
        if ($request->ajax()) {
51
            return response('Unauthorized.', Response::HTTP_UNAUTHORIZED);
52
        }
53
        if (! $request->user()) {
54
            return redirect()->guest('auth/login');
55
        }
56
57
        flash()->error(trans('core::core.permission denied', ['permission' => $permission]));
58
59
        return redirect()->back();
60
    }
61
}
62