AuthServiceProvider.php 2.4 KB

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