Browse Source

完善分配用户的角色,分配角色下的用户

tangs 5 years ago
parent
commit
d64832b612

+ 90 - 7
app/Http/Controllers/PermissionController.php

@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
 
 use App\Models;
 use foo\bar;
+use function GuzzleHttp\Psr7\str;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Validator;
@@ -57,26 +58,108 @@ class PermissionController extends Controller
     }
 
     /**
-     * 分配用户权限,是管理员或者普通用户的权限
+     * 分配某个用户所拥有的角色
      *
      * @param Request $request
      * @return string
      */
     public function AssignUserRole(Request $request)
     {
-        $uid = $request->input("uid");
-        $roles = $request->input("roles");
+        $validator = Validator::make($request->all(), [
+            "userId" => "required|min:1",
+//            "roleIds" => "array",
+//            "roleIds.*" => "integer",
+        ]);
+        if ($validator->fails()) {
+            return $this->fail(REQUEST_PARAM_ERROR, $this->error[REQUEST_PARAM_ERROR], $validator->errors());
+        }
+        $uid = $request->input("userId");
+        $roleIdsStr = $request->input("roleIds");
+        $roleIds = $this->GetArrayInt($roleIdsStr);
+        if (0 == $roleIds) {
+            return $this->fail(PARAM_ARRAY_INT, $this->error[PARAM_ARRAY_INT]);
+        }
+
+        // 判断当前用户是否有权分配权限
+        $currentUid = 1;
+        $userRole = new Models\UserRole();
+        $role = $userRole->LoadRoleByUid($currentUid);
+
+        if (!$role || $role["status"] != "normal" || $role["role"] != "admin") {
+//            return $this->fail(PERMISSION_DENIED, $this->error[PERMISSION_DENIED]);
+        }
+
+        // 有权分配
+        $result = $userRole->AssignUserRoles($uid, $roleIds);
+        if ($result["code"] == 0) {
+            return $this->success($result["data"]);
+        }
+        return $this->fail($result["code"], $this->error[$result["code"]]);
+    }
+
+    /**
+     * 指定角色下有哪些用户,注意和AssignUserRoles区别
+     *
+     * @param Request $request
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function AssignRoleUser(Request $request)
+    {
+        $validator = Validator::make($request->all(), [
+            "roleId" => "required|min:1",
+//            "userIds" => "array",
+//            "userIds.*" => "integer",
+        ]);
+        if ($validator->fails()) {
+            return $this->fail(REQUEST_PARAM_ERROR, $this->error[REQUEST_PARAM_ERROR], $validator->errors());
+        }
+
+        $roleId = $request->input("roleId");
+        $userIdsStr = $request->input("userIds");
+        $userIds = $this->GetArrayInt($userIdsStr);
+        if (0 == $userIds) {
+            return $this->fail(PARAM_ARRAY_INT, $this->error[PARAM_ARRAY_INT]);
+        }
 
+//      判断当前用户是否有权分配权限
         $currentUid = 1;
         $userRole = new Models\UserRole();
         $role = $userRole->LoadRoleByUid($currentUid);
 
-        if (!$role || $role->status != "normal" || $role->role & 1 == 0) {
-            return "permission denied";
+        if (!$role || $role["status"] != "normal" || $role["role"] != "admin") {
+//            return $this->fail(PERMISSION_DENIED, $this->error[PERMISSION_DENIED]);
         }
 
         // 有权分配
-        $userRole->AssignRoles($uid, $role);
-        return"success";
+        $result = $userRole->AssignRoleUsers($roleId, $userIds);
+        if ($result["code"] == 0) {
+            return $this->success($result["data"]);
+        }
+        return $this->fail($result["code"], $this->error[$result["code"]]);
+
+    }
+
+    /**
+     * 把传入的参数检查是不是正确的int数组,并且每个数字必须大于0。
+     *
+     * @param $str
+     * @return array|int
+     */
+    private function GetArrayInt($str)
+    {
+        $str = trim($str);
+        if ($str == "") {
+            return [];
+        }
+        $intArray = [];
+        $multi = explode(",", $str);
+        foreach ($multi as $m) {
+            $mInt = (int)$m;
+            if ($mInt < 1) {
+                return 0;
+            }
+            array_push($intArray, $mInt);
+        }
+        return $intArray;
     }
 }

