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