|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Yeelight\Http\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Http\Request; |
|
6
|
|
|
use Illuminate\Support\Facades\Auth; |
|
7
|
|
|
use Illuminate\Support\Str; |
|
8
|
|
|
use Yeelight\Models\Permission as Checker; |
|
9
|
|
|
|
|
10
|
|
|
class Permission |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var string |
|
14
|
|
|
*/ |
|
15
|
|
|
protected $middlewarePrefix = 'yeelight.backend.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 (!Auth::guard(config('yeelight.backend.route.prefix'))->user() || !empty($args)) { |
|
29
|
|
|
return $next($request); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
if ($this->checkRoutePermission($request)) { |
|
33
|
|
|
return $next($request); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
if (!Auth::guard(config('yeelight.backend.route.prefix'))->user()->allPermissions()->first(function ($permission) use ($request) { |
|
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
|
|
|
|