generated from liutk/owl-admin-base
104 lines
2.8 KiB
PHP
104 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Admin\Middleware;
|
|
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Collection;
|
|
use Slowlyo\OwlAdmin\Admin;
|
|
use Slowlyo\OwlAdmin\Support\Cores\Permission;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class CheckPermission
|
|
{
|
|
/**
|
|
* @var array<int, string>
|
|
*/
|
|
protected $exceptPaths = [
|
|
'/api/*',
|
|
'/start_chunk_upload_file',
|
|
'/save_chunk_upload_file',
|
|
'/finish_chunk_upload_file',
|
|
'/upload_file',
|
|
'/upload_image',
|
|
'/upload_rich',
|
|
];
|
|
|
|
/**
|
|
* @var array<int, string>
|
|
*/
|
|
protected $exceptRoutes = [
|
|
//
|
|
];
|
|
|
|
/**
|
|
* Handle an incoming request.
|
|
*
|
|
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
|
*/
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
if ($this->inExceptArray($request) || $this->checkRoutePermission($request)) {
|
|
return $next($request);
|
|
}
|
|
|
|
return Admin::response()->fail(__('admin.unauthorized'), ['route' => $request->route()->getName()]);
|
|
}
|
|
|
|
protected function checkRoutePermission(Request $request): bool
|
|
{
|
|
if (is_null($user = Admin::user())) {
|
|
return false;
|
|
}
|
|
|
|
$ability = $this->normalizeRouteAbility(
|
|
$original = $request->route()->getName()
|
|
);
|
|
|
|
return collect($ability)
|
|
->when($ability !== $original, fn (Collection $collection) => $collection->push($original))
|
|
->contains(fn ($ability) => $user->can($ability));
|
|
}
|
|
|
|
protected function normalizeRouteAbility(string $ability)
|
|
{
|
|
foreach ($this->resourceAbilityMap() as $method => $map) {
|
|
if (str_ends_with($ability, ".{$method}")) {
|
|
return preg_replace("/(.*)\.{$method}$/", '${1}.'.$map, $ability);
|
|
}
|
|
}
|
|
|
|
return $ability;
|
|
}
|
|
|
|
protected function resourceAbilityMap(): array
|
|
{
|
|
return [
|
|
'index' => 'list',
|
|
'show' => 'view',
|
|
'store' => 'create',
|
|
'edit' => 'update',
|
|
'destroy' => 'delete',
|
|
];
|
|
}
|
|
|
|
protected function inExceptArray(Request $request): bool
|
|
{
|
|
if (in_array($request->route()->getName(), $this->exceptRoutes)) {
|
|
return true;
|
|
}
|
|
|
|
$permission = Admin::permission();
|
|
|
|
return $request->is(
|
|
collect($this->exceptPaths)
|
|
->when(Admin::permission(), fn (Collection $collection, Permission $permission) => $collection->merge($permission->authExcept)->merge($permission->permissionExcept))
|
|
->map(function ($path) {
|
|
$path = trim((string) config('admin.route.prefix'), '/').'/'.trim((string) $path, '/');
|
|
|
|
return ltrim($path, '/');
|
|
})
|
|
);
|
|
}
|
|
}
|