Completed
Push — master ( 643241...1efb7f )
by Song
02:21
created

Permission::shouldPassThrough()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 19

Duplication

Lines 19
Ratio 100 %

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 1
dl 19
loc 19
rs 9.6333
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Middleware;
4
5
use Encore\Admin\Auth\Permission as Checker;
6
use Encore\Admin\Facades\Admin;
7
use Illuminate\Http\Request;
8
use Illuminate\Support\Str;
9
10
class Permission
11
{
12
    /**
13
     * @var string
14
     */
15
    protected $middlewarePrefix = 'admin.permission:';
16
17
    /**
18
     * Handle an incoming request.
19
     *
20
     * @param \Illuminate\Http\Request $request
21
     * @param \Closure                 $next
22
     * @param array                    $args
23
     *
24
     * @return mixed
25
     */
26
    public function handle(Request $request, \Closure $next, ...$args)
27
    {
28
        if (!Admin::user() || !empty($args) || $this->shouldPassThrough($request)) {
29
            return $next($request);
30
        }
31
32
        if ($this->checkRoutePermission($request)) {
33
            return $next($request);
34
        }
35
36
        if (!Admin::user()->allPermissions()->first(function ($permission) use ($request) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Auth\Authenticatable as the method allPermissions() does only exist in the following implementations of said interface: Encore\Admin\Auth\Database\Administrator.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
37
            return $permission->shouldPassThrough($request);
38
        })) {
39
            Checker::error();
40
        }
41
42
        return $next($request);
43
    }
44
45
    /**
46
     * If the route of current request contains a middleware prefixed with 'admin.permission:',
47
     * then it has a manually set permission middleware, we need to handle it first.
48
     *
49
     * @param Request $request
50
     *
51
     * @return bool
52
     */
53
    public function checkRoutePermission(Request $request)
54
    {
55
        if (!$middleware = collect($request->route()->middleware())->first(function ($middleware) {
56
            return Str::startsWith($middleware, $this->middlewarePrefix);
57
        })) {
58
            return false;
59
        }
60
61
        $args = explode(',', str_replace($this->middlewarePrefix, '', $middleware));
62
63
        $method = array_shift($args);
64
65
        if (!method_exists(Checker::class, $method)) {
66
            throw new \InvalidArgumentException("Invalid permission method [$method].");
67
        }
68
69
        call_user_func_array([Checker::class, $method], [$args]);
70
71
        return true;
72
    }
73
74
    /**
75
     * Determine if the request has a URI that should pass through verification.
76
     *
77
     * @param \Illuminate\Http\Request $request
78
     *
79
     * @return bool
80
     */
81 View Code Duplication
    protected function shouldPassThrough($request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
82
    {
83
        $excepts = [
84
            admin_base_path('auth/login'),
85
            admin_base_path('auth/logout'),
86
        ];
87
88
        foreach ($excepts as $except) {
89
            if ($except !== '/') {
90
                $except = trim($except, '/');
91
            }
92
93
            if ($request->is($except)) {
94
                return true;
95
            }
96
        }
97
98
        return false;
99
    }
100
}
101