AuthServiceProvider.php 2.0 KB

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