AuthServiceProvider.php 2.4 KB

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