|
@@ -0,0 +1,74 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+
|
|
|
+namespace Hugh\AdminUserOptimize;
|
|
|
+
|
|
|
+use Encore\Admin\Auth\Database\Administrator as AdminAdministrator;
|
|
|
+use Illuminate\Support\Str;
|
|
|
+
|
|
|
+class Administrator extends AdminAdministrator
|
|
|
+{
|
|
|
+ /**
|
|
|
+ * A User has and belongs to many permissions & User's permissions
|
|
|
+ *
|
|
|
+ * @return \Illuminate\Support\Collection
|
|
|
+ */
|
|
|
+ public function allPermissions() : \Illuminate\Support\Collection
|
|
|
+ {
|
|
|
+ return $this->roles->pluck('permissions')->flatten()->merge($this->permissions)->unique('id');
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Check a user can access the url by method
|
|
|
+ * Warning!!!
|
|
|
+ * This function only check url & method
|
|
|
+ * But NOT check Middleware admin.permission: by Encore\Admin\Middleware\Permission@checkRoutePermission
|
|
|
+ *
|
|
|
+ * @param string $url
|
|
|
+ * @param <TypeEnum::*> $method
|
|
|
+ *
|
|
|
+ * @return bool
|
|
|
+ */
|
|
|
+ public function checkUrlPermission(string $url,$method = TypeEnum::GET) : bool
|
|
|
+ {
|
|
|
+ return !is_null($this->allPermissions()->first(function ($permission) use ($url, $method) {
|
|
|
+ return $this->shouldPassThrough($permission, $url, $method);
|
|
|
+ }));
|
|
|
+ }
|
|
|
+ private function shouldPassThrough($permission, $url, $requestMethod)
|
|
|
+ {
|
|
|
+ if (empty($permission->http_method) && empty($permission->http_path)) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ $method = $permission->http_method;
|
|
|
+
|
|
|
+ $matches = array_map(function ($path) use ($method) {
|
|
|
+
|
|
|
+ if (Str::contains($path, ':')) {
|
|
|
+ list($method, $path) = explode(':', $path);
|
|
|
+ $method = explode(',', $method);
|
|
|
+ }
|
|
|
+
|
|
|
+ return compact('method', 'path');
|
|
|
+ }, explode("\n", $permission->http_path));
|
|
|
+ foreach ($matches as $match) {
|
|
|
+
|
|
|
+ $path = $match['path'] === '/' ? '/' : trim($match['path'], '/');
|
|
|
+
|
|
|
+ if (!Str::is($path, $url)) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ $method = collect($match['method'])->filter()->map(function ($method) {
|
|
|
+ return strtoupper($method);
|
|
|
+ });
|
|
|
+
|
|
|
+ if ($method->isEmpty() || $method->contains($requestMethod)) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+}
|