123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589 |
- <?php
- /**
- * Created by:PhpStorm
- * Author:chenzhiyuan
- * Date: 2022/4/19
- * Time: 1:41 下午
- */
- namespace App\Service\Admin;
- use App\Log;
- use App\Models\System\AdminManageRole;
- use App\Models\System\Permission;
- use App\Models\System\Role;
- use App\Models\System\RolePermission;
- use App\Models\System\Users;
- use App\Support\EmailQueue;
- use Illuminate\Support\Facades\DB;
- class RoleService
- {
- /**
- * 获取用户可以操作的权限集
- * @param $adminId
- * @param $sysGroupId
- * @param array $permissionIds
- * @return array|\Illuminate\Support\Collection
- */
- public static function getPermissionIdsOfUser($adminId, $sysGroupId, $permissionIds=[])
- {
- try {
- # 获取当前用户的角色信息
- $roleIds = AdminManageRole::select('role_id')->where('sys_user_id', $adminId)
- ->where('is_delete', 0)->distinct()->pluck('role_id');
- if(empty($roleIds))
- return [];
- # 判断当前用户是否有超级权限
- $isAdminAuth = Role::whereIn('id', $roleIds)->where('role_type', 10)->exists();
- if($isAdminAuth) { # 拥有超级权限,获取主账号所属的角色信息
- if(empty($sysGroupId)) {
- $sysGroupId = Users::query()->where('id', $adminId)->value('group_admin_id');
- }
- $roleIds = AdminManageRole::select('role_id')->where('sys_user_id', $sysGroupId)
- ->where('is_delete', 0)->distinct()->pluck('role_id');
- }
- $permissionIds = RolePermission::select('permission_id')->whereIn('role_id', $roleIds)
- ->where(function($query) use($permissionIds) {
- if(!empty($permissionIds)) $query->whereIn('permission_id', $permissionIds);
- })
- ->where('is_delete', 0)->distinct()->pluck('permission_id');
- } catch (\Exception $e) {
- Log::logError('获取用户可以操作的权限集异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- 'admin_id' => $adminId
- ], 'GetPermissionIdsOfUser');
- return [];
- }
- return $permissionIds;
- }
- /**
- * 判断用户所操作的权限集是否合法
- * @param $permissionIds mixed 用户拥有的权限集
- * @param $permissionInput array 用户当前操作的权限集
- * @return bool
- * */
- public static function checkPermission($permissionIds, $permissionInput)
- {
- if(empty($permissionIds)) return false;
- if(!is_array($permissionIds)) $permissionIds = $permissionIds->toArray();
- foreach ($permissionInput as $id) {
- if(!in_array($id, $permissionIds)) return false;
- }
- return true;
- }
- /**
- * 添加角色,并赋予角色管理的权限
- * @param $viewType
- * @param $adminId
- * @param $sysGroupId
- * @param $isSystemAdmin
- * @param $name
- * @param $desc
- * @param $roleType
- * @param $permissionIdArr
- * @return integer
- */
- public static function create_role($viewType,$adminId,$sysGroupId,$isSystemAdmin,$name,$desc,$roleType,$permissionIdArr = [])
- {
- try {
- if(!$isSystemAdmin && ($adminId != $sysGroupId)) {
- # 获取当前登录用户可操作的权限
- $permissionIds = RoleService::getPermissionIdsOfUser($adminId, $sysGroupId);
- # 校验当下操作的权限集是否合法
- $check = RoleService::checkPermission($permissionIds, $permissionIdArr);
- if(!$check) return 4506;
- }
- DB::begintransaction();
- # 新增角色
- $roleId = Role::query()->create([
- 'view_type' => $viewType,
- 'role_type' => $roleType,
- 'name' => $name,
- 'admin_id' => $adminId,
- 'sys_group_id' => $isSystemAdmin ? $adminId : $sysGroupId,
- 'desc' => $desc,
- ])->id;
- if(!$roleId) {
- Log::logError('Role表写入数据失败', [
- 'view_type' => $viewType,
- 'admin_id' => $adminId,
- 'sys_group_id' => $sysGroupId,
- 'name' => $name,
- 'desc' => $desc,
- 'permission_ids' => $permissionIdArr
- ], 'CreateRole');
- return 4502;
- }
- # 获取可分配权限的侧边栏信息
- $permissionIdViewType = Permission::query()->where("is_delete",0)
- ->whereIn("id",$permissionIdArr)
- ->pluck("view_type","id")
- ->toArray();
- # 角色权限绑定
- foreach ($permissionIdArr as $permissionId){
- RolePermission::query()->updateOrInsert(
- [
- 'role_id' => $roleId,
- 'permission_id' => $permissionId
- ],
- [
- 'is_delete' => 0,
- 'view_type' => $permissionIdViewType[$permissionId],
- ]
- );
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::logError('角色创建过程发生异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- 'param' => [
- 'view_type' => $viewType,
- 'admin_id' => $adminId,
- 'sys_group_id' => $sysGroupId,
- 'name' => $name,
- 'desc' => $desc,
- 'permission_ids' => $permissionIdArr
- ]
- ], 'CreateRole');
- return 4501;
- }
- return 0;
- }
- /**
- * 删除角色
- * @param $roleId
- * @param $adminId
- * @param $sysGroupId
- * @param $isSystemAdmin
- * @return bool
- */
- public static function del_role($roleId,$adminId,$sysGroupId,$isSystemAdmin)
- {
- try {
- $roleInfo = Role::query()->where("id",$roleId)
- ->where(function($query) use($isSystemAdmin, $sysGroupId, $adminId) {
- if($isSystemAdmin) {
- $query->where('sys_group_id', $adminId);
- } else {
- $query->where('sys_group_id', $sysGroupId);
- }
- })
- ->where("system_role",0)
- ->where("is_delete",0)
- ->first();
- if(empty($roleInfo)) return 4505;
- # 判断是否有成员属于该角色
- $isUsed = AdminManageRole::where('role_id', $roleId)->where('is_delete', 0)->count();
- if($isUsed) return 4509;
- DB::begintransaction();
- //删除角色
- $result = Role::query()->where("id",$roleId)->update(['is_delete'=>1]);
- if(!$result) {
- DB::rollBack();
- return 4507;
- }
- $permissionCount = RolePermission::where("role_id",$roleId)->where('is_delete', 0)->count();
- if($permissionCount) {
- //删除角色以及权限控制
- $result = RolePermission::query()->where("role_id",$roleId)->update(['is_delete'=>1]);
- if(!$result) {
- DB::rollBack();
- return 4508;
- }
- }
- DB::commit();
- } catch (\Exception $e) {
- DB::rollBack();
- Log::logError('角色删除过程发生异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- 'param' => [
- 'role_id' => $roleId,
- 'admin_id' => $adminId,
- 'sys_group_id' => $sysGroupId,
- ]
- ], 'DelRole');
- return 4501;
- }
- return 0;
- }
- /***
- * 编辑角色
- * @param $viewType
- * @param $adminId
- * @param $sysGroupId
- * @param $isSystemAdmin
- * @param $roleId
- * @param $name
- * @param $desc
- * @param $roleType
- * @param array $permissionIdArr
- * @return bool
- */
- public static function edit_role($viewType,$adminId,$sysGroupId,$isSystemAdmin,$roleId,$name,$desc,$roleType,$permissionIdArr = [])
- {
- try {
- if(!$isSystemAdmin && ($adminId != $sysGroupId)) {
- # 获取当前登录用户可操作的权限
- $permissionIds = RoleService::getPermissionIdsOfUser($adminId, $sysGroupId);
- # 校验当下操作的权限集是否合法
- $check = RoleService::checkPermission($permissionIds, $permissionIdArr);
- if(!$check) return 4506;
- }
- /**检查角色存在***/
- $roleInfo = Role::query()->where("id",$roleId)
- ->where("view_type",$viewType)
- ->where("is_delete",0)->first();
- if(empty($roleInfo)) {
- return 4505;
- }
- // Log::logInfo('获取角色信息完成', [$roleId], 'EditRoleDebug');
- DB::begintransaction();
- /**编辑角色**/
- Role::query()->where("id",$roleId)
- ->where("is_delete",0)
- ->update([
- 'role_type' => $roleType,
- 'admin_id' => $adminId,
- 'sys_group_id' => $isSystemAdmin ? $adminId : $sysGroupId,
- 'name' => $name,
- 'desc' => $desc,
- ]);
- // Log::logInfo('编辑角色信息完成', [$roleId], 'EditRoleDebug');
- $permissionIdViewType = Permission::query()->where("is_delete",0)
- ->whereIn("id",$permissionIdArr)
- ->pluck("view_type","id")
- ->toArray();
- // Log::logInfo('获取编辑后角色对应权限信息完成', [$roleId], 'EditRoleDebug');
- // 获取本次被删除的权限
- $nowRolePermissionList = RolePermission::query()->select('permission_id')
- ->where('role_id', $roleId)->where('is_delete', 0)
- ->pluck('permission_id')->toArray();
- $disablePermissionList = array_diff($nowRolePermissionList, $permissionIdArr);
- $disablePermissionList = array_values($disablePermissionList);
- // Log::logInfo('获取所有权限列表并找到已删除的权限', [$roleId], 'EditRoleDebug');
- /**角色权限相绑定**/
- foreach ($permissionIdArr as $permissionId){
- if(!isset($permissionIdViewType[$permissionId])){ //权限被删除
- continue;
- }
- RolePermission::query()->updateOrInsert(
- [
- 'role_id' => $roleId,
- 'permission_id' => $permissionId
- ],
- [
- 'is_delete' => 0,
- 'view_type' => $permissionIdViewType[$permissionId],
- ]
- );
- }
- // Log::logInfo('新增权限处理完成', [$roleId], 'EditRoleDebug');
- if(!empty($disablePermissionList)) {
- // 删除当前角色的绑定关系
- // RolePermission::query()->where('role_id', $roleId)
- // ->whereIn('permission_id', $disablePermissionList)->update(['is_delete' => 1]);
- // Log::logInfo('当前角色已删除权限处理完成,开始循环处理当前角色创建角色账号', [$roleId], 'EditRoleDebug');
- $alreadyDealRoleIdList = [];
- self::dealRole($roleId, $disablePermissionList, $alreadyDealRoleIdList);
- $res = RolePermission::query()->whereIn('role_id', $alreadyDealRoleIdList)
- ->whereIn('permission_id', $disablePermissionList)->update(['is_delete' => 1]);
- if(!$res) {
- DB::rollBack();
- return 4504;
- }
- }
- DB::commit();
- } catch(\Exception $e) {
- DB::rollBack();
- Log::logError('角色编辑过程发生异常', [
- 'line' => $e->getLine(),
- 'msg' => $e->getMessage(),
- 'param' => [
- 'view_type' => $viewType,
- 'admin_id' => $adminId,
- 'sys_group_id' => $sysGroupId,
- 'name' => $name,
- 'desc' => $desc,
- 'permission_ids' => $permissionIdArr
- ]
- ], 'EditRole');
- return 4504;
- }
- return 0;
- }
- /*
- * 1.将起始操作的角色权限绑定关系解除
- * 2.查询起始操作角色关联的用户列表
- * 3.依次查询关联用户是否仍拥有要解除关系的权限
- * 4.若用户仍然拥有要删除的权限,则由该用户创建的角色权限无须处理
- * 5.若用户完全失去要删除的权限,那么由该用户创建的角色也将不能用户该权限
- * 6.解除用户创建的角色与要删除权限之间的关联关系,并依次判断创建的角色是否需要进行下一步处理(回到第一步)
- * */
- public static function dealRole($roleId, $disablePermissionList, &$alreadyDealRoleIdList = [])
- {
- if(in_array($roleId, $alreadyDealRoleIdList)) {
- return true;
- } else {
- $alreadyDealRoleIdList[] = $roleId;
- }
- // 查询当前操作角色关联的用户
- $userIdList = AdminManageRole::query()->where('role_id', $roleId)->where('is_delete', 0)
- ->pluck('sys_user_id')->toArray();
- // Log::logInfo('查询当前操作角色关联的用户', [
- // 'role_id' => $roleId,
- // 'user_id_list' => $userIdList,
- // 'already' => $alreadyDealRoleIdList
- // ], 'EditRoleDebug');
- if(empty($userIdList)) return true;
- foreach($userIdList as $userId) {
- // 查询用户是否还有该权限
- $enablePermissionIdList = self::getPermissionIdsOfUser($userId, null, []);
- // Log::logInfo('查询用户是否还有该权限', ['role_id' => $roleId, 'user_id' => $userId], 'EditRoleDebug');
- $diffPermissionIdList = array_intersect($disablePermissionList, $enablePermissionIdList->toArray());
- // 当前用户没有该权限,则继续查找用户创建的角色列表,并将创建的角色依次解除绑定后继续判断创建角色关联的用户权限
- if(!empty($diffPermissionIdList)) {
- // 判断要解除绑定的权限集与求差集之后的权限集是否完全一致
- if(array_diff($diffPermissionIdList, $disablePermissionList) ||
- array_diff($disablePermissionList, $diffPermissionIdList)) {
- Log::logError('角色编辑过程发生异常-权限集不一致', [
- 'role_id' => $roleId,
- 'operate_user_id' => $userId,
- 'disable_permission' => $disablePermissionList,
- 'diff_permission' => $diffPermissionIdList,
- 'enable_permission' => $enablePermissionIdList->toArray()
- ], 'EditRoleDebug');
- EmailQueue::rPush('角色编辑过程发生异常-权限集不一致', json_encode([
- 'role_id' => $roleId,
- 'operate_user_id' => $userId,
- 'disable_permission' => $disablePermissionList,
- 'diff_permission' => $diffPermissionIdList,
- 'enable_permission' => $enablePermissionIdList->toArray()
- ], 1), ['song.shen@kuxuan-inc.com'], '猎羽');
- // return false;
- }
- // 查找用户创建的角色列表
- $roleIdList = Role::query()->where('admin_id', $userId)->where('is_delete', 0)
- ->pluck('id')->toArray();
- // Log::logInfo('查找用户创建的角色列表', [
- // 'user_id' => $userId,
- // 'user_role_id_list' => $roleIdList,
- // 'already' => $alreadyDealRoleIdList
- // ], 'EditRoleDebug');
- foreach($roleIdList as $role) {
- if(!in_array($role, $alreadyDealRoleIdList)) {
- // RolePermission::query()->where('role_id', $role)
- // ->whereIn('permission_id', $disablePermissionList)->update(['is_delete' => 1]);
- // $alreadyDealRoleIdList[] = $role;
- // Log::logInfo('当前角色已删除权限处理完成', [
- // 'role_id' => $role,
- // 'already' => $alreadyDealRoleIdList
- // ], 'EditRoleDebug');
- self::dealRole($role, $disablePermissionList, $alreadyDealRoleIdList);
- }
- }
- }
- }
- return true;
- }
- /**
- * 权限类型
- * @param $adminId
- * @param $sysGroupId
- * @param $isSystemAdmin
- * @param $errno
- * @return array
- */
- public static function role_type($adminId, $sysGroupId, $isSystemAdmin, &$errno)
- {
- $roleTypeIds = [10, 20, 30];
- $roleTypeList = [10 => '超级权限', 20 => '管理权限', 30 => '普通权限'];
- $userRoleType = 0;
- if(!$isSystemAdmin && ($adminId != $sysGroupId)) {
- # 获取当前登录用户的角色权限
- $userRoleIds = AdminManageRole::select(['role_id'])->where('sys_user_id', $adminId)->where('is_delete', 0)->pluck('role_id');
- if(empty($userRoleIds)) {
- $errno = 4506;
- return [];
- }
- $userRoleType = Role::whereIn('id', $userRoleIds)->where('is_delete', 0)->min('role_type');
- if(!$userRoleType) {
- $errno = 4506;
- return [];
- }
- }
- $roleTypeIds = array_filter($roleTypeIds, function($v) use($userRoleType) {
- return $v >= $userRoleType;
- });
- $data = [];
- foreach ($roleTypeIds as $roleType) {
- if(!isset($roleTypeList[$roleType])) continue;
- $data[$roleType] = $roleTypeList[$roleType];
- }
- return $data;
- }
- /**
- * 权限列表
- * @param $viewType
- * @param $adminId
- * @param $sysGroupId
- * @param $isSystemAdmin
- * @param $page
- * @param $page_limit
- * @param $errno
- * @return array
- */
- public static function role_list($viewType,$adminId,$sysGroupId,$isSystemAdmin,$page,$page_limit, &$errno)
- {
- $userRoleType = 0;
- if(!$isSystemAdmin && ($adminId != $sysGroupId)) {
- # 获取当前登录用户的角色权限
- $userRoleIds = AdminManageRole::select(['role_id'])->where('sys_user_id', $adminId)->where('is_delete', 0)->pluck('role_id');
- if(empty($userRoleIds)) return [];
- $userRoleType = Role::whereIn('id', $userRoleIds)->where('is_delete', 0)->min('role_type');
- if(!$userRoleType) return [];
- }
- $query = Role::query()
- ->where(function($query) use($isSystemAdmin, $sysGroupId, $adminId) {
- if($isSystemAdmin) {
- $query->where('sys_group_id', $adminId);
- } else {
- $query->where('sys_group_id', $sysGroupId);
- }
- })
- ->where("is_delete",0)->where('role_type', '>=', $userRoleType);
- $total = $query->count();
- $list = $query->select("id","name","desc","system_role","created_at", "role_type")
- ->offset(($page-1)*$page_limit)
- ->limit($page_limit)
- ->get()->toArray();
- foreach ($list as $k=>$item){
- $canEdit = 0;
- if($userRoleType == 0) {
- $canEdit = 1;
- }
- $list[$k]['can_edit'] = $canEdit;
- $list[$k]['is_system'] = $item['system_role'] == 0 ? 0 : 1 ; //是否是系统用户
- unset($list[$k]['system_role']);
- }
- return [$total,$list];
- }
- /**
- * 权限详情
- * @param $roleId
- * @param $adminId
- * @param $sysGroupId
- * @param $isSystemAdmin
- * @param $errno
- * @return array
- */
- public static function role_info($roleId,$adminId,$sysGroupId,$isSystemAdmin,&$errno)
- {
- $role_info = Role::query()->where("id",$roleId)
- ->where("is_delete",0)
- ->where(function($query) use($isSystemAdmin, $sysGroupId, $adminId) {
- if($isSystemAdmin) {
- $query->where('sys_group_id', $adminId);
- } else {
- $query->where('sys_group_id', $sysGroupId);
- }
- })
- ->select("id","name","desc","system_role", "role_type")
- ->first();
- if (empty($role_info)) {
- $errno = 4505;
- return [];
- }
- /**权限角色拥有的权限集**/
- $permissionIdArr = RolePermission::query()->where("role_id",$roleId)
- ->where("is_delete",0)
- ->pluck("permission_id")->toArray();
- /**补充权限选中**/
- $role_info->is_system = $role_info->system_role == 0 ? 0 : 1 ; //是否是系统角色
- $role_info->checked_permission = $permissionIdArr;
- unset($role_info->system_role); //删除系统角色标识
- return $role_info->toArray();
- }
- }
|