+ 17 - 0
app/Models/Role.php

@@ -123,6 +123,23 @@ class Role extends Model
         return $data;
     }
 
+    public function LoadRoleByIds($rids)
+    {
+        $data = $this->select("id", "name", "description", "status")
+            ->whereIn("id", $rids)->where("is_del", false)->get();
+        return $data;
+    }
+
+    public function LoadRoleByIds_KV($rids)
+    {
+        $roles = $this->LoadRoleByIds($rids);
+        $data = [];
+        foreach ($roles as $role){
+            $data[$role["id"]] = $role;
+        }
+        return $data;
+    }
+
     public function LoadRole($uid)
     {
         $roles = $this->where("user_id", $uid)->where("is_del", false)->get();

+ 2 - 6
app/Models/UserActionBar.php

@@ -14,7 +14,7 @@ class UserActionBar extends Model
     /**
      * 配置角色/用户/群组有权限的action bars,当前的做法是,
      * 每次更新都先把ownerId和ownerType匹配的数据全部标记删除,
-     * 然后批量插入新的配置的action bars数据行。
+     * 然后批量插入新的配置的action bars数据行。
      *
      * @param $ownerType 拥有者用户类型
      * @param $ownerId 拥有者用户id
@@ -34,10 +34,6 @@ class UserActionBar extends Model
         $this->where("owner_type", $ownerType)->where("owner_id", $ownerId)->where("is_del", false)
             ->update(["is_del" => true]);
 
-        Log::debug(gettype($barIds));
-        Log::debug(count($barIds));
-        Log::debug($barIds);
-
         // 重新添加ownerType 和 ownerId的数据
         if (count($barIds) < 1) {
             return ["code" => SUCCESS, "data" => []];
@@ -49,7 +45,7 @@ class UserActionBar extends Model
         }
         $this->insert($data);
 
-        // 插入批量插入的数据,并返回给前端
+        // 查出批量插入的数据,并返回给前端
         $new_data = $this->select("id", "owner_type", "owner_id", "bar_id", "status")
             ->where("owner_type", $ownerType)->where("owner_id", $ownerId)->where("is_del", false)->get();
 

+ 83 - 17
app/Models/UserRole.php

@@ -12,29 +12,95 @@ class UserRole extends Model
     protected $table = "user_roles";
     public $timestamps = false;
 
-    public function AssignRoles($uid, array $roles)
+    /**
+     * 配置用户的角色,当前的做法是,
+     * 每次更新都先把userId匹配的数据全部标记删除
+     * 然后批量插入新的配置的角色数据
+     *
+     * @param $uid
+     * @param array $roles
+     * @return array
+     */
+    public function AssignUserRoles($uid, array $roles)
     {
-        $checkData = $this->select("id")
-            ->where("user_id", $uid)
-            ->where("is_del", false)
-            ->first;
+        if ($uid < 1) {
+            return ["code" => INVALID_USER_ID];
+        }
+
+        // 删除当前用户所有的角色
+        $this->where("user_id", $uid)->where("is_del", false)->update(["is_del" => true]);
 
-        $r = 0;
+        if (count($roles) < 1) {
+            return ["code" => SUCCESS, "data" => ["roles" => []]];
+        }
+
+        // 重新添加用户角色新配置的角色数据
+        $data = [];
         foreach ($roles as $role) {
-            $r = $r & $role;
+            array_push($data, ["user_id" => $uid, "role_id" => $role]);
         }
+        $this->insert($data);
 
-        if (!$checkData) {
-            // 插入新数据
-            $this->user_id = $uid;
-            $this->roles = $r;
-            $this->save();
-        } else {
-            // 更新旧角色
-            $this->roles = $r;
-            $this->save();
+//         查出批量插入的数据,并返回给前端
+        $new_data = $this->select("id", "user_id", "role_id", "status")->where("user_id", $uid)->where("is_del", false)
+            ->orderBy("role_id", "asc")->get();
+        $rids = [];
+        foreach ($new_data as $nd) {
+            array_push($rids, $nd["role_id"]);
         }
-        return"success";
+        if (count($rids) > 0) {
+            $role = new Role();
+            $roleInfo = $role->LoadRoleByIds_KV($rids);
+        }
+        $result = ["roles" => $new_data, "roleInfo" => $roleInfo];
+
+        return ["code" => SUCCESS, "data" => $result];
+    }
+
+
+    /**
+     * 配置角色下的用户数据,当前的做法是,
+     * 每次更新都先把roleId匹配的数据全部标记删除
+     * 然后批量插入新的配置的用户数据
+     *
+     * @param $rid
+     * @param array $userIds
+     * @return array
+     */
+    public function AssignRoleUsers($rid, array $userIds)
+    {
+        if ($rid < 1) {
+            return ["code" => INVALID_ROLE_ID];
+        }
+
+        // 删除当前角色所有的用户
+        $this->where("role_id", $rid)->where("is_del", false)->update(["is_del" => true]);
+        if (count($userIds) < 1) {
+            return ["code" => SUCCESS, "data" => ["users" => []]];
+        }
+
+        // 重新添加指定角色下的用户数据
+        $data = [];
+        foreach ($userIds as $userId) {
+            array_push($data, ["user_id" => $userId, "role_id" => $rid]);
+        }
+        $this->insert($data);
+
+        //查出批量插入的数据,并返回给前端
+        $new_data = $this->select("id", "user_id", "role_id", "status")->where("role_id", $rid)->where("is_del", false)
+            ->orderBy("user_id", "asc")->get();
+        $uids = [];
+        foreach ($new_data as $nd) {
+            array_push($uids, $nd["user_id"]);
+        }
+        if (count($uids) > 0) {
+            $user = new User();
+            $userInfo = $user->ListUserByIds_KV($uids);
+        }
+
+        $result = ["users" => $new_data, "userInfo" => $userInfo];
+
+        return ["code" => SUCCESS, "data" => $result];
     }
 
     public function LoadRoleByUid($uid)

+ 2 - 0
config/errorcode.php

@@ -6,6 +6,7 @@ const NOTHING_UPDATE = 1;
 const REQUEST_SUCCESS = 0;
 const REQUEST_PARAM_ERROR = 101;
 const REQUEST_DATABASE_ERROR = 102;
+const PARAM_ARRAY_INT = 103;
 
 const EMPTY_USER_NAME = 110;
 const EMPTY_USER_ID = 111;
@@ -43,6 +44,7 @@ return [
 
     "101" => "params error",
     "102" => "database operation error",
+    "103" => "params should be int array",
 
     "111" => "empty user id",
     "112" => "invalid user id",

+ 3 - 1
routes/web.php

@@ -33,7 +33,9 @@ Route::get("listRole", "RoleController@ListRole");
 Route::get("loadRoleUsers", "RoleController@LoadRoleUsers");
 
 // user action bar
-Route::get("admin/AssignActionBars", "PermissionController@assignActionBars");
+Route::get("admin/assignActionBars", "PermissionController@AssignActionBars");
+Route::get("admin/assignUserRole", "PermissionController@AssignUserRole");
+Route::get("admin/assignRoleUser", "PermissionController@AssignRoleUser");
 
 Route::get("addUserActionBar", "UserActionBarController@AddUserActionBar");
 Route::get("removeUserActionBar", "UserActionBarController@RemoveUserActionBar");