Exemplo n.º 1
0
        public ActionResult AddCliente(Cliente cliente)
        {
            _repository.AddAsync(cliente);

            if (!_repository.SaveChanges())
            {
                return(BadRequest("Cliente não pode ser adicionado"));
            }

            return(Ok(cliente));
        }
Exemplo n.º 2
0
        public async Task <ResultEntity> AddOrUpdateAsync(Client client)
        {
            var result = new ResultEntity();
            var exist  = await _clientRepository.GetQueryable().Where(a => a.Name == client.DeviceCode && a.Id != client.Id).CountAsync() > 0;

            if (exist)
            {
                result.Message = "设备码已存在";
            }
            else
            {
                if (client.Id > 0)
                {
                    _clientRepository.Update(client);
                }
                else
                {
                    await _clientRepository.AddAsync(client);
                }

                result.Success = true;
            }

            return(result);
        }
Exemplo n.º 3
0
        public async Task <List <ClientDto> > AddClientsAsync(List <ClientCreateDto> clientCreateDtos)
        {
            var clientDtos = new List <ClientDto>();
            var entities   = new List <IdentityServer4.EntityFramework.Entities.Client>();

            foreach (var dto in clientCreateDtos)
            {
                var entityModel = new ClientModelMapper().MapToClientModel(dto);

                if (string.IsNullOrEmpty(entityModel.ClientId))
                {
                    return(null);
                }

                entityModel.AllowedGrantTypes = grantsForMvcClient;

                // client has to have same scopes in api resources. Client scope name is not unique so we add all scopes to client allowed scopes.
                // we need this because identity server has no foreign key between client and api resources. It uses scope names for relation.
                entityModel.AllowedScopes = dto.ApiResources.SelectMany(x => x.Scopes).ToList();
                entityModel.AllowedScopes = entityModel.AllowedScopes.Union(defaultScopes).ToList();
                // add api resource scopes.
                await _apiResourceRepository.AddApiScopesAsync(dto.ApiResources);

                entities.Add(entityModel.ToEntity());
            }

            await _clientRepository.AddAsync(entities);

            clientDtos = entities.Select(x => new ClientModelMapper().MapToClientDto(x)).ToList();


            return(clientDtos);
        }
        //Implment interface
        public async Task <Clients> AddClients(Clients clients)
        {
            var client = new Clients
            {
                Id      = clients.Id,
                Name    = clients.Name,
                Email   = clients.Email,
                Phones  = clients.Phones,
                Address = clients.Address,
                AddedOn = clients.AddedOn
            };
            var createdUser = await _clientRepository.AddAsync(client);

            var response = new Clients
            {
                Id      = createdUser.Id,
                Name    = createdUser.Name,
                Email   = createdUser.Email,
                Phones  = createdUser.Phones,
                Address = createdUser.Address,
                AddedOn = createdUser.AddedOn,
            };

            return(response);
        }
Exemplo n.º 5
0
        public async Task <BaseResponse> RegisterClient(RegisterRequest register)
        {
            try
            {
                var isEmailExist = _clientRepository.GetSingle(x => x.Email == register.Email);
                if (isEmailExist != null)
                {
                    _response.Message = Constants.EMAIL_ALREADY_EXIST;
                    return(_response);
                }
                var client = _mapper.Map <Client>(register);
                client.CreatedOn = DateTime.Now;
                client.IsActive  = true;
                client.IsDeleted = false;

                var data = await _clientRepository.AddAsync(client);

                if (data != null)
                {
                    var loginResponse = _mapper.Map <LoginResponse>(data);
                    _response.data.loginResponse = loginResponse;
                    _response.StatusCode         = Constants.SUCCESS_CODE;
                }
                else
                {
                    _response.Message = Constants.LOGIN_FAILURE_MSG;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(_response);
        }
Exemplo n.º 6
0
        public async Task <bool> Handle(CreateClientCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                NotifyValidationErrors(request);
                return(false);
            }

            var existed = await _clientRepository.ExistedAsync(request.Client.ClientId);

            if (existed)
            {
                await _bus.RaiseEvent(new DomainNotification("key_already_existed", $"Client named {request.Client.ClientId} already exists"));

                return(false);
            }

            var client = request.GetClientEntity();

            await _clientRepository.AddAsync(client);

            if (Commit())
            {
                await _bus.RaiseEvent(new ClientCreatedEvent(client.ClientId, client.ClientName, request.ClientType));

                return(true);
            }

            return(false);
        }
Exemplo n.º 7
0
        public async Task <Client> AddAsync(Client entity)
        {
            await _entityRepository.AddAsync(entity);

            await _entityRepository.SaveChangesAsync();

            return(entity);
        }
Exemplo n.º 8
0
        public async Task <BaseResponse> AddAsync(AddClientRequest request)
        {
            var client = _mapper.Map <AddClientRequest, Client>(request);
            await _clientRepository.AddAsync(client);

            await _unitOfWork.SaveChangesAsync();

            return(new BaseResponse());
        }
Exemplo n.º 9
0
 public async Task <ClientDto> AddClientAsync(ClientDto clientToAdd)
 {
     try
     {
         return(await _clientRepository.AddAsync(clientToAdd));
     }
     catch (DataException)
     {
         throw;
     }
 }
        public async Task DeveObterCliente()
        {
            _fixture.ClearDataBase();
            var clienteBuilder = new ClienteBuilder().Instanciar();
            var request        = new HttpRequestMessageBuilder()
                                 .ComMethod(HttpMethod.Get)
                                 .ComUrl("api/Client/GetAsync/1")
                                 .ComBody(string.Empty)
                                 .Instanciar();
            await _clientRepository.AddAsync(clienteBuilder);

            var response = await _fixture.Client.SendAsync(request);

            var resultado = await response.Content.ReadAsAsync <Cliente>();

            response.IsSuccessStatusCode.Should().BeTrue();
            response.StatusCode.Should().Be(HttpStatusCode.OK);
            resultado.Id.Should().Be(1);
            resultado.Nome.Should().Be("Nome Cliente");
            resultado.SobreNome.Should().Be("Sobre Nome Cliente");
        }
Exemplo n.º 11
0
        public async Task <AuthorizationResponseModel> RegisterAsync(AuthorizationRequestModel registrationModel)
        {
            RoleData role = applicationRoleRepository.Get(registrationModel.Role);
            RegistrationResponseModel response = new RegistrationResponseModel()
            {
                IsSuccessful = false, Message = string.Empty
            };
            var userData = new UserData
            {
                Email    = registrationModel.Email,
                Password = registrationModel.Password,
                RoleId   = role.Id
            };

            IdentityResult userCreatingResult = await applicationUserRepository.CreateAsync(userData);

            if (!userCreatingResult.Succeeded)
            {
                // pushing message of first error in array
                response.Message = GetErrorMessage(userCreatingResult);
                return(response);
            }

            userData = await applicationUserRepository.FindByEmailAsync(userData.Email);

            ClientData client = new ClientData()
            {
                Name      = registrationModel.UserName,
                Surname   = registrationModel.Surname,
                PhotoPath = "default/profile.png",
                UserId    = userData.Id
            };
            ClientData addedClient = await clientRepository.AddAsync(client);

            if (addedClient == null)
            {
                response.Message = "Client not added";
            }
            response.IsSuccessful = true;
            string token       = javascriptWebTokenFactory.Create(userData.Id);
            var    sessionData = new SessionData
            {
                UserId = userData.Id,
                Token  = token,
            };
            await sessionRepository.CreateAsync(sessionData);

            response.Token = token;
            return(response);
        }
Exemplo n.º 12
0
        public async Task <ClientModel> AddAsync(ClientModel model, int userId)
        {
            if (model == null)
            {
                throw new ArgumentNullException();
            }

            var client = _clientMapper.ConvertToDataModel(model);

            client.IsActive  = true;
            client.CreatedOn = DateTime.UtcNow;
            client.UpdatedOn = DateTime.UtcNow;

            client.Application = new Application()
            {
                Name         = client.OrganizationName + "Mobile App",
                ClientId     = Guid.NewGuid(),
                ClientSecret = Guid.NewGuid(),
                Scope        = "mobile",
                CreatedOn    = DateTime.UtcNow,
                UpdatedOn    = DateTime.UtcNow
            };

            var clientAdmin = new User()
            {
                FirstName = "Client",
                LastName  = "Admin",
                Email     = client.Email,
                Role      = (int)UserRoles.ClientAdmin,
                IsActive  = true,
                CreatedOn = DateTime.UtcNow,
                UpdatedOn = DateTime.UtcNow
            };

            var password = Guid.NewGuid().ToString().Substring(1, 6);

            string salt;
            string passwordHash;

            PasswordHelpers.GenerateSaltAndHash(password, out salt, out passwordHash);

            clientAdmin.Salt         = salt;
            clientAdmin.PasswordHash = passwordHash;

            client.Users.Add(clientAdmin);

            client = await _clientRepository.AddAsync(client);

            return(_clientMapper.ConvertToModel(client));
        }
Exemplo n.º 13
0
        public async Task <ClientResponse> SaveAsync(Client client)
        {
            try
            {
                await clientRepository.AddAsync(client);

                await unitOfWork.CompleteAsync();

                return(new ClientResponse(client));
            }
            catch (Exception ex)
            {
                return(new ClientResponse($"Ошибка при сохранении Клиента: {ex.Message}"));
            }
        }
Exemplo n.º 14
0
        public async Task <ClientCreationResult> StartAsync(CreateClientCommand command)
        {
            _isCompleted = true;
            var client = Client.Create(Guid.NewGuid(), command.RedirectUri);

            client.DisplayName = command.DisplayName;
            client.UpdateSecret();
            await _repo.AddAsync(client);

            return(new ClientCreationResult
            {
                Succeed = true,
                Message = $"Client successfully created.",
                Id = client.Id
            });
        }
Exemplo n.º 15
0
        public async Task <IActionResult> Create(Client client)
        {
            if (!_authentication.IsAuthenticated(User))
            {
                return(RedirectToAction("SignIn", "Authentication"));
            }

            if (!ModelState.IsValid)
            {
                return(View("Create"));
            }

            Client newClient = await _repository.AddAsync(client);

            return(RedirectToAction("Read", "Client", newClient));
        }
Exemplo n.º 16
0
        public async Task <ClientResponse> SaveAsync(Client client)
        {
            try
            {
                Client clientIn = await _clientRepository.FindByIdAsync(client.ClientEmail);

                await _clientRepository.AddAsync(client);

                await _unitOfWork.CompleteAsync();

                return(new ClientResponse(client));
            }
            catch (Exception e)
            {
                return(new ClientResponse($"An error occurred when saving the client: {e.Message}"));
            }
        }
Exemplo n.º 17
0
        public async Task <bool> Handle(RegisterClientCommand request, CancellationToken cancellationToken = default)
        {
            var client = await _clientRepository.GetAsync(request.ClientId).ConfigureAwait(false);

            if (client != null)
            {
                return(false);
            }

            client = new Client(request.ClientId, request.Type, request.IpAddress);
            client.UpdateLastAccessTime();

            await _clientRepository.AddAsync(client).ConfigureAwait(false);

            await _clientRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken).ConfigureAwait(false);

            return(true);
        }
Exemplo n.º 18
0
        public async Task <ClientModel> Create(ClientModel clientModel)
        {
            await ValidateClientIfExist(clientModel);

            var mappedEntity = ObjectMapper.Mapper.Map <Client>(clientModel);

            if (mappedEntity == null)
            {
                throw new ApplicationException($"Entity could not be mapped.");
            }

            var newEntity = await _clientRepository.AddAsync(mappedEntity);

            _logger.LogInformation($"Entity successfully added.");

            var newMappedEntity = ObjectMapper.Mapper.Map <ClientModel>(newEntity);

            return(newMappedEntity);
        }
Exemplo n.º 19
0
        public async Task <IActionResult> New(ClientViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    model.Secret = model.Secret.ToSha256();
                    await _clientRepository.AddAsync(model.MapToModel());

                    return(RedirectToAction(nameof(Index)).WithSuccess(GENERIC_SUCCESS));
                }

                return(View(model).WithError(GENERIC_ERROR));
            }
            catch
            {
                return(RedirectToAction(nameof(Index)).WithError(GENERIC_ERROR));
            }
        }
        public async Task <ClientReadModel> RegisterAsync(ClientAddOrUpdateModel client, string refreshToken)
        {
            var clientToSave = _mapper.Map <Client>(client);

            clientToSave.Id           = Guid.NewGuid();
            clientToSave.Created      = DateTime.Now;
            clientToSave.PasswordHash = _passwordService.ComputeHash(client.Password);
            await _clientRepository.BeginTransactionAsync();

            try {
                await _clientRepository.AddAsync(clientToSave);
                await AddRefreshTokenAsync(clientToSave.Id, refreshToken);

                _clientRepository.CommitTransaction();
                return(_mapper.Map <ClientReadModel>(clientToSave));
            } catch (Exception) {
                _clientRepository.RollbackTransaction();
                throw;
            }
        }
Exemplo n.º 21
0
        public async Task <IActionResult> Add([FromBody] ClientRegister client)
        {
            if (ModelState.IsValid)
            {
                int UserId = -1;

                if (int.TryParse(HttpContext.User.FindFirst("user_id").Value, out UserId))
                {
                    var clientObj = client.getClient(UserId);
                    if (clientObj != null)
                    {
                        var result = await clientRepository.AddAsync(clientObj);

                        if (result != null)
                        {
                            return(CreatedAtAction("Add", result));
                        }
                    }
                }
                return(BadRequest("Error"));
            }
            return(BadRequest(ModelState.Values.FirstOrDefault().Errors.FirstOrDefault().ErrorMessage));
        }
        public async Task LoadClient(Log log)
        {
            var clients = await GetAllClient();

            var client = clients.Where(x => x.Name.Equals(log.ClientName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();

            if (client == null)
            {
                await clientRepository.AddAsync(new Clients()
                {
                    Name           = log.ClientName,
                    DomainAccounts = new string[0],
                    Emails         = new string[0],
                    Mobiles        = new string[0],
                    Environments   = new Models.Environment[]
                    {
                        new Models.Environment()
                        {
                            Name = log.EnvironmentName
                        }
                    }
                });

                Delete(cache_key);
            }
            else
            {
                var env = client.Environments.Where(x => x.Name.Equals(log.EnvironmentName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (env == null)
                {
                    var update = clientRepository.AddEnvAsync(client.Name, new Models.Environment()
                    {
                        Name = log.EnvironmentName
                    });
                }
            }
        }
 public async Task AddAsync(Client entity)
 {
     await clientRepository.AddAsync(entity);
 }
Exemplo n.º 24
0
 public async Task <Client> Handle(CreateClientCommand request, CancellationToken cancellationToken)
 {
     return(await _clientRepository.AddAsync(request.Client));
 }
Exemplo n.º 25
0
 public async Task AddAsync(Client client)
 {
     var userEntity = _mapper.Map <ClientEntity>(client);
     await _clientRepository.AddAsync(userEntity);
 }
Exemplo n.º 26
0
        public async Task <Client> CreateClientAsync(Client client)
        {
            var addedClient = await _clientRepository.AddAsync(client);

            return(addedClient);
        }
Exemplo n.º 27
0
 public Task AddClientAsync(Client client)
 {
     return(_clientRepository.AddAsync(client));
 }
 public async Task AddClient(Client client)
 {
     await _clientRepository.AddAsync(client.ToEntity());
 }
Exemplo n.º 29
0
 public async Task <int> AddClientAsync(AddClientDto addClientDto)
 {
     return(await _repository.AddAsync(_converter.AddClientDtoToClient(addClientDto)));
 }