AuthServiceProvider.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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\OwnerSundryFeeDetail::class => \App\Policies\OwnerSundryFeeDetailPolicy::class,
  23. // 'App\Model' => 'App\Policies\ModelPolicy',
  24. CustomerLog::class => CustomerLogPolice::class,
  25. CustomerLogStatus::class => CustomerLogStatusesPolice::class,
  26. ];
  27. /**
  28. * Register any authentication / authorization services.
  29. *
  30. * @return void
  31. */
  32. public function boot()
  33. {
  34. $this->registerPolicies();
  35. $isSuperAdmin = null;
  36. if(!Schema::hasTable('users')){return;}
  37. /** @var CacheService $cacheService */
  38. $cacheService = app('CacheService');
  39. Gate::before(function ($user)use(&$isSuperAdmin) {
  40. if($isSuperAdmin===null){
  41. $isSuperAdmin=$user->isSuperAdmin();
  42. }
  43. if ($isSuperAdmin) {
  44. Cache::put('isSuperAdmin'.$user['id'], true);
  45. }else{
  46. Cache::put('isSuperAdmin'.$user['id'], false);
  47. }
  48. });
  49. if(!Schema::hasTable('authorities')){return;}
  50. $authorities=$cacheService->getOrExecute('authorities',function (){
  51. return Authority::with('roles')->get();
  52. });
  53. foreach($authorities as $authority) {
  54. Gate::define($authority->alias_name, function($user) use ($authority,$cacheService) {
  55. if(Cache::get('isSuperAdmin'.$user['id'])){
  56. if($authority['permission']=='允许'){
  57. return true;
  58. }
  59. }
  60. $authorityRoles=$cacheService->getOrExecute("authority{$authority['id']}->roles",function ()use($authority){
  61. return $authority->roles;
  62. });
  63. /** @var UserService $userService */
  64. $userService = app('UserService');
  65. return $userService->hasRoles($user,$authorityRoles);
  66. });
  67. }
  68. }
  69. }