request;
/**
* 组织SQL
*/
$permQuery = new Query();
$permQuery->select(['auth_perm.*']);
$permQuery->from('auth_perm');
$permQuery->leftJoin('auth_perms_routes', '`auth_perms_routes`.`perm_id` = `auth_perm`.`perm_id`');
$permQuery->groupBy('auth_perm.perm_id');
$permQuery->orderBy('auth_perm.perm_id DESC');
/**
* 过滤
*/
$keyword = $request->get("keyword");
if ($keyword) {
$permQuery->where(['or',
['like','name',$keyword],
['like','route',$keyword],
]);
}
$get['keyword'] = $keyword;
/**
* 分页处理
*/
$pageSize = $request->get("pageSize") ? (int) $request->get("pageSize") : 20;
$pages = new Pagination(['totalCount' => $permQuery->count(), 'pageSize' => $pageSize]);
$perms = $permQuery->offset($pages->offset)->limit($pages->limit)->all();
/**
* 数据整理
*/
$data = [];
foreach ($perms as $perm) {
$routes = (new Query)->select('route')
->from('auth_perms_routes')
->where(['perm_id' => $perm['perm_id']])->column();
$routes = implode("
", $routes);
$data[] = [
'id' => $perm['perm_id'],
'name' => $perm['name'],
'route' => $routes,
];
}
/**
* 渲染模板
*/
return $this->render('index', [
'perms' => $data,
'pages' => $pages,
'get' => $get,
]);
}
/**
* 新增界面
*/
public function actionCreate()
{
return $this->render('create');
}
/**
* 新增执行动作
*/
/*
public function actionDoAdd()
{
$post = Yii::$app->request->post();
if (empty($post)) {
return;
}
$name = isset($post['name']) ? $post['name'] : '';
$routes = isset($post['routes']) ? $post['routes'] : '';
$connection = Yii::$app->db;
$transaction = $connection->beginTransaction();
try {
$connection->createCommand()->insert('auth_perm', [
'name' => $name,
])->execute();
$permId = $connection->getLastInsertID();
if ($routes) {
$routes = explode("\n", $routes);
foreach ($routes as $route) {
if ($route = trim($route)) {
$connection->createCommand()->insert('auth_perms_routes', [
'perm_id' => $permId,
'route' => $route,
])->execute();
}
}
}
$transaction->commit();
// 重置缓存
Yii::$app->authManager->invalidateCache();
} catch (Exception $e) {
Yii::$app->session->setFlash('danger', '数据保存失败,请重新操作');
$transaction->rollBack();
return $this->redirect(['/mall/perm/create']);
}
Yii::$app->session->setFlash('success', '权限添加完成');
return $this->redirect(['index']);
}
*/
/**
* 更新界面
*/
public function actionUpdate($id)
{
$auth = Yii::$app->authManager;
$perm = $auth->getPerm($id);
$routes = (new Query)->select('route')
->from('auth_perms_routes')
->where(['perm_id' => $id])->column();
$routes = implode("\n", $routes);
return $this->render('update', [
'perm' => $perm,
'routes' => $routes
]);
}
/**
* 更新执行动作
*/
public function actionDoUpdate($id)
{
$post = Yii::$app->request->post();
if (empty($post)) {
return;
}
$name = isset($post['name']) ? $post['name'] : '';
$routes = isset($post['routes']) ? $post['routes'] : '';
$auth = Yii::$app->authManager;
$perm = $auth->getPerm($id);
$connection = Yii::$app->db;
$transaction = $connection->beginTransaction();
try {
$connection->createCommand()
->update('auth_perm', [
'name' => $name,
], [
'perm_id' => $perm->permId,
])->execute();
// 删除旧routes
$connection->createCommand()
->delete('auth_perms_routes', ['perm_id' => $perm->permId])
->execute();
if ($routes) {
$routes = explode("\n", $routes);
foreach ($routes as $route) {
if ($route = trim($route)) {
$connection->createCommand()->insert('auth_perms_routes', [
'perm_id' => $perm->permId,
'route' => $route,
])->execute();
}
}
}
$transaction->commit();
// 重置缓存
Yii::$app->authManager->invalidateCache();
} catch (Exception $e) {
Yii::$app->session->setFlash('danger', '数据保存失败,请重新操作');
$transaction->rollBack();
return $this->redirect(['index']);
}
Yii::$app->session->setFlash('success', '权限更新完成');
return $this->redirect(['index']);
}
/**
* 删除执行动作
*/
/*
public function actionDelete($id)
{
$connection = Yii::$app->db;
$transaction = $connection->beginTransaction();
try {
$connection->createCommand()
->delete('auth_perms_routes', ['perm_id' => $id])
->execute();
$connection->createCommand()
->delete('auth_perm', ['perm_id' => $id])
->execute();
$transaction->commit();
Yii::$app->session->setFlash('success', '权限删除完成');
// 重置缓存
Yii::$app->authManager->invalidateCache();
} catch (Exception $e) {
Yii::$app->session->setFlash('danger', '数据保存失败,请重新操作');
$transaction->rollBack();
}
return $this->redirect(['index']);
}
*/
/**
* @return string
*/
public function actionSetRouter()
{
$route = new Route();
$modules = Yii::$app->modules;
$allRoutes = [];
$notConfirmActions = [];
$delActions = [];
foreach ($modules as $k => $module) {
if ('debug' == $k || 'gii' == $k) {
continue;
}
$routes = $route->getHtAppRoutes($k);
$allRoutes = ArrayHelper::merge($allRoutes, $routes);
}
$confirmActions = AuthPermRepository::getPermsRouters('perm_id >0');
$tmpConfirmActions = [];
if ($confirmActions) {
foreach($confirmActions as $k => $v) {
$tmpConfirmActions[] = $v['route'];
}
}
if ($tmpConfirmActions) {
$tmpConfirmActions = array_unique($tmpConfirmActions);
foreach($allRoutes as $k => $v) {
if (in_array($v, $tmpConfirmActions)) {
continue;
}
$notConfirmActions[] = $v;
}
foreach($tmpConfirmActions as $kk => $vv) {
if (in_array($vv, $allRoutes)) {
continue;
}
$delActions[] = $vv;
}
} else {
$notConfirmActions = $allRoutes;
}
$groupActions = AuthPermRepository::getGroupPermsRouters($confirmActions);
return $this->render('set_router', [
'groupActions' => $groupActions,
'notConfirmActions' => $notConfirmActions,
'delActions' => $delActions,
]);
}
/**
* @return string
*/
public function actionGetGroupPerm()
{
$e = new stdClass();
$req = Yii::$app->request;
$route = $req->post('route');
$list = [];
// 解析$route 判读是用哪个level
$currLevel = AuthPermRepository::routeLevel($route);
$condition = ['=', 'level', $currLevel - 1];
$actions = AuthPermRepository::getAllItems($condition);
foreach ($actions as $k => $v) {
$list[] = ['id' => $v->perm_id, 'name' => $v->name];
}
$e->list = $list;
return $this->renderJson($e);
}
/**
* @return string
*/
public function actionCreatePerm()
{
$e = new stdClass();
$e->success = false;
$req = Yii::$app->request;
$route = $req->post('route');
$permGroup = $req->post('permGroup');
$permName = $req->post('routeName');
$permId = $req->post('routeId');
$routeDesc = $req->post('routeDesc');
$level = AuthPermRepository::routeLevel($route);
if (empty($route)) {
$e->message = '请传入路由';
return $this->renderJson($e);
}
if (AuthPerm::LEVEL_ACTION == $level && $permId) {
$authRoute = AuthPermRepository::findOne($permId);
$routeStr = null;
if (!$authRoute) {
$e->message = '未找到对应的权限组';
return $this->renderJson($e);
}
$result = AuthPerm::createRouter($permId, $route);
if ($result) {
$e->success = true;
} else {
$e->message = '提交失败';
}
return $this->renderJson($e);
}
$checkE = $this->checkRouteName($permName, $level);
if (!$checkE->success) {
$e->message = $checkE->message;
return $this->renderJson($e);
}
if (AuthPerm::LEVEL_MODULE == $level) {
$parentId = 0;
} else if(AuthPerm::LEVEL_CONTROLLER == $level) {
$parentId = $permGroup;
} else if(AuthPerm::LEVEL_ACTION == $level) {
$parentId = $permGroup;
} else {
$e->message = '创建失败';
return $this->renderJson($e);
}
$item = [
'name' => $permName, 'desc' => $routeDesc, 'level' => $level,
'parent_id' => $parentId
];
$routers = [$route];
AuthPerm::createWithRouters($item, $routers);
$e->success = true;
return $this->renderJson($e);
}
/**
* @param $routeName
* @param $level
* @return stdClass
*/
private function checkRouteName($routeName, $level)
{
$e = new stdClass();
$e->success = false;
if (empty($routeName)) {
$e->message = '权限名为空';
return $e;
}
$routerModel = AuthPermRepository::findOne(['name' => $routeName, 'level' => $level]);
if (!$routerModel) {
$e->message = '';
$e->success = true;
} else {
$e->message = '权限名已存在';
}
return $e;
}
/**
* @return string
*/
public function actionSearchPerm()
{
$e = new stdClass();
$req = Yii::$app->request;
$query = $req->post('query');
$route = $req->post('route');
$list = [];
$condition = [
'and',
['like', 'name', $query],
['=', 'level', AuthPerm::LEVEL_ACTION]
];
$actions = AuthPermRepository::getAllItems($condition, 15);
foreach ($actions as $k => $v) {
$list[] = ['id' => $v->perm_id, 'name' => $v->name];
}
$e->list = $list;
return $this->renderJson($e);
}
/**
* @return string
* @throws \Exception
*/
public function actionDelInvalidAction()
{
$req = Yii::$app->request;
$route = $req->post('route');
$e = new stdClass();
$e->success = false;
if (empty($route)) {
$e->message = '路由为空';
return $this->renderJson($e);
}
$condition = ['=', 'route', $route];
$actions = AuthPermRepository::getPermsRouters($condition);
if (!$actions) {
$e->message = '未找到该路由记录';
return $this->renderJson($e);
}
$permIds = [];
foreach($actions as $k => $item) {
$permIds[] = $item->perm_id;
AuthPermsRoutesModel::deleteAll(['perm_id' => $item->perm_id, 'route' => $route]);
}
if ($permIds) {
$permIds = array_unique($permIds);
}
$authPerms = AuthPermRepository::getPermsRouters(['perm_id' => $permIds], true);
if ($authPerms) {
$indexRouters = ArrayHelper::index($authPerms, 'perm_id');
$deletePermArr = [];
foreach ($permIds as $k => $id) {
if (isset($indexRouters[$id])) {
continue;
}
$deletePermArr[] = $id;
}
if ($deletePermArr) {
AuthPerm::deleteAll(['perm_id' => $deletePermArr]);
}
}
$e->success = true;
return $this->renderJson($e);
}
/*
* 编辑权限
*/
public function actionEditPerm()
{
$e = new stdClass();
$e->success = false;
$e->routes = '';
$req = Yii::$app->request;
$id = $req->post('id');
$permName = trim($req->post('permName'));
$permRoutes = trim($req->post('permRoutes'));
$permDesc = trim($req->post('permDesc'));
$authPerm = AuthPermRepository::findOne($id);
if (!$authPerm) {
$e->message = '未找到记录';
return $this->renderJson($e);
}
$currLevel = $authPerm->level;
$checkAuthName = AuthPermRepository::findOne("name ='{$permName}' and level = {$currLevel} and id <> {$id}");
if ($checkAuthName) {
$e->message = '存在同名的权限组名';
return $this->renderJson($e);
}
$permRoutes = str_replace("\r\n",',',$permRoutes);
$permRoutes = str_replace("\r",',',$permRoutes);
$permRoutes = str_replace("\n",',',$permRoutes);
$permRoutes = str_replace(",",',',$permRoutes);
$permRouteArr = explode(',', $permRoutes);
$transaction = Yii::$app->getDb()->beginTransaction();
try {
$authPerm->name = $permName;
$authPerm->desc = $permDesc;
$authPerm->save();
AuthPerm::deletePermRouters($id);
foreach ($permRouteArr as $k => $v) {
AuthPerm::createRouter($id, $v);
}
$transaction->commit();
$e->routes = $permRoutes;
$e->success = true;
return $this->renderJson($e);
} catch (Exception $ex){
$transaction->rollBack();
$e->message = '添加失败';
return $this->renderJson($e);
}
}
/**
* @return string
*/
public function actionDelPerm()
{
$e = new stdClass();
$e->success = false;
$req = Yii::$app->request;
$id = $req->post('id');
$authPermModel = AuthPermRepository::findOne($id);
if (!$authPermModel) {
$e->message = '未找到记录';
return $this->renderJson($e);
}
if (AuthPerm::LEVEL_ACTION != $authPermModel->level) {
$e->message = '只能删除权限组';
return $this->renderJson($e);
}
$transaction = Yii::$app->getDb()->beginTransaction();
try {
$authPermModel->delete();
AuthPerm::deletePermRouters($id);
$transaction->commit();
$e->success = true;
} catch (Exception $ex) {
$transaction->rollBack();
$e->message = '删除失败';
}
return $this->renderJson($e);
}
/**
* 初始化当前权限表部分路由
*/
public function actionInitControls()
{
$modules = Yii::$app->modules;
$permission = [];
$modulesArr = [];
foreach ($modules as $name => $class) {
if ('debug' == $name || 'gii' == $name) {
continue;
}
$module = Yii::$app->getModule($name);
$modulesArr[] = $name.'/*';
if (!empty($module->params['perm'])) {
echo $name.'/*'.">>>>>\r\n";
$permission[$name] = $module->params['perm'];
}
}
// init module
$authPermModel = AuthPermModel::find();
$authPermModel->alias('a');
$authPermModel->select('a.perm_id, a.name, r.route');
$authPermModel->leftJoin(AuthPermsRoutesModel::tableName()." as r", 'r.perm_id = a.perm_id');
$authPermModel->where(['a.level' => AuthPerm::LEVEL_MODULE]);
$authPermModel->andWhere([
'r.route' => $modulesArr
]);
$authPermModel->asArray();
$exitModules = $authPermModel->all();
$routes = ArrayHelper::getColumn($exitModules,'route');
foreach($modulesArr as $K => $v) {
if (in_array($v, $routes)) {
continue;
}
$saveRoute = [$v];
$item = ['name' => $v, 'parent_id' => 0, 'level' => AuthPerm::LEVEL_MODULE, 'desc' => ''];
AuthPerm::createWithRouters($item, $saveRoute);
echo "create module:".$v ."
\r\n";
}
echo "====== end init module ======
\r\n";
echo "============== start init controller ==========
\r\n";
$indexModules = ArrayHelper::index($exitModules, 'route');
foreach ($permission as $kk => $perm) {
$moduleIndex = $kk.'/*';
$moduleId = 0;
if (isset($indexModules[$moduleIndex])) {
$moduleId = $indexModules[$moduleIndex]['perm_id'];
}
if (empty($moduleId)) {
continue ;
}
foreach($perm['items'] as $kkk => $actions) {
$authPermModel = AuthPermModel::find();
$authPermModel->alias('a');
$authPermModel->select('a.perm_id, a.name, r.route, a.parent_id');
$authPermModel->leftJoin(AuthPermsRoutesModel::tableName()." as r", 'r.perm_id = a.perm_id');
$authPermModel->where(['a.level' => AuthPerm::LEVEL_CONTROLLER]);
$authPermModel->andWhere(['>', 'a.parent_id', 0]);
$authPermModel->andWhere([
'r.route' => $actions['path']
]);
$authPermModel->asArray();
$exitController = $authPermModel->one();
$controllerId = 0;
if ($exitController) {
$controllerId = $exitController['perm_id'];
} else {
$saveRoute = [$actions['path']];
$item = ['name' => $actions['label'], 'parent_id' => $moduleId, 'level' => AuthPerm::LEVEL_CONTROLLER, 'desc' => ''];
$saveResult = AuthPerm::createWithRouters($item, $saveRoute);
if ($saveResult) {
$controllerId = $saveResult[0]->perm_id;
}
}
echo "moduleId => {$moduleId} ==== controller => {$controllerId} ==== \r\n";
if ($controllerId) {
$keys = array_keys($actions['items']);
AuthPermModel::updateAll(['parent_id' => $controllerId], ['perm_id' => $keys]);
}
}
}
}
}