Ejemplo n.º 1
0
        public async Task <DeptResult> EditDeptsInRole(RoleViewModel model, string roleId)
        {
            var deptResult = new DeptResult {
                Succeeded = false
            };
            var role = await roleManager.FindByIdAsync(roleId);

            if (role == null)
            {
                deptResult.Error = "找不到角色,请确认";
                logger.LogWarning("修改角色部门失败{LogType}{CustomProperty}", "Operate", JsonConvert.SerializeObject(model.Depts) + $"错误原因:{deptResult.Error}");
                return(deptResult);
            }
            foreach (var item in model.Depts)
            {
                bool isInRole = await deptManager.IsInRoleAsync(item.Id, roleId);

                var users = userManager.Users.Where(user => user.Department == item.DeptName).ToList();
                if (isInRole && !item.InRole)
                {
                    await userManager.RemoveUsersFromRoleAsync(users, role.Name);

                    deptResult = await deptManager.RemoveFromRoleAsync(item.Id, roleId);
                }
                else if (!isInRole && item.InRole)
                {
                    await userManager.AddUsersToRoleAsync(users, role.Name);

                    deptResult = await deptManager.AddToRoleAsync(item.Id, roleId);
                }
                else
                {
                    continue;
                }
                if (!deptResult.Succeeded)
                {
                    logger.LogWarning("修改角色部门失败{LogType}{CustomProperty}", "Operate", JsonConvert.SerializeObject(model.Depts) + $"错误原因:{deptResult.Error}");
                    return(deptResult);
                }
            }
            logger.LogWarning("修改角色部门{LogType}{CustomProperty}", "Operate", JsonConvert.SerializeObject(model.Depts));
            return(deptResult);
        }