Ejemplo n.º 1
0
        public static void Validate(this ClientInputModel inputModel)
        {
            var validationException = new ValidationException();

            validationException.AddValidation(() => inputModel.AllowedGrantTypes.IsNullOrEmpty(), nameof(inputModel.AllowedGrantTypes), ALLOWED_GRANT_TYPES_VALIDATION_MESSAGE);
            validationException.AddValidation(() => string.IsNullOrWhiteSpace(inputModel.ClientName), nameof(inputModel.ClientName), CLIENT_NAME_VALIDATION_MESSAGE);
            validationException.AddValidation(() => string.IsNullOrWhiteSpace(inputModel.ClientId), nameof(inputModel.ClientId), CLIENT_ID_VALIDATION_MESSAGE);

            validationException.ThrowIfHasError();
        }
Ejemplo n.º 2
0
        private async Task LoadClient()
        {
            var url   = $"clients/{Id}";
            var model = await ApiService.GetAsync <ClientModel>(url);

            client = new ClientInputModel
            {
                Name = model.Name
            };
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Create([FromBody] ClientInputModel model)
        {
            var result = await this.clients.Create(model, this.currentUser.Id);

            if (!result.Succeeded)
            {
                return(this.BadRequest(result.Errors));
            }

            return(this.Ok(result.Data));
        }
Ejemplo n.º 4
0
        public ActionResult <ClientViewModel> Post(ClientInputModel clientInput)
        {
            Client client   = MapClient(clientInput);
            var    response = clientService.Save(client);

            if (response.Error)
            {
                return(BadRequest(response.Menssage));
            }

            return(Ok(new ClientViewModel(response.Object)));
        }
Ejemplo n.º 5
0
        public ActionResult <ClientViewModel> Modify(ClientInputModel clientInput)
        {
            Client client   = MapClient(clientInput);
            var    response = _clientService.Modify(client);

            if (response.Error)
            {
                return(BadRequest(response.Message));
            }

            return(Ok(response.Object));
        }
Ejemplo n.º 6
0
        public async Task <ActionResult <ResponseModel <ClientModel> > > UpdateAsync([FromBody] ClientInputModel input, int id)
        {
            var client = await _clientManager.UpdateAsync(id, input.Name, input.Address, CurrentUser.Id);

            if (client != null)
            {
                return(Ok(new ResponseModel <ClientModel>(new ClientModel(client))));
            }
            else
            {
                return(BadRequest(new ErrorModel("Unable to update Client.")));
            }
        }
Ejemplo n.º 7
0
        private Client MapClient(ClientInputModel clientInput)
        {
            Client client = new Client();

            client.IdClient     = clientInput.IdClient;
            client.Name         = clientInput.Name;
            client.LastName     = clientInput.LastName;
            client.Phone        = clientInput.Phone;
            client.Address      = clientInput.Address;
            client.Neighborhood = clientInput.Neighborhood;
            client.City         = clientInput.City;
            return(client);
        }
Ejemplo n.º 8
0
        private Task <IActionResult> HandleWithListChange(ClientInputModel inputModel, string button, string listValue)
        {
            if (button.Contains(GRANT))
            {
                HandleWithGrantListChange(inputModel, button, listValue);
            }
            else if (button.Contains(SCOPE))
            {
                HandleWithScopeListChange(inputModel, button, listValue);
            }

            ModelState.Clear();
            return(ReturnEditView(inputModel));
        }
Ejemplo n.º 9
0
        public ActionResult <ClientViewModel> Modify(ClientInputModel clientInputModel)
        {
            Client client   = MapearClient(clientInputModel);
            var    response = _ClientService.Modify(client);

            if (response.Error == false)
            {
                return(Ok(response.Object));
            }
            else
            {
                return(BadRequest(response.Menssage));
            }
        }
Ejemplo n.º 10
0
        private Client MapearClient(ClientInputModel clientInputModel)
        {
            var client = new Client
            {
                Address      = clientInputModel.Address,
                City         = clientInputModel.City,
                Department   = clientInputModel.Department,
                Neighborhood = clientInputModel.Neighborhood,
                Person       = MapPerson(clientInputModel.Person),
            };


            return(client);
        }
Ejemplo n.º 11
0
        private void HandleWithScopeListChange(ClientInputModel inputModel, string button, string listValue)
        {
            if (inputModel.AllowedScopes == null)
            {
                inputModel.AllowedScopes = new List <string>();
            }

            if (button.Contains(ADD))
            {
                inputModel.AllowedScopes.Add(listValue);
            }
            else if (button.Contains(REMOVE))
            {
                inputModel.AllowedScopes.Remove(listValue);
            }
        }
Ejemplo n.º 12
0
        public void WhenCallValidation_WithoutEmptyInput_ThenShouldThrowValidationExceptionWithAllMessages()
        {
            // Arrange
            var clientInputModel = new ClientInputModel()
            {
                ClientId          = "ClientId",
                ClientName        = "Name",
                AllowedGrantTypes = new System.Collections.Generic.List <string>()
                {
                    "ABC"
                },
            };

            // Act
            ClientValidations.Validate(clientInputModel);
        }
Ejemplo n.º 13
0
        private Client MapClient(ClientInputModel clientInput)
        {
            Client client = new Client();

            client.ClientId     = clientInput.ClientId;
            client.Name         = clientInput.Name;
            client.LastName     = clientInput.LastName;
            client.Phone        = clientInput.Phone;
            client.Address      = clientInput.Address;
            client.Neighborhood = clientInput.Neighborhood;
            client.City         = clientInput.City;
            client.Department   = clientInput.Department;
            client.User         = MapUser(clientInput.User);

            return(client);
        }
        public async Task <ActionResult <ClientModel> > Create(ClientInputModel model)
        {
            _logger.LogDebug($"Creating a new client with name {model.Name}");

            var client = new Client();

            model.MapTo(client);

            await _dbContext.Clients.AddAsync(client);

            await _dbContext.SaveChangesAsync();

            var resultModel = ClientModel.FromClient(client);

            return(CreatedAtAction(nameof(GetById), "clients", new { id = client.Id }, resultModel));
        }
Ejemplo n.º 15
0
        public Task <IActionResult> Edit(ClientInputModel inputModel, string button, string listValue)
        {
            if (button == ControllerConstants.CANCEL)
            {
                return(Task.FromResult((IActionResult)RedirectToAction(nameof(Index))));
            }

            if (button != ControllerConstants.SAVE)
            {
                return(HandleWithListChange(inputModel, button, listValue));
            }
            else
            {
                return(HandleWithSave(inputModel));
            }
        }
Ejemplo n.º 16
0
        public ActionResult <ClientViewModel> Post(ClientInputModel clientInput)
        {
            Client client   = MapClient(clientInput);
            var    response = clientService.Save(client);

            if (response.Error)
            {
                ModelState.AddModelError("Guardar Cliente", response.Message);
                var problemDetails = new ValidationProblemDetails(ModelState)
                {
                    Status = StatusCodes.Status400BadRequest,
                };
                return(BadRequest(problemDetails));
            }

            return(Ok(response.Client));
        }
Ejemplo n.º 17
0
        public IActionResult Edit(int id, ClientInputModel input)
        {
            if (!ModelState.IsValid)
            {
                return(View(input));
            }

            var client = _clientService.GetClient(id);

            _mapper.Map(input, client);
            client.SetClientType(input.ClientType);
            _clientService.SaveChanges();

            _logger.LogInformation("{user} edited client {client}", User.Identity.Name, id);

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 18
0
        public void GivenIHasAClientId_WhenCallUpsertToInsertNewClient_ThenShouldThrowAlreadyExistsException()
        {
            // Given
            var clientInput = new ClientInputModel()
            {
                ClientId          = "ClientId",
                ClientName        = "Name",
                AllowedGrantTypes = new List <string>()
                {
                    "ABC"
                }
            };

            ClientDataAccessMock.Setup(dataAccess => dataAccess.InsertAsync(It.IsAny <ClientData>())).Throws(MongoWriteException);

            // When
            Assert.Throws(typeof(AlreadyExistsException), () => ClientService.UpsertClientAsync(clientInput).GetAwaiter().GetResult());
        }
        public async Task <IActionResult> Update(ClientInputModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await _clientService.UpdateAsync(UserId, model.ClientId, model.ClientName, model.RedirectUrl, model.PostLogoutRedirectUrl, model.RequireConsent, model.AllowedScope);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, result.ErrorMsg);
                }
            }

            return(View(model));
        }
        public async Task <ActionResult <ClientModel> > Update(long id, ClientInputModel model)
        {
            _logger.LogDebug($"Updating client with id {id}");

            var client = await _dbContext.Clients.FindAsync(id);

            if (client == null)
            {
                return(NotFound());
            }

            model.MapTo(client);

            _dbContext.Clients.Update(client);
            await _dbContext.SaveChangesAsync();

            return(ClientModel.FromClient(client));
        }
Ejemplo n.º 21
0
        public async Task CreateAsync(ClientInputModel input)
        {
            var clientExists = await this.db.Clients.AnyAsync(c => c.UserId == input.UserId);

            if (clientExists)
            {
                throw new InvalidOperationException("Client with this UserId is already registered!");
            }

            await this.db.AddAsync(new Client
            {
                UserId                 = input.UserId,
                ClientName             = input.ClientName,
                NationalIdentityNumber = input.NationalIdentityNumber
            });

            await this.db.SaveChangesAsync();
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> Post([FromBody] ClientInputModel request)
        {
            var client = new Client(
                name: request.Name,
                description: request.Description,
                phone: request.Phone,
                email: request.Email,
                totalPayment: request.TotalPayment
                );
            await _apiContext.Clients.AddAsync(client);

            var success = await _apiContext.SaveChangesAsync() > 0;

            if (success)
            {
                return(CreatedAtAction(nameof(GetById), client, new { id = client.Id }));
            }
            throw new Exception("Ocorreu um problema ao salvar os dados");
        }
Ejemplo n.º 23
0
 public async Task UpsertClientAsync(ClientInputModel inputModel)
 {
     try
     {
         ClientValidations.Validate(inputModel);
         var clientData = inputModel.ToData(Cryptography);
         if (string.IsNullOrWhiteSpace(clientData.Id))
         {
             await ClientDataAccess.InsertAsync(clientData);
         }
         else
         {
             await ClientDataAccess.ReplaceAsync(clientData, (data) => data.Id == clientData.Id);
         }
     }
     catch (MongoWriteException ex)
     {
         ex.ThrowIfDuplicateKey(nameof(inputModel.ClientId), $"O id do client '{inputModel.ClientId}' já existe");
         throw ex;
     }
 }
Ejemplo n.º 24
0
        public void GivenItHasClient_WhenCallUpsertToUpdateClient_ThenShouldCallReplace()
        {
            // Given
            var input = new ClientInputModel()
            {
                Id = "1", ClientId = "ClientId", ClientName = "Name", AllowedGrantTypes = new List <string>()
                {
                    "ABC"
                }
            };

            ClientDataAccessMock
            .Setup(dataAccess => dataAccess.ReplaceAsync(It.IsAny <ClientData>(), It.IsAny <Expression <Func <ClientData, bool> > >()))
            .ReturnsAsync(true);

            // When
            ClientService.UpsertClientAsync(input).GetAwaiter().GetResult();

            // Then
            ClientDataAccessMock.Verify(dataAccess => dataAccess.InsertAsync(It.IsAny <ClientData>()), Times.Never);
            ClientDataAccessMock.Verify(dataAccess => dataAccess.ReplaceAsync(It.IsAny <ClientData>(), It.IsAny <Expression <Func <ClientData, bool> > >()), Times.Once);
        }
Ejemplo n.º 25
0
        public async Task <ActionResult <ClientViewModel> > PostClient(ClientInputModel clientInput)
        {
            Client client = _mapper.Map <Client>(clientInput);

            IdentityResult result =
                await _applicationUserRepository.CreateAsync(client.User, clientInput.User.Password);

            if (!result.Succeeded)
            {
                return(this.IdentityResultErrors(result));
            }

            IdentityResult roleResult = await _applicationUserRepository.AddToRoleAsync(client.User, "Client");

            if (!roleResult.Succeeded)
            {
                return(this.IdentityResultErrors(roleResult));
            }

            client.PublishEvent(new SavedPerson(client));
            _clientsRepository.Insert(client);

            try
            {
                await _unitWork.SaveAsync();
            }
            catch (DbUpdateException)
            {
                if (ClientExists(clientInput.Id))
                {
                    return(Conflict($"El cliente con identificación {clientInput.Id} ya se encuentra registrado."));
                }

                throw;
            }

            return(_mapper.Map <ClientViewModel>(client));
        }
Ejemplo n.º 26
0
        private async Task SetScopeAndGrantToViewBag(ClientInputModel inputModel)
        {
            var loadedApiScopes = await this.ApiScopeService.GetAllApiScopesAsync();

            var loadedIdentity = await this.IdentityResourceService.GetAllIdentityResourcesAsync();

            var scopes        = loadedApiScopes.Select(apiScope => apiScope.Name).Concat(loadedIdentity.Select(identity => identity.Name)).Distinct();
            var allGrantTypes = GrantTypes.ClientCredentials
                                .Concat(GrantTypes.Code)
                                .Concat(GrantTypes.CodeAndClientCredentials)
                                .Concat(GrantTypes.DeviceFlow)
                                .Concat(GrantTypes.Hybrid)
                                .Concat(GrantTypes.HybridAndClientCredentials)
                                .Concat(GrantTypes.HybridAndClientCredentials)
                                .Concat(GrantTypes.Implicit)
                                .Concat(GrantTypes.ImplicitAndClientCredentials)
                                .Concat(GrantTypes.ResourceOwnerPassword)
                                .Concat(GrantTypes.ResourceOwnerPasswordAndClientCredentials)
                                .Distinct();

            ViewBag.Scopes     = scopes.Except(inputModel.AllowedScopes ?? Enumerable.Empty <string>());
            ViewBag.GrantTypes = allGrantTypes.Except(inputModel.AllowedGrantTypes ?? Enumerable.Empty <string>());
        }
        private bool CheckClientInputModel(ClientInputModel inputModel)
        {
            var properties = inputModel.GetType().GetProperties().Select(property => property.GetValue(inputModel));

            return(properties.All(p => (p is IEnumerable <object> enumerable && enumerable.Count() > 0) || p != null));
        }
Ejemplo n.º 28
0
        public async Task <ActionResult <ResponseModel> > Edit(ClientInputModel inputModel)
        {
            ResponseModel responseModel = new ResponseModel();

            try
            {
                // TODO: 效验
                #region 效验

                if (inputModel == null || inputModel.Id == 0)
                {
                    responseModel.code    = -1;
                    responseModel.message = "更新失败: 不存在此客户端";
                    return(await Task.FromResult(responseModel));
                }

                // 授权类型只能来自选项
                // eg: 若选项是两项: CodeAndClientCredentials => authorization_code,client_credentials
                string selectedGrantTypes = inputModel.AllowedGrantTypes;
                if (!AllGrantTypes.Contains(selectedGrantTypes))
                {
                    responseModel.code    = -1;
                    responseModel.message = "编辑失败: 不存在此授权类型";
                    return(await Task.FromResult(responseModel));
                }
                #endregion

                // 覆盖更新: 先从数据库查出原有数据
                var dbModel = await _configurationDbContext.Clients
                              .Include(d => d.AllowedGrantTypes)
                              .Include(d => d.AllowedScopes)
                              .Include(d => d.AllowedCorsOrigins)
                              .Include(d => d.RedirectUris)
                              .Include(d => d.PostLogoutRedirectUris)
                              .FirstOrDefaultAsync(m => m.Id == inputModel.Id);

                if (dbModel == null)
                {
                    responseModel.code    = -1;
                    responseModel.message = "更新失败: 不存在此客户端";
                    return(await Task.FromResult(responseModel));
                }
                // 注意: IdentityServer4.Models 没有 Id 属性,数据库操作时只能用于创建,不能用于更新
                // 秘钥不为空, 覆盖旧秘钥
                #region 覆盖秘钥
                if (!string.IsNullOrEmpty(inputModel.ClientSecret?.Trim()))
                {
                    // 注意: 约定: 一个客户端只能有一个秘钥
                    dbModel.ClientSecrets = new List <ClientSecret>();

                    // TODO: bug: 修改秘钥, 每次都是新增加秘钥, 不会删除已有秘钥
                    // 下方这样,也无法解决,每次修改还是会增加秘钥,而不会删除原来的
                    //dbModel.ClientSecrets.Clear();
                    //_configurationDbContext.Clients.Update(dbModel);
                    //await _configurationDbContext.SaveChangesAsync();

                    dbModel.ClientSecrets.Add(new ClientSecret()
                    {
                        ClientId = dbModel.Id,
                        Created  = DateTime.Now,
                        Type     = "SharedSecret",
                        Value    = new Secret(inputModel.ClientSecret.Sha256()).Value
                    });
                }
                #endregion

                // InputModel => dbModel
                #region 普通属性赋值
                dbModel.ClientId       = inputModel.ClientId;
                dbModel.ClientName     = inputModel.DisplayName;
                dbModel.Description    = inputModel.Description;
                dbModel.RequireConsent = inputModel.RequireConsent;
                dbModel.AllowAccessTokensViaBrowser      = inputModel.AllowAccessTokensViaBrowser;
                dbModel.AlwaysIncludeUserClaimsInIdToken = inputModel.AlwaysIncludeUserClaimsInIdToken;
                dbModel.AllowOfflineAccess = inputModel.AllowOfflineAccess;
                dbModel.Updated            = DateTime.Now;
                #endregion

                // 关联属性赋值
                #region 关联属性赋值
                dbModel.AllowedGrantTypes = new List <ClientGrantType>();
                if (!string.IsNullOrEmpty(inputModel.AllowedGrantTypes))
                {
                    inputModel.AllowedGrantTypes.Split(",").Where(m => m != "" && m != null).ToList().ForEach(q =>
                    {
                        dbModel.AllowedGrantTypes.Add(new IdentityServer4.EntityFramework.Entities.ClientGrantType()
                        {
                            ClientId  = dbModel.Id,
                            GrantType = q
                        });
                    });
                }

                dbModel.AllowedScopes = new List <ClientScope>();
                if (!string.IsNullOrEmpty(inputModel.AllowedScopes))
                {
                    inputModel.AllowedScopes.Split(",").Where(m => m != "" && m != null).ToList().ForEach(q =>
                    {
                        dbModel.AllowedScopes.Add(new IdentityServer4.EntityFramework.Entities.ClientScope()
                        {
                            ClientId = dbModel.Id,
                            Scope    = q
                        });
                    });
                }

                dbModel.AllowedCorsOrigins = new List <ClientCorsOrigin>();
                if (!string.IsNullOrEmpty(inputModel.AllowedCorsOrigins))
                {
                    inputModel.AllowedCorsOrigins.Split(",").Where(m => m != "" && m != null).ToList().ForEach(q =>
                    {
                        dbModel.AllowedCorsOrigins.Add(new IdentityServer4.EntityFramework.Entities.ClientCorsOrigin()
                        {
                            ClientId = dbModel.Id,
                            Origin   = q
                        });
                    });
                }

                dbModel.PostLogoutRedirectUris = new List <ClientPostLogoutRedirectUri>();
                if (!string.IsNullOrEmpty(inputModel.PostLogoutRedirectUris))
                {
                    inputModel.PostLogoutRedirectUris.Split(",").Where(m => m != "" && m != null).ToList().ForEach(q =>
                    {
                        dbModel.PostLogoutRedirectUris.Add(new IdentityServer4.EntityFramework.Entities.ClientPostLogoutRedirectUri()
                        {
                            ClientId = dbModel.Id,
                            PostLogoutRedirectUri = q
                        });
                    });
                }

                dbModel.RedirectUris = new List <ClientRedirectUri>();
                if (!string.IsNullOrEmpty(inputModel.RedirectUris))
                {
                    inputModel.RedirectUris.Split(",").Where(m => m != "" && m != null).ToList().ForEach(q =>
                    {
                        dbModel.RedirectUris.Add(new IdentityServer4.EntityFramework.Entities.ClientRedirectUri()
                        {
                            ClientId    = dbModel.Id,
                            RedirectUri = q
                        });
                    });
                }
                #endregion

                // 保存到数据库
                _configurationDbContext.Clients.Update(dbModel);
                await _configurationDbContext.SaveChangesAsync();

                responseModel.code    = 1;
                responseModel.message = "更新成功 ";
            }
            catch (Exception ex)
            {
                responseModel.code    = -1;
                responseModel.message = "更新失败: " + ex.Message;
            }

            return(await Task.FromResult(responseModel));
        }
Ejemplo n.º 29
0
        private async Task <IActionResult> ReturnEditView(ClientInputModel inputModel)
        {
            await SetScopeAndGrantToViewBag(inputModel);

            return(View(ControllerConstants.EDIT, inputModel));
        }