AuthServiceProvider.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. Gate::before(function ($user){
  35. if (config("app.env") == 'local')return true;
  36. });
  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'.$user['id'], true);
  47. }else{
  48. Cache::put('isSuperAdmin'.$user['id'], 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->alias_name, function($user) use ($authority,$cacheService) {
  57. if(Cache::get('isSuperAdmin'.$user['id'])){
  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. }