/** * 检查权限 */ public function power_check() { /** * var_dump(request()->method()); * string 'GET' (length=3) * var_dump(Route::currentRouteAction()); * string 'App\Http\Controllers\Admin\GroupController@get_list' (length=51) */ // route $route = Route::currentRouteAction(); $temp_r = explode('@', $route); $temp_ctl = explode('\\', $temp_r[0]); // controller acction method $controller = end($temp_ctl); // controller $action = end($temp_r); // action $method = request()->method(); // method // delete temp var unset($temp_r); unset($temp_ctl); $oAdmin = Admin::findOrFail(session('admin_id')); $oGroups = AdminGroup::whereIn('id', json_decode($oAdmin->groups))->get(); $oPowers = Power::where('controller', $controller)->where('action', $action)->get(); $aPowers = array_column($oPowers->toArray(), 'method', 'id'); /** * 选出继续操作需要的权限ID */ $iNeedPower = null; // id foreach ($aPowers as $key => $value) { if ($value === $method || $value === '') { $iNeedPower = $key; break; } } if ($iNeedPower === null) { // 没有此权限记录 return False; } /** * 检查用户所属的组中有没有拥有这种权限的组 */ $flag = False; foreach ($oGroups as $oGroup) { $powers = json_decode($oGroup->power); $powers = empty($powers) ? array() : $powers; if (in_array($iNeedPower, $powers)) { $flag = True; break; } } return $flag; }
/** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit(Request $request, $id) { // $oGroup = Group::findOrFail($id); // 需要更新的组 $powers = Group::get_group_power($id); // 组拥有的权限 $oAllPowers = Power::select(['id', 'category', 'name'])->get(); // 全部的权限 // 按分类分开 $aCategoryPowers = array(); foreach ($oAllPowers as $k => $v) { $aCategoryPowers[$v->category][] = ['id' => $v->id, 'name' => $v->name]; } if ($request->isMethod('get')) { return view('admin.group.edit', ['group' => $oGroup, 'power_categorys' => $aCategoryPowers, 'powers' => $powers]); } // post $sGroupName = $request->input('groupname', $oGroup->groupname); $aGroupPower = $request->input('powers', array()); $aAllPowers = array_column($oAllPowers->toArray(), 'id'); try { $j = count($aGroupPower); for ($i = 0; $i < $j; $i++) { $aGroupPower[$i] = intval($aGroupPower[$i]); if (!in_array($aGroupPower[$i], $aAllPowers)) { // 权限不存在 unset($aGroupPower[$i]); } } } catch (Exception $e) { App::abort(404); } // 超级管理员的权限永远是所有,无法更改的 // 只有名字可以修改 if ($oGroup->id != 1) { Group::update_powers($id, $aGroupPower); } $oGroup->save(); session()->flash('msg_success', '修改成功'); return back(); }
/** * @return \yii\db\ActiveQuery */ public function getPowers() { return $this->hasMany(Power::className(), ['admin_id' => 'admin_id']); }