Exemple #1
0
        public async Task <string> AddRole(RoleViewModel model)
        {
            using (var trans = await _systemIdentityDbContext.Database.BeginTransactionAsync())
            {
                try
                {
                    var role      = _mapper.Map <SystemRole>(model);
                    var isSuccess = await _roleRepository.AddRole(role);

                    if (!isSuccess)
                    {
                        return("无法创建角色,请检查角色名是否相同!");
                    }

                    // 找到所有父和子节点
                    var menuIdArray = model.Menus.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    var menuTree    = from tree in _menuTreeRepository.Get(false)
                                      where menuIdArray.Contains(tree.Ancestor.ToString()) ||
                                      menuIdArray.Contains(tree.Descendant.ToString())
                                      select tree;

                    var menuIds = menuTree.Select(tree => tree.Descendant).Concat(
                        menuTree.Select(tree => tree.Ancestor)).Distinct();

                    role = await _roleRepository.GetRole(model.Name);

                    isSuccess = await _roleRepository.AddOrUpdateRoleClaim(role,
                                                                           CustomClaimTypes.RoleMenus, string.Join(',', menuIds.Distinct()));

                    if (!isSuccess)
                    {
                        await trans.RollbackAsync();

                        return("无法创建角色,菜单权限添加失败!");
                    }

                    // 存储原始选中节点前端用
                    isSuccess = await _roleRepository.AddOrUpdateRoleClaim(role,
                                                                           CustomClaimTypes.RoleMenusFront, string.Join(',', menuIdArray.Distinct()));

                    if (!isSuccess)
                    {
                        await trans.RollbackAsync();

                        return("无法更新角色,菜单权限添加失败!");
                    }
                    await trans.CommitAsync();
                }
                catch (Exception e)
                {
                    await trans.RollbackAsync();

                    throw e;
                }
            }
            return(string.Empty);
        }