예제 #1
0
        public async Task <ServiceResponse <GetAccountDto> > UpdateAccount(UpdateAccountDto accountDto, int userId)
        {
            var serviceResponse = new ServiceResponse <GetAccountDto>();
            var savedAccount    = await userManager.FindByIdAsync(userId.ToString());

            if (savedAccount is null)
            {
                serviceResponse.Message    = $"Failed to update user with id {userId}: Account not found";
                serviceResponse.Successful = false;
                serviceResponse.StatusCode = StatusCodes.Status400BadRequest;
            }
            else
            {
                savedAccount.UserName    = accountDto.Name;
                savedAccount.Email       = accountDto.Email;
                savedAccount.PhoneNumber = accountDto.PhoneNumber;
                var result = await userManager.UpdateAsync(savedAccount);

                serviceResponse = await GetAccountById(userId);

                if (result.Succeeded && serviceResponse.Successful)
                {
                    serviceResponse.Message = $"User with id {userId} was updated";
                }
                else
                {
                    serviceResponse.Message    = GetErrorsString(result.Errors, $"Failed to update user with id { userId }! ");
                    serviceResponse.Successful = false;
                    serviceResponse.StatusCode = StatusCodes.Status400BadRequest;
                }
            }
            return(serviceResponse);
        }
        public IActionResult UpdateAccountIdentification([FromBody] UpdateAccountDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            try
            {
                if (dto.licenseId != null && dto.licenseId != "")
                {
                    if (_accountService.validateLicense(dto.licenseId))
                    {
                        return(StatusCode(StatusCodes.Status403Forbidden, "DMV"));
                    }

                    if (_accountService.validateFraudLicense(dto.licenseId))
                    {
                        return(StatusCode(StatusCodes.Status403Forbidden, "Fraud"));
                    }
                }
                _accountService.UpdateAccountIdentificationDetails(dto);
                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest("Update Failed" + ex.Message));
            }
        }
예제 #3
0
 public HttpResponseMessage UpdateAccount([FromBody] UpdateAccountDto updateAccountDto)
 {
     return(Request.ExecuteProtectedAndWrapResult <UpdateAccountDto, AccountModel>(
                dto => AccountService.Update(dto),
                ModelState, updateAccountDto
                ));
 }
        //======================================= UPDATE =======================================//

        private static bool InvalidPollsterKey(UpdateAccountDto createAccountDto, UpgradeKey key, string eMail)
        {
            string dtoKey = createAccountDto.Key;

            if (dtoKey == null)
            {
                return(false);
            }
            return(key == null || key.EMail != eMail && key.EMail.Length > 0);
        }
예제 #5
0
        public async Task <IActionResult> UpdateOtherAccount(UpdateAccountDto updateAccountDto)
        {
            ServiceResponse <Account> accountResponse = await _register.UpdateOtherAccount(updateAccountDto);

            var response = new Response <Account>(accountResponse);

            return(accountResponse.Code switch
            {
                HttpStatusCode.UnprocessableEntity => UnprocessableEntity(response),
                HttpStatusCode.NotFound => NotFound(response),
                _ => Ok(response)
            });
예제 #6
0
        public virtual async Task <AccountDto> UpdateAccountAsync(int accountId, UpdateAccountDto accountDto)
        {
            var account = await Utils.GetAccountAsync(_db, accountId);

            try
            {
                var errors = new List <ValidationResult>();

                Utils.ValidateDto(accountDto, errors);
                Utils.ThrowAggregateExceptionOnValidationErrors(errors);

                account.Name = !string.IsNullOrEmpty(accountDto.AccountName)
                    ? accountDto.AccountName
                    : account.Name;

                account.AccountTypeId = accountDto.AccountTypeId != default
                    ? accountDto.AccountTypeId
                    : account.AccountTypeId;

                account.ArchetypeId = accountDto.ArchetypeId != default
                    ? accountDto.ArchetypeId
                    : account.ArchetypeId;

                account.SalesforceAccountId = !string.IsNullOrEmpty(accountDto.SalesforceAccountId)
                    ? accountDto.SalesforceAccountId
                    : account.SalesforceAccountId;

                account.SalesforceAccountManager = !string.IsNullOrEmpty(accountDto.SalesforceAccountManager)
                    ? accountDto.SalesforceAccountManager
                    : account.SalesforceAccountManager;

                account.SalesforceAccountNumber = !string.IsNullOrEmpty(accountDto.SalesforceAccountNumber)
                    ? accountDto.SalesforceAccountNumber
                    : account.SalesforceAccountNumber;

                account.SalesforceAccountUrl = !string.IsNullOrEmpty(accountDto.SalesforceAccountUrl)
                    ? accountDto.SalesforceAccountUrl
                    : account.SalesforceAccountUrl;

                account.ContractNumber = !string.IsNullOrEmpty(accountDto.ContractNumber)
                    ? accountDto.ContractNumber
                    : account.ContractNumber;

                _db.Entry(account).State = EntityState.Modified;
                await _db.SaveChangesAsync();

                return(_mapper.Map <AccountDto>(account));
            }
            catch (DbException e)
            {
                throw new PersistenceException($"An error occurred while updating Account ({nameof(accountId)}={accountId}, {nameof(accountDto)}={JsonConvert.SerializeObject(accountDto)})", e);
            }
        }
        public async Task <ServiceResponse <Account> > UpdateOtherAccount(UpdateAccountDto updateAccountDto)
        {
            if (updateAccountDto.EMail == null)
            {
                return(new ServiceResponse <Account>()
                       .Failure(NoEmailProvided, HttpStatusCode.UnprocessableEntity));
            }
            var response = await UpdateAccount(updateAccountDto);

            return(response.Data == null
                ? response
                : response.Success(_mapper.Map <Account>(response.Data), SuccessfulUpdateStr));
        }
        public async Task <ServiceResponse <Account> > UpdateMyAccount(UpdateAccountDto updateAccountDto,
                                                                       HttpContext context)
        {
            var response = await UpdateAccount(updateAccountDto);

            if (response.Data == null)
            {
                return(response);
            }
            await UpdateCurrentIdentity(context, response.Data);

            return(response.Success(_mapper.Map <Account>(response.Data), SuccessfulUpdateStr));
        }
예제 #9
0
        public async Task <bool> UpdateAccount(int id, UpdateAccountDto accountDto)
        {
            var account = _dbContext.Accounts.FirstOrDefault(x => x.AccountId == id);

            if (account == null)
            {
                return(false);
            }

            account.Name = accountDto.Name;
            await _dbContext.SaveChangesAsync();

            return(true);
        }
예제 #10
0
        public void UpdateAccountIdentificationDetails(UpdateAccountDto dto)
        {
            Account account = _repositoryFactory.AccountRepository.GetAccountById(dto.id);

            if (dto.licenseId != null && dto.licenseId != "")
            {
                ImageFile drivingLicense = JsonConvert.DeserializeObject <ImageFile>(dto.drivingLicense.ToString());
                account.drivingLicense = Convert.FromBase64String(drivingLicense.value);
            }

            if (dto.additionalIdentification != null)
            {
                ImageFile additionalIdentification = JsonConvert.DeserializeObject <ImageFile>(dto.additionalIdentification.ToString());
                account.additionalIdentification = Convert.FromBase64String(additionalIdentification.value);
            }
            _repositoryFactory.AccountRepository.Update(account);
        }
예제 #11
0
        public AccountModel Update(UpdateAccountDto dto)
        {
            return(ProtectedExecute <UpdateAccountDto, AccountModel>(accountDto =>
            {
                SessionService.CheckSession(accountDto.Session);

                if (accountDto.Id != accountDto.Session.UserId)
                {
                    throw new ForbiddenException("Account owner");
                }

                accountDto.Password = Hasher.GetHash(accountDto.Password);
                AccountModel model = Mapper.Map <UpdateAccountDto, AccountModel>(accountDto);

                return AccountRepo.Update(model.Id, model);
            }, dto));
        }
        public IActionResult UpdateAccount([FromBody] UpdateAccountDto dto)
        {
            if (string.IsNullOrEmpty(dto.Password))
            {
                return(BadRequest("Password cannot be empty"));
            }

            if (dto.Password.Length < 5)
            {
                return(BadRequest("Password need to be 5 characters or longer"));
            }

            var account = _accountService.GetAccount(User.FindFirst("name").Value);

            _accountService.UpdateAccount(_mapper.Map(dto, account));

            return(Ok("Account updated"));
        }
        public async Task <IActionResult> UpdateAccountById([ModelBinder(BinderType = typeof(JsonModelBinder))][Required][FromForm(Name = "userdata")] UpdateAccountDto updateAccountDto,
                                                            [FromRoute] int userId)
        {
            if (User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier)?.Value == userId.ToString())
            {
                var serviceResponse = await accountService.UpdateAccount(updateAccountDto, userId);

                var controllerResponse = mapper.Map <ServiceResponse <GetAccountDto>, ControllerResponse <GetAccountDto> >(serviceResponse);

                return(StatusCode(serviceResponse.StatusCode, controllerResponse));
            }
            else
            {
                return(Unauthorized(new ControllerResponse()
                {
                    Message = "You cannot update details of other users!", Successful = false
                }));
            }
        }
예제 #14
0
        public ActionResult UpdateAccount(int id, UpdateAccountDto accountDto)
        {
            var existingAccount = repository.GetAccount(id);

            if (existingAccount is null)
            {
                return(NotFound());
            }

            Models.Account updatedAccount = existingAccount with
            {
                AccountId = accountDto.AccountId,
                FirstName = accountDto.FirstName,
                LastName  = accountDto.LastName
            };

            repository.UpdateAccount(updatedAccount);

            return(NoContent());
        }
예제 #15
0
        public async Task <ApiResult> AccountUpdate(UpdateAccountDto input)
        {
            using var tran = await unitofWork.BeginTransactionAsync();

            var account = await accountRepository.GetAsync(input.ID);

            if (account == null)
            {
                throw new ApplicationServiceException("所选用户不存在!");
            }
            account.UpdateNicknameOrPassword(input.NickName, input.Password);
            account.SetRoles(input.Roles);
            account.User.CreateOrUpdateUser(input.User?.UserName, "", input.User?.Address, input.User?.Tel, input.User?.Gender == null ? UserGender.Unknown : (UserGender)input.User?.Gender, input.User?.BirthDay);
            accountRepository.Update(account);
            if (await new RoleValidityCheckSpecification(roleRepository).IsSatisfiedBy(account))
            {
                await unitofWork.CommitAsync(tran);
            }
            await BuildLoginCache(account);

            return(ApiResult.Ok("用户信息更新成功"));
        }
예제 #16
0
        public async Task <ActionResult> Update(UpdateAccountDto updateAccountDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values.SelectMany(x => x.Errors)));
            }

            var user = await GetAuthenticatedUserAccount();

            if (user == null)
            {
                return(NotFound(new { Message = "User account not found" }));
            }

            if (!string.IsNullOrEmpty(updateAccountDto.Email) &&
                user.Email != updateAccountDto.Email &&
                await _userManager.Users.FirstOrDefaultAsync(u => u.Email == updateAccountDto.Email) == null)
            {
                user.EmailConfirmed = false;
                user.Email          = updateAccountDto.Email;
                var mailToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                var confirmationUrl = Url.Link("ConfirmEmail", new { token = mailToken, email = user.Email });
                await _mailService.SendMailAsync(
                    user.Email,
                    "Agree - Confirmation",
                    $"<html><body>Hello, {user.DisplayName}#{user.Tag.ToString().PadLeft(4, '0')}. Please click <a href=\"{confirmationUrl}\">HERE</a> to confirm your new email.</body></html>");
            }

            if (!string.IsNullOrEmpty(updateAccountDto.UserName) &&
                user.DisplayName != updateAccountDto.UserName)
            {
                var userWithSameTagAndName = await _userManager.Users.FirstOrDefaultAsync(
                    u => u.DisplayName == updateAccountDto.UserName &&
                    u.Tag == user.Tag);

                if (userWithSameTagAndName == null)
                {
                    user.DisplayName = updateAccountDto.UserName;
                }
            }

            if (user.Tag != updateAccountDto.Tag)
            {
                var userWithSameTagAndName = await _userManager.Users.FirstOrDefaultAsync(
                    u => u.DisplayName == user.DisplayName &&
                    u.Tag == updateAccountDto.Tag);

                if (userWithSameTagAndName == null)
                {
                    user.Tag = updateAccountDto.Tag;

                    if (!string.IsNullOrEmpty(updateAccountDto.UserName) &&
                        user.DisplayName != updateAccountDto.UserName)
                    {
                        userWithSameTagAndName = await _userManager.Users.FirstOrDefaultAsync(
                            u => u.DisplayName == updateAccountDto.UserName &&
                            u.Tag == user.Tag);

                        if (userWithSameTagAndName == null)
                        {
                            user.DisplayName = updateAccountDto.UserName;
                        }
                    }
                }
            }

            var result = await _userManager.UpdateAsync(user);

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

            var userViewModel = _mapper.Map <ApplicationUserViewModel>(user);

            Response.Cookies.Append("agreeallow_accesstoken", await _tokenService.GenerateToken(user.Email), new CookieOptions
            {
                HttpOnly = true,
                SameSite = SameSiteMode.Strict
            });

            return(Ok(new UserResponse(userViewModel)));
        }
예제 #17
0
        public async Task <ActionResult <AccountDto> > UpdateAccount([FromRoute] int id, [FromBody] UpdateAccountDto accountDto)
        {
            if (!ModelState.IsValid)
            {
                BadRequest(ModelState);
            }

            var account = await _accountService.UpdateAccount(id, accountDto);

            if (!account)
            {
                return(NotFound());
            }
            return(Ok());
        }
 private static (bool, bool) GetConditions(UpdateAccountDto dto) => (dto.Tags != null, dto.Key != null);
예제 #19
0
 protected override void UpdateEntity(UpdateAccountDto updateItemDto, SharedAccount entity)
 {
     entity.Update(updateItemDto.FirstName, updateItemDto.LastName, updateItemDto.Email);
 }
예제 #20
0
        protected override async Task <GetAccountDto> ExecuteAsync(UpdateAccountCommand request, CancellationToken ct)
        {
            UpdateAccountDto accountDto = _mapper.Map <UpdateAccountDto>(request);

            return(await _accountService.UpdateAsync(accountDto, ct));
        }
예제 #21
0
        public async Task <IActionResult> DepositAndWidthdraw(Guid userId, Guid accountId, [FromBody] UpdateAccountDto model, bool deposit = true)
        {
            if (!await _accountRepo.AccountExists(userId, accountId))  //check account exist
            {
                return(BadRequest("Account does not exits"));
            }

            lock (_lockAccount) //user lock or RabbitMQ
            {
                var accountFromDb  = _accountRepo.GetEntities(x => true).SingleOrDefaultAsync(x => x.Id == accountId).Result;
                var editAccountDto = _mapper.Map <EditAccountDto>(accountFromDb);
                if (deposit)
                {
                    editAccountDto.CurrentBalance += model.CurrentBalance;
                }
                else
                {
                    editAccountDto.CurrentBalance -= model.CurrentBalance;
                }

                if (editAccountDto.CurrentBalance > 0)
                {
                    var result = _accountRepo.EditByDTOAsync(editAccountDto).GetAwaiter().GetResult();
                    if (result)
                    {
                        _logger.LogInformation($"Deposit Success");
                        return(Ok("Update success"));
                    }
                }

                return(BadRequest($"Cannot Withdraw or deposit"));
            }
        }
 //[AuthorizeRbac("accounts:write")]
 public async Task <IActionResult> UpdateAccount(int accountId, UpdateAccountDto accountDto)
 {
     return(Ok(await _updateAccount.UpdateAccountAsync(accountId, accountDto)));
 }