first change
This commit is contained in:
98
Modules/User/app/Services/PermissionService.php
Normal file
98
Modules/User/app/Services/PermissionService.php
Normal file
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\User\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
use Spatie\Permission\Models\Role;
|
||||
|
||||
class PermissionService
|
||||
{
|
||||
|
||||
public function getPermissionListsArrangedByPrefix()
|
||||
{
|
||||
$permissions = self::getPermissions();
|
||||
|
||||
$routeNameArr = [];
|
||||
foreach ($permissions as $permission) {
|
||||
if (!is_null($permission->name)) {
|
||||
$routeName = explode('.', $permission->name);
|
||||
if (is_array($routeName) && !empty($routeName[0])) {
|
||||
$routeNameArr[$routeName[0]][$permission->id] = array_key_exists(1, $routeName) ? $routeName[1] : $routeName[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ksort($routeNameArr);
|
||||
|
||||
return $routeNameArr;
|
||||
}
|
||||
|
||||
public static function generatePermissionFromRoutes()
|
||||
{
|
||||
$routes = Route::getRoutes();
|
||||
foreach ($routes as $route) {
|
||||
|
||||
$routeName = $names[] = $route->getName();
|
||||
|
||||
$ignoreRoutes = [
|
||||
'debugbar',
|
||||
'unisharp',
|
||||
'livewire',
|
||||
'login',
|
||||
'register',
|
||||
'logout',
|
||||
'post',
|
||||
'sanctum',
|
||||
'ignition',
|
||||
'welcome',
|
||||
'home',
|
||||
'api',
|
||||
];
|
||||
|
||||
$routePrefix = explode('.', $routeName);
|
||||
if (is_array($routePrefix) && !empty($routePrefix[0])) {
|
||||
if (!in_array($routePrefix[0], $ignoreRoutes) && !Permission::where('name', $routeName)->exists()) {
|
||||
Permission::updateOrCreate(['name' => $routeName], ['name' => $routeName, 'guard_name' => 'web']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$permissions = Permission::pluck('name', 'id');
|
||||
$diffRoutes = array_diff($permissions->toArray(), $names);
|
||||
if ($diffRoutes) {
|
||||
Permission::whereIn('id', array_keys($diffRoutes))->delete();
|
||||
}
|
||||
|
||||
$roles = Role::all();
|
||||
foreach ($roles as $role) {
|
||||
|
||||
if ($role->name == 'admin' || $role->name == 'super-admin') {
|
||||
$role->givePermissionTo(Permission::all());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public function getPermissions()
|
||||
{
|
||||
$query = Permission::query();
|
||||
return $query->get();
|
||||
}
|
||||
|
||||
public function getPermissionById($id)
|
||||
{
|
||||
return Permission::findOrFail($id);
|
||||
}
|
||||
|
||||
public function deletePermission($id)
|
||||
{
|
||||
return DB::transaction(function () use ($id) {
|
||||
$permission = self::getPermissionById($id);
|
||||
$permission->delete();
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user