AuthServiceProvider.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. Gate::before(function ($user) {
  38. return true;
  39. });
  40. $isSuperAdmin = null;
  41. if(!Schema::hasTable('users')){return;}
  42. /** @var CacheService $cacheService */
  43. $cacheService = app('CacheService');
  44. Gate::before(function ($user)use(&$isSuperAdmin) {
  45. if($isSuperAdmin===null){
  46. $isSuperAdmin=$user->isSuperAdmin();
  47. }
  48. if ($isSuperAdmin) {
  49. Cache::put('isSuperAdmin'.$user['id'], true);
  50. }else{
  51. Cache::put('isSuperAdmin'.$user['id'], false);
  52. }
  53. });
  54. if(!Schema::hasTable('authorities')){return;}
  55. $authorities=$cacheService->getOrExecute('authorities',function (){
  56. return Authority::with('roles')->get();
  57. });
  58. foreach($authorities as $authority) {
  59. Gate::define($authority->alias_name, function($user) use ($authority,$cacheService) {
  60. if(Cache::get('isSuperAdmin'.$user['id'])){
  61. if($authority['permission']=='允许'){
  62. return true;
  63. }
  64. }
  65. $authorityRoles=$cacheService->getOrExecute("authority{$authority['id']}->roles",function ()use($authority){
  66. return $authority->roles;
  67. });
  68. /** @var UserService $userService */
  69. $userService = app('UserService');
  70. return $userService->hasRoles($user,$authorityRoles);
  71. });
  72. }
  73. }
  74. }