Ejemplo n.º 1
0
        public async Task AssignRolesAsync(string id, AssignRoleToUserDto model, IEnumerable <string> allowedClientIds = null)
        {
            var user = await _userRepo.GetAsync(id, isReadonly : false);

            if (user == null)
            {
                throw new IamException(HttpStatusCode.BadRequest, "用户不存在");
            }
            var exsitedRoles = await _userMgr.GetRolesAsync(user);

            if (allowedClientIds != null)
            {
                var ownedRoles = await _roleRepo.GetAllByNamesAsync(exsitedRoles, allowedClientIds);

                exsitedRoles = exsitedRoles.Except(ownedRoles.Select(itm => itm.Name)).ToList();
            }

            IdentityResult result = await _userMgr.RemoveFromRolesAsync(user, exsitedRoles);

            if (!result.Succeeded)
            {
                throw new IamException(HttpStatusCode.BadRequest, String.Join(";", result.Errors.Select(err => err.Description)));
            }

            if (model == null || model.RoleIds == null || !model.RoleIds.Any())
            {
                return;
            }

            var allowedRoles = await _roleRepo.GetAllByIdsAsync(model.RoleIds, allowedClientIds);

            result = await _userMgr.AddToRolesAsync(user, allowedRoles.Select(itm => itm.Name));

            if (!result.Succeeded)
            {
                throw new IamException(HttpStatusCode.BadRequest, String.Join(";", result.Errors.Select(err => err.Description)));
            }
        }