| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- <?php
- namespace App\Providers;
- use App\Authority;
- use App\Services\AuthorityService;
- use App\Services\CacheService;
- use App\User;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\Gate;
- use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
- use Illuminate\Support\Facades\Schema;
- class AuthServiceProvider extends ServiceProvider
- {
- /**
- * The policy mappings for the application.
- *
- * @var array
- */
- protected $policies = [
- // 'App\Model' => 'App\Policies\ModelPolicy',
- ];
- /**
- * Register any authentication / authorization services.
- *
- * @return void
- */
- public function boot()
- {
- $this->registerPolicies();
- $isSuperAdmin = null;
- if(!Schema::hasTable('users')){return;}
- /** @var CacheService $cacheService */
- $cacheService = app('CacheService');
- Gate::before(function ($user)use(&$isSuperAdmin) {
- if($isSuperAdmin===null){
- $isSuperAdmin=$user->isSuperAdmin();
- }
- if ($isSuperAdmin) {
- Cache::put('isSuperAdmin', true);
- }else{
- Cache::put('isSuperAdmin', false);
- }
- });
- if(!Schema::hasTable('authorities')){return;}
- $authorities=$cacheService->getOrExecute('authorities',function (){
- return Authority::with('roles')->get();
- });
- foreach($authorities as $authority) {
- Gate::define($authority->name, function($user) use ($authority,$cacheService) {
- if(Cache::get('isSuperAdmin')){
- if($authority['permission']=='允许'){
- return true;
- }
- }
- $authorityRoles=$cacheService->getOrExecute("authority{$authority['id']}->roles",function ()use($authority){
- return $authority->roles;
- });
- return $user->hasRole($authorityRoles);
- });
- }
- }
- }
|