AuthServiceProvider.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Providers;
  3. use App\Authority;
  4. use App\Services\AuthorityService;
  5. use App\Services\CacheService;
  6. use App\Services\UserService;
  7. use App\User;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Support\Facades\Cache;
  10. use Illuminate\Support\Facades\Gate;
  11. use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
  12. use Illuminate\Support\Facades\Schema;
  13. class AuthServiceProvider extends ServiceProvider
  14. {
  15. /**
  16. * The policy mappings for the application.
  17. *
  18. * @var array
  19. */
  20. protected $policies = [
  21. // 'App\Model' => 'App\Policies\ModelPolicy',
  22. ];
  23. /**
  24. * Register any authentication / authorization services.
  25. *
  26. * @return void
  27. */
  28. public function boot()
  29. {
  30. $this->registerPolicies();
  31. $isSuperAdmin = null;
  32. if(!Schema::hasTable('users')){return;}
  33. /** @var CacheService $cacheService */
  34. $cacheService = app('CacheService');
  35. Gate::before(function ($user)use(&$isSuperAdmin) {
  36. if($isSuperAdmin===null){
  37. $isSuperAdmin=$user->isSuperAdmin();
  38. }
  39. if ($isSuperAdmin) {
  40. Cache::put('isSuperAdmin', true);
  41. }else{
  42. Cache::put('isSuperAdmin', false);
  43. }
  44. });
  45. if(!Schema::hasTable('authorities')){return;}
  46. $authorities=$cacheService->getOrExecute('authorities',function (){
  47. return Authority::with('roles')->get();
  48. });
  49. foreach($authorities as $authority) {
  50. Gate::define($authority->name, function($user) use ($authority,$cacheService) {
  51. if(Cache::get('isSuperAdmin')){
  52. if($authority['permission']=='允许'){
  53. return true;
  54. }
  55. }
  56. $authorityRoles=$cacheService->getOrExecute("authority{$authority['id']}->roles",function ()use($authority){
  57. return $authority->roles;
  58. });
  59. /** @var UserService $userService */
  60. $userService = app('UserService');
  61. return $userService->hasRoles($user,$authorityRoles);
  62. });
  63. }
  64. }
  65. }