| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace App\Http\Controllers;
- use App\Authority;
- use App\Components\AsyncResponse;
- use App\Services\common\BatchUpdateService;
- use App\User;
- use Illuminate\Support\Facades\Auth;
- use Illuminate\Support\Facades\Gate;
- use Illuminate\Support\Facades\Validator;
- class AuthorityController extends Controller
- {
- use AsyncResponse;
- public function index()
- {
- if (!Gate::allows('权限-查询')){return view("exception.authority"); }
- $authorities = app("AuthorityService")->format(Authority::query()->get());
- return view('maintenance.authority.index',['authorities'=>$authorities]);
- }
- public function store()
- {
- $this->gate("权限-录入");
- $errors = Validator::make(\request()->input(),
- ['parent_id'=>['nullable',"integer"],
- 'name'=>'required',
- 'alias_name'=>['required','unique:authorities,alias_name'],
- 'permission'=>'required',
- ],[
- 'integer'=>':attribute 非法参数',
- 'required'=>':attribute 必填',
- ],[
- 'parent_id'=>'父级',
- 'name'=>'权限名',
- 'alias_name'=>'唯一标识',
- 'permission'=>'许可',
- 'unique'=>'重复'
- ])->errors();
- if ($errors->count()>0)$this->success(["errors"=>$errors]);
- $authority = Authority::query()->create([
- 'name' => \request("name"),
- 'parent_id' => \request("parent_id"),
- 'alias_name' => \request("alias_name"),
- 'permission' => \request("permission")
- ]);
- app("AuthorityService")->removeAdminAuth();
- $this->success($authority);
- }
- public function update()
- {
- $this->gate("权限-编辑");
- $list = request("list");
- if (!$list || count($list)<1)$this->success();
- array_unshift($list,["id","name"]);
- app(BatchUpdateService::class)->batchUpdate("authorities",$list);//更新权限名
- app("AuthorityService")->removeAllAuth();//刷掉权限缓存
- $updateMenu = [["id","name"]];
- $mapping = array_flip(app("MenuService")->getMenuAndAuthorityMapping());//获取菜单与权限映射并反转
- foreach (request("list") as $data)if (isset($mapping[$data["id"]]))$updateMenu[] = ["id"=>$mapping[$data["id"]],"name"=>$data["name"]];//验证更新的权限中是否存在有映射关系的缓存并记录
- if (count($updateMenu)>1){
- app(BatchUpdateService::class)->batchUpdate("menus",$updateMenu);//存在映射关系的缓存更新映射对象
- app("MenuService")->setMenu();//重建菜单缓存
- }
- $this->success();
- }
- public function destroy()
- {
- $this->gate("权限-删除");
- Authority::query()->whereIn('id',request("ids"))->get()->each(function ($auth){$auth->delete();});
- app("AuthorityService")->removeAllAuth();//刷掉权限缓存
- $this->success();
- }
- public function getAuthoritiesApi()
- {
- /** @var User $user */
- $user = Auth::user();
- if(!$user) $this->success(null);
- if($user && $user->isSuperAdmin()){
- $this->success( Authority::query()->orderBy('name')->get());
- }
- $authority = $user->authorities();
- $this->success($authority);
- }
- }
|