Auth.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace plugin\admin\app\common;
  3. use plugin\admin\app\model\Admin;
  4. use plugin\admin\app\model\AdminRole;
  5. use plugin\admin\app\model\Role;
  6. use plugin\admin\app\model\Rule;
  7. class Auth
  8. {
  9. /**
  10. * 获取权限范围内的所有角色id
  11. * @param bool $with_self
  12. * @return array
  13. */
  14. public static function getScopeRoleIds(bool $with_self = false): array
  15. {
  16. if (!$admin = admin()) {
  17. return [];
  18. }
  19. $role_ids = $admin['roles'];
  20. $rules = Role::whereIn('id', $role_ids)->pluck('rules')->toArray();
  21. if ($rules && in_array('*', $rules)) {
  22. return Role::pluck('id')->toArray();
  23. }
  24. $roles = Role::get();
  25. $tree = new Tree($roles);
  26. $descendants = $tree->getDescendant($role_ids, $with_self);
  27. return array_column($descendants, 'id');
  28. }
  29. /**
  30. * 获取权限范围内的所有管理员id
  31. * @param bool $with_self
  32. * @return array
  33. */
  34. public static function getScopeAdminIds(bool $with_self = false): array
  35. {
  36. $role_ids = static::getScopeRoleIds();
  37. $admin_ids = AdminRole::whereIn('role_id', $role_ids)->pluck('admin_id')->toArray();
  38. if ($with_self) {
  39. $admin_ids[] = admin_id();
  40. }
  41. return array_unique($admin_ids);
  42. }
  43. /**
  44. * 兼容旧版本
  45. * @param int $admin_id
  46. * @deprecated
  47. * @return bool
  48. */
  49. public static function isSupperAdmin(int $admin_id = 0): bool
  50. {
  51. return static::isSuperAdmin($admin_id);
  52. }
  53. /**
  54. * 是否是超级管理员
  55. * @param int $admin_id
  56. * @return bool
  57. */
  58. public static function isSuperAdmin(int $admin_id = 0): bool
  59. {
  60. if (!$admin_id) {
  61. if (!$roles = admin('roles')) {
  62. return false;
  63. }
  64. } else {
  65. $roles = AdminRole::where('admin_id', $admin_id)->pluck('role_id');
  66. }
  67. $rules = Role::whereIn('id', $roles)->pluck('rules');
  68. return $rules && in_array('*', $rules->toArray());
  69. }
  70. }