public async Task <ActionResult> Update(
            string username,
            [FromBody, BindRequired] AccountUpdateRequest request)
        {
            Account account = await _accountService.GetAsync(username);

            if (account == null)
            {
                return(Error(
                           StatusCodes.Status404NotFound,
                           new ApiError(
                               "An account does not exist with the specified username.",
                               ApiErrorCode.NotFound
                               )
                           ));
            }

            try
            {
                await _accountService.UpdateAsync(account, request);

                return(Success());
            }
            catch (AccountUpdateException e)
            {
                return(HandleAccountUpdateException(e));
            }
        }
Exemplo n.º 2
0
        public async Task UpdateAsync(Account account, AccountUpdateRequest request)
        {
            AccountUpdateErrorFlags errorFlags = AccountUpdateErrorFlags.None;

            if (request.Password != null)
            {
                account.Password = _passwordHasher.HashPassword(account, request.Password);
            }
            if (request.Email != null && account.Email != request.Email)
            {
                if (await IsEmailInUse(request.Email))
                {
                    errorFlags |= AccountUpdateErrorFlags.EmailInUse;
                }
                else
                {
                    account.Email = request.Email;
                }
            }

            if (errorFlags != AccountUpdateErrorFlags.None)
            {
                throw new AccountUpdateException(
                          "An error occurred while updating the account.",
                          errorFlags
                          );
            }

            await _accountContext.SaveChangesAsync();
        }
Exemplo n.º 3
0
        public async Task <IActionResult> UpdateAccount([FromBody] AccountUpdateRequest request)
        {
            // Validate inputs
            string modelError = string.Empty;

            if (!ModelState.IsValid)
            {
                //status code 400
                return(BadRequest());
            }

            if (request == null)
            {
                request = new AccountUpdateRequest();
            }
            else if (request.AccountID < 1)
            {
                return(BadRequest("AccountID is invalid!"));
            }
            else
            {
                int?actionEmployee = request.ActionEmployee;
                if ((actionEmployee.GetValueOrDefault() < 1) & actionEmployee.HasValue)
                {
                    return(BadRequest("ActionEmployee is invalid!"));
                }
            }

            try
            {
                string strSQL = @"exec [CMX_Update_Account] @AccountID=";
                strSQL = strSQL + request.AccountID.ToString();
                strSQL = strSQL + @", @QueueDate='";
                strSQL = strSQL + request.QueueDate.ToString();
                strSQL = strSQL + @"', @CurrentAction=";
                strSQL = strSQL + request.CurrentAction.ToString();
                strSQL = strSQL + @", @CurrentNextAction=";
                strSQL = strSQL + request.CurrentNextAction.ToString();
                strSQL = strSQL + @", @AgencyStatusID=";
                strSQL = strSQL + request.AgencyStatusID.ToString();
                strSQL = strSQL + @", @SystemStatusID=";
                strSQL = strSQL + request.SystemStatusID.ToString();
                strSQL = strSQL + @", @ActionEmployee=";
                strSQL = strSQL + request.ActionEmployee.ToString();
                await WorksContext.Database.ExecuteSqlCommandAsync(strSQL);

                return(Ok("Update Account successfully!"));
            }
            catch (Exception ex)
            {
                WriteLog(ex, nameof(ActivityController) + "-" + nameof(UpdateAccount), LogLevel.Error, false);

                // status code = 400
                return(BadRequest());

                throw;
            }
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Update([FromBody] AccountUpdateRequest req)
        {
            var id   = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
            var user = await _userService.Update(id, req);

            if (user == null)
            {
                return(BadRequest(new { message = "Network error. User could not be updated." }));
            }

            return(NoContent());
        }
Exemplo n.º 5
0
        public IHttpActionResult UpdateAccount(AccountUpdateRequest dto)
        {
            var username = GetUser();

            try
            {
                var result = _service.UpdateAccount(username, dto);
                return(Json(ApiResult.Success()));
            }
            catch (Exception ex)
            {
                return(Json(ApiResult.Failure("Account update Failed")));
            }
        }
Exemplo n.º 6
0
        public OpResult UpdateAccount(string userName, AccountUpdateRequest dto)
        {
            var account = _repo.GetFirst <Account>(a => a.UserName == userName, null, "Profiles");

            if (account == null)
            {
                return(OpResult.FailureResult("Account not found"));
            }

            var profile = account.GetProfile();

            if (profile == null)
            {
                if (!(string.IsNullOrEmpty(dto.FirstName) && string.IsNullOrWhiteSpace(dto.LastName)))
                {
                    profile = new Profile();
                    account.Profiles.Add(profile);
                }
            }
            if (profile != null)
            {
                profile.FirstName = dto.FirstName;
                profile.LastName  = dto.LastName;
            }

            if (account.Email != dto.Email)
            {
                var anotherAccount = _repo.GetFirst <Account>(a => a.ID != dto.Id && a.Email == dto.Email, null, "Profiles");
                if (anotherAccount != null)
                {
                    return(OpResult.FailureResult("eMail already exists"));
                }

                account.Email = dto.Email;
            }

            AccountValidator validator = new AccountValidator();
            var validationResult       = validator.Validate(account);

            if (!validationResult.IsValid)
            {
                return(OpResult.FailureResult(validationResult.Errors.Select(e => e.ErrorMessage).ToList()));
            }

            _repo.Update <Account>(account);
            _repo.Save();

            return(OpResult.SuccessResult());
        }
Exemplo n.º 7
0
        public ActionResult Save(AccountManagementModel accountManagementModel)
        {
            if (ModelState.IsValid)
            {
                var accountDetail = _accountDao.FindById(accountManagementModel.Id);

                var accountUpdateRequest = new AccountUpdateRequest
                {
                    AccountId = accountManagementModel.Id,
                    BookingSettingsRequest = new BookingSettingsRequest
                    {
                        AccountNumber     = accountDetail.Settings.AccountNumber,
                        ChargeTypeId      = accountDetail.Settings.ChargeTypeId,
                        Country           = accountManagementModel.CountryCode,
                        CustomerNumber    = accountDetail.Settings.CustomerNumber,
                        DefaultTipPercent = accountManagementModel.DefaultTipPercent,
                        Email             = accountManagementModel.Email,
                        FirstName         = accountDetail.Name,
                        LastName          = accountDetail.Name,
                        Name          = accountManagementModel.Name,
                        NumberOfTaxi  = accountDetail.Settings.NumberOfTaxi,
                        Passengers    = accountDetail.Settings.Passengers,
                        PayBack       = accountDetail.Settings.PayBack,
                        Phone         = accountManagementModel.PhoneNumber,
                        ProviderId    = accountDetail.Settings.ProviderId,
                        VehicleTypeId = accountDetail.Settings.VehicleTypeId
                    }
                };

                try
                {
                    _bookingSettingsService.Put(accountUpdateRequest);
                    TempData["UserMessage"] = "Operation done successfully";
                }
                catch (Exception e)
                {
                    TempData["UserMessage"] = e.Message;
                }
            }
            else
            {
                TempData["UserMessage"] = "Model state is not valid";
            }

            // needed to feed orders list
            accountManagementModel.OrdersPaged = GetOrders(accountManagementModel.Id, accountManagementModel.OrdersPageIndex, accountManagementModel.OrdersPageSize);

            return(View("Index", accountManagementModel));
        }
Exemplo n.º 8
0
        public async Task <AccountResponse> Update(string id, AccountUpdateRequest req)
        {
            var user = await Task.Run(() => _context.Account.FirstOrDefault(x => x.id.ToString() == id));

            if (user == null)
            {
                return(null);
            }

            user.first_name      = req.first_name;
            user.last_name       = req.last_name;
            user.password        = BCrypt.Net.BCrypt.HashPassword(req.password);
            user.account_updated = DateTime.Now;
            await _context.SaveChangesAsync();

            return(_mapper.Map <AccountResponse>(user.WithoutPassword()));
        }
        public async Task <ActionResult> Update(
            [ModelBinder(
                 BinderType = typeof(AuthorizedAccountBinder)
                 ), BindRequired] Account account,
            [FromBody, BindRequired] AccountUpdateRequest request)
        {
            try
            {
                await _accountService.UpdateAsync(account, request);

                return(Success());
            }
            catch (AccountUpdateException e)
            {
                return(HandleAccountUpdateException(e));
            }
        }
Exemplo n.º 10
0
        public async Task <ActionResult <AccountResponse> > Update(string id, AccountUpdateRequest model)
        {
            // users can update their own account and admins can update any account
            if (id != Account.Id && Account.Role != Role.Admin)
            {
                return(Unauthorized(new { message = "Unauthorized" }));
            }

            // only admins can update role
            if (Account.Role != Role.Admin)
            {
                model.Role = null;
            }

            var account = await _accountService.Update(id, model);

            return(Ok(account));
        }
Exemplo n.º 11
0
        public HttpResponseMessage Update(int id, AccountUpdateRequest updateRequest)
        {
            if (updateRequest == null)
            {
                ModelState.AddModelError("", "There was no data recieved at the endpoint.");
            }
            else if (id != updateRequest.Id)
            {
                ModelState.AddModelError("id", "id in the URL does not match the ID in the body");
            }

            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
            accountService.Update(updateRequest);

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Exemplo n.º 12
0
        //TODO: Broke because i changed the stored procedure
        //public Account SelectById(int id)
        //{
        //    Account model = new Account();
        //    using (SqlConnection conn = new SqlConnection(connStr))
        //    {
        //        string cmdText = "accounts_selectbyid";
        //        using (SqlCommand cmd = new SqlCommand(cmdText, conn))
        //        {
        //            cmd.CommandType = System.Data.CommandType.StoredProcedure;
        //            cmd.Parameters.AddWithValue("@Id", id);
        //            conn.Open();
        //            SqlDataReader reader = cmd.ExecuteReader();
        //            while(reader.Read())
        //            {
        //                int index = 0;
        //                model.Id = reader.GetInt32(index++);
        //                model.Username = reader.GetString(index++);
        //                model.PasswordHash = reader.GetString(index++);
        //                model.Salt = reader.GetString(index++);
        //                model.Email = reader.GetString(index++);
        //                model.CreatedDate = reader.GetDateTime(index++);
        //                model.ModifiedDate = reader.GetDateTime(index++);
        //                model.ModifiedBy = reader.GetString(index++);
        //            }
        //            conn.Close();
        //        }
        //    }
        //    return model;
        //}

        public void Update(AccountUpdateRequest model)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string cmdText = "accounts_update";
                using (SqlCommand cmd = new SqlCommand(cmdText, conn))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Id", model.Id);
                    cmd.Parameters.AddWithValue("@Username", model.Username);
                    cmd.Parameters.AddWithValue("@PasswordHash", model.PasswordHash);
                    cmd.Parameters.AddWithValue("@Salt", model.Salt);
                    cmd.Parameters.AddWithValue("@Email", model.Email);
                    cmd.Parameters.AddWithValue("@ModifiedBy", model.ModifiedBy);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
        }
Exemplo n.º 13
0
        public async Task <IActionResult> UpdateAccount([FromBody] AccountUpdateRequest amount)
        {
            var account = await _context.Accounts.FirstOrDefaultAsync();

            double newAmount = 0;

            if (amount != null)
            {
                newAmount = Convert.ToDouble(amount.Amount);
            }

            account.Balance   += newAmount;
            account.Available -= newAmount;

            _context.Accounts.Update(account);

            await _context.SaveChangesAsync();

            return(Ok(account));
        }
Exemplo n.º 14
0
 public HttpResponseMessage Put(int id, [FromBody] AccountUpdateRequest model)
 {
     try
     {
         if (ModelState.IsValid)
         {
             model.ModifiedBy = "Temp Modifier";
             svc.Update(model);
             SuccessResponse resp = new SuccessResponse();
             return(Request.CreateResponse(HttpStatusCode.OK, resp));
         }
         else
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
         }
     }
     catch (Exception ex)
     {
         return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message));
     }
 }
Exemplo n.º 15
0
        public int Update(AccountUpdateRequest updateRequest)
        {
            int affectedRows = 0;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string sqlQuery = "Account_Update";
                using (SqlCommand command = new SqlCommand(sqlQuery, connection))
                {
                    command.CommandType = System.Data.CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@Id", updateRequest.Id);
                    command.Parameters.AddWithValue("@Email", updateRequest.Email);
                    command.Parameters.AddWithValue("@Password", updateRequest.Password /*?? (object)DBNull.Value at the end of a parameter*/);
                    command.Parameters.AddWithValue("ModifiedBy", updateRequest.ModifiedBy);
                    //If a parameter is nullable, ? in the model and also ?? (object)DBNull.Value at the end of a parameter.

                    connection.Open();
                    affectedRows = command.ExecuteNonQuery();
                    connection.Close();
                }
            }
            return(affectedRows);
        }
Exemplo n.º 16
0
        public async Task <AccountResponse> Update(string id, AccountUpdateRequest model)
        {
            var account = await getAccount(id);

            // validate
            if (account.Email != model.Email && _accountRepository.FindByEmail(model.Email) != null)
            {
                throw new Exception($"Email '{model.Email}' is already taken");
            }

            // hash password if it was entered
            if (!string.IsNullOrEmpty(model.Password))
            {
                account.PasswordHash = BC.HashPassword(model.Password);
            }

            // copy model to account and save
            _mapper.Map(model, account);
            account.Updated = DateTime.UtcNow;
            await _accountRepository.Update(account);

            return(_mapper.Map <AccountResponse>(account));
        }
Exemplo n.º 17
0
        public AccountResponse Update(int id, AccountUpdateRequest model)
        {
            var account = getAccount(id);

            // validate
            if (account.Email != model.Email && _context.Accounts.Any(x => x.Email == model.Email))
            {
                throw new AppException($"Email '{model.Email}' is already taken");
            }

            // hash password if it was entered
            if (!string.IsNullOrEmpty(model.Password))
            {
                account.PasswordHash = BC.HashPassword(model.Password);
            }

            // copy model to account and save
            _mapper.Map(model, account);
            account.Updated = DateTime.UtcNow;
            _context.Accounts.Update(account);
            _context.SaveChanges();

            return(_mapper.Map <AccountResponse>(account));
        }
Exemplo n.º 18
0
        public async Task <IActionResult> UpdateAsync([FromBody] AccountUpdateRequest request)
        {
            try
            {
                var userCheckin = await _repo.GetUserCheckinAsync(request.Code);

                if (userCheckin == null)
                {
                    return(NotFound($"Actual user checkin with code={request.Code} not found"));
                }
                await _repo.ChangeAccountAsync(userCheckin, request.UserName, request.UserPassword);

                return(Ok());
            }
            catch (UserAccountException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"error {nameof(AccountController.UpdateAsync)} {this.GetType().Name}");
                return(InternalServerError(ex));
            }
        }
Exemplo n.º 19
0
        public async Task <ActionResult <AccountResponse> > Update([FromBody] AccountUpdateRequest account)
        {
            var response = await AccountBusiness.Update(User.Account(), (Account)account);

            return((AccountResponse)response);
        }
Exemplo n.º 20
0
        public IActionResult Update([FromRoute] Guid id, [FromBody] AccountUpdateRequest account)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.GetReadableString()));
            }

            var accountToUpdate = AccountRepository.Get(id);

            if (accountToUpdate == default(Account))
            {
                return(NotFound());
            }

            Account accountRecord;

            if (User.GetId() == id && !User.IsInRole(nameof(Role.Administrator)))
            {
                if (!string.IsNullOrWhiteSpace(account.Name) && account.Name != accountToUpdate.Name)
                {
                    return(StatusCode(403, "Users may not change their Account name."));
                }

                if (account.Role != null && account.Role != accountToUpdate.Role)
                {
                    return(StatusCode(403, "Users may not change their Role."));
                }

                if (string.IsNullOrWhiteSpace(account.Password))
                {
                    return(BadRequest("A password must be specified."));
                }

                accountRecord = new Account()
                {
                    Id                    = accountToUpdate.Id,
                    Name                  = accountToUpdate.Name,
                    Role                  = accountToUpdate.Role,
                    PasswordHash          = Utility.ComputeSHA512Hash(account.Password),
                    PasswordResetRequired = false,
                    LastUpdateById        = accountToUpdate.LastUpdateById,
                    LastUpdateDate        = accountToUpdate.LastUpdateDate,
                };
            }
            else if (User.IsInRole(nameof(Role.User)))
            {
                return(StatusCode(403, "Users may not modify another user's Account."));
            }
            else if (User.IsInRole(nameof(Role.Supervisor)))
            {
                if (account.Role != null)
                {
                    return(StatusCode(403, "Supervisors may not modify user Roles."));
                }

                if (accountToUpdate.Role == Role.Administrator || accountToUpdate.Role == Role.Supervisor)
                {
                    return(StatusCode(403, "Supervisors may not modify administrative or supervisory Accounts."));
                }

                if (AccountNameExistsExcludingId(account.Name, id))
                {
                    return(Conflict($"A user named '{account.Name}' already exists."));
                }

                accountRecord = new Account()
                {
                    Id           = accountToUpdate.Id,
                    Name         = account.Name ?? accountToUpdate.Name,
                    Role         = accountToUpdate.Role,
                    PasswordHash = account.Password == null ? accountToUpdate.PasswordHash :
                                   Utility.ComputeSHA512Hash(account.Password),
                    PasswordResetRequired = account.Password != null,
                    LastUpdateById        = User.GetId(),
                    LastUpdateDate        = DateTime.UtcNow,
                };
            }
            else if (User.IsInRole(nameof(Role.Administrator)))
            {
                if (AccountNameExistsExcludingId(account.Name, id))
                {
                    return(Conflict($"A user named '{account.Name}' already exists."));
                }

                accountRecord = new Account()
                {
                    Id           = accountToUpdate.Id,
                    Name         = account.Name ?? accountToUpdate.Name,
                    Role         = account.Role ?? accountToUpdate.Role,
                    PasswordHash = account.Password == null ? accountToUpdate.PasswordHash :
                                   Utility.ComputeSHA512Hash(account.Password),
                    PasswordResetRequired = User.GetId() != accountToUpdate.Id && account.Password != null,
                    LastUpdateById        = User.GetId(),
                    LastUpdateDate        = DateTime.UtcNow,
                };
            }
            else
            {
                return(StatusCode(403, "User Role has no rights to perform an Account update."));
            }

            try
            {
                var updatedAccount = AccountRepository.Update(accountRecord);
                return(Ok(MapAccountResponseFrom(updatedAccount)));
            }
            catch (Exception ex)
            {
                throw new Exception($"Error updating account for '{accountToUpdate.Name}': {ex.Message}", ex);
            }
        }
        public object Put(AccountUpdateRequest accountUpdateRequest)
        {
            Guid accountId = accountUpdateRequest.AccountId;
            var  request   = accountUpdateRequest.BookingSettingsRequest;

            AccountDetail existingEmailAccountDetail = _accountDao.FindByEmail(request.Email);
            AccountDetail currentAccountDetail       = _accountDao.FindById(accountId);

            if (currentAccountDetail.Email != request.Email && currentAccountDetail.FacebookId.HasValue())
            {
                throw new HttpError(HttpStatusCode.BadRequest, _resources.Get("EmailChangeWithFacebookAccountErrorMessage"));
            }

            if (existingEmailAccountDetail != null && existingEmailAccountDetail.Email == request.Email && existingEmailAccountDetail.Id != accountId)
            {
                throw new HttpError(HttpStatusCode.BadRequest, ErrorCode.EmailAlreadyUsed.ToString(), _resources.Get("EmailUsedMessage"));
            }

            CountryCode countryCode = CountryCode.GetCountryCodeByIndex(CountryCode.GetCountryCodeIndexByCountryISOCode(request.Country));

            if (PhoneHelper.IsPossibleNumber(countryCode, request.Phone))
            {
                request.Phone = PhoneHelper.GetDigitsFromPhoneNumber(request.Phone);
            }
            else
            {
                throw new HttpError(string.Format(_resources.Get("PhoneNumberFormat"), countryCode.GetPhoneExample()));
            }

            var isChargeAccountEnabled = _serverSettings.GetPaymentSettings().IsChargeAccountPaymentEnabled;

            // Validate account number if charge account is enabled and account number is set.
            if (isChargeAccountEnabled && !string.IsNullOrWhiteSpace(request.AccountNumber))
            {
                if (!request.CustomerNumber.HasValue())
                {
                    throw new HttpError(HttpStatusCode.Forbidden, ErrorCode.AccountCharge_InvalidAccountNumber.ToString());
                }

                // Validate locally that the account exists
                var account = _accountChargeDao.FindByAccountNumber(request.AccountNumber);
                if (account == null)
                {
                    throw new HttpError(HttpStatusCode.Forbidden, ErrorCode.AccountCharge_InvalidAccountNumber.ToString());
                }

                // Validate with IBS to make sure the account/customer is still active
                var ibsChargeAccount = _ibsServiceProvider.ChargeAccount().GetIbsAccount(request.AccountNumber, request.CustomerNumber);
                if (!ibsChargeAccount.IsValid())
                {
                    throw new HttpError(HttpStatusCode.Forbidden, ErrorCode.AccountCharge_InvalidAccountNumber.ToString());
                }
            }

            var command = new UpdateBookingSettings();

            Mapper.Map(request, command);

            command.AccountId = accountId;

            _commandBus.Send(command);

            return(new HttpResult(HttpStatusCode.OK));
        }