public IActionResult UpdatePassword(UpdatePasswordDTO updatePasswordDTO)
        {
            var apiJsonResponse = new ApiJsonResponse();

            try
            {
                using (FoodInfoServiceContext context = new FoodInfoServiceContext())
                {
                    if (context.User.Any(x => x.IsDeleted == false && x.Username == updatePasswordDTO.Username))
                    {
                        var User = context.User.FirstOrDefault(x => x.IsDeleted == false && x.Username == updatePasswordDTO.Username);
                        if (updatePasswordDTO.NewPassword != string.Empty)
                        {
                            User.Password     = HelperFunctions.ComputeSha256Hash(updatePasswordDTO.NewPassword);
                            User.ModifiedDate = DateTime.Now;
                            context.SaveChanges();
                            return(apiJsonResponse.ApiOkContentResult(updatePasswordDTO));
                        }
                        else
                        {
                            return(apiJsonResponse.ApiBadRequestWithMessage(PublicConstants.PasswordRequired));
                        }
                    }
                    else
                    {
                        return(apiJsonResponse.ApiBadRequestWithMessage(PublicConstants.UserNotFoundError));
                    }
                }
            }
            catch
            {
                return(apiJsonResponse.ApiBadRequestWithMessage(PublicConstants.SysErrorMessage));
            }
        }
Exemplo n.º 2
0
        public void updatePasswordTest()
        {
            MockAccountDataMapper mapper       = new MockAccountDataMapper(false);
            MockTokenService      tokenService = new MockTokenService();
            AccountService        service      = new AccountService(mapper, tokenService);
            UpdatePasswordDTO     user         = new UpdatePasswordDTO {
                newPassword = "******"
            };
            Exception         ex    = Assert.Throws <InvalidParametersException>(() => service.updatePassword(user));
            UpdatePasswordDTO user2 = new UpdatePasswordDTO {
                username    = "******",
                newPassword = "******"
            };
            Exception ex2 = Assert.Throws <AppObjectNotFoundException>(() => service.updatePassword(user2));

            mapper  = new MockAccountDataMapper(true);
            service = new AccountService(mapper, tokenService);
            UpdatePasswordDTO user3 = new UpdatePasswordDTO {
                username = "******",
            };
            Exception ex3 = Assert.Throws <InvalidParametersException>(() => service.updatePassword(user3));

            Assert.Equal(ex3.Message, "newPassword parameter can not be empty");
            UpdatePasswordDTO user4 = new UpdatePasswordDTO {
                username    = "******",
                newPassword = "******"
            };

            service.updatePassword(user4);
            Assert.Equal(mapper.getUpdateCallCount(), 1);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Update(UpdatePasswordDTO updatePasswordDTO)
        {
            if (ModelState.IsValid)
            {
                IdentityUser user = await _userManager.GetUserAsync(HttpContext.User);

                if (updatePasswordDTO.UserLoginId != user.Id)
                {
                    // Error user missmatch
                    ModelState.AddModelError(string.Empty, "User Missmatch");
                    return(PartialView("index"));
                }

                IdentityResult result = await _updatePasswordService.ChangePasswordAsync(updatePasswordDTO);

                if (result.Succeeded)
                {
                    JsonResult js = new JsonResult(new { Url = "/Common/Password/Success" });
                    js.StatusCode = 202;
                    return(js);
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                    return(PartialView("Index"));
                }
            }
            return(PartialView("Index"));
        }
        public async Task <IActionResult> UpdatePassword(UpdatePasswordDTO updatePasswordDTO)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(Messages.InvalidModel));
                }
                if (!(await _user.CheckUserByUserId(updatePasswordDTO.UserId)))
                {
                    return(BadRequest(Messages.UserNotExist));
                }
                updatePasswordDTO.Password = _util.HashPassword(updatePasswordDTO.Password);
                UserDTO userDTO = await _user.Get(updatePasswordDTO.UserId);

                if ((await _user.CheckUserExist(userDTO.UserName, updatePasswordDTO.Password, userDTO.UserId)))
                {
                    return(BadRequest(Messages.UserExist));
                }
                await _user.UpdatePassword(updatePasswordDTO);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(Messages.GeneralError));
            }
        }
Exemplo n.º 5
0
 /// <summary>
 /// Asynchronously update the <see cref="User" /> password in the system.
 /// </summary>
 /// <param name="userName">Name of the user.</param>
 /// <param name="recoveryParams">The recovery parameters.</param>
 /// <returns>True if <see cref="User" /> password is updated, false otherwise.</returns>
 public virtual async Task <bool> UpdatePasswordAsync(string userName, UpdatePasswordDTO recoveryParams)
 {
     using (IBaasicClient client = BaasicClientFactory.Create(Configuration))
     {
         return(await client.PutAsync <UpdatePasswordDTO, bool>(client.GetApiUrl(String.Format("{0}/{1}/change-password", ModuleRelativePath, userName)), recoveryParams));
     }
 }
Exemplo n.º 6
0
        public async Task UpdatePassword(UpdatePasswordDTO updatePasswordDTO)
        {
            User user = await _user.Get(m => m.UserId == updatePasswordDTO.UserId);

            user.Password    = updatePasswordDTO.Password;
            user.UpdatedDate = DateTime.Now;
            await _user.Update(user);
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Index(string LayoutUrl)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);

            UpdatePasswordDTO updatePasswordDTO = new UpdatePasswordDTO(user);

            updatePasswordDTO.LayoutUrl = LayoutUrl;
            return(View(updatePasswordDTO));
        }
Exemplo n.º 8
0
        public async Task <IdentityResult> ChangePasswordAsync(UpdatePasswordDTO updatePasswordDTO)
        {
            IdentityUser userLogin = await _userManager.FindByIdAsync(updatePasswordDTO.UserLoginId);

            IdentityResult result = await _userManager.ChangePasswordAsync(userLogin,
                                                                           updatePasswordDTO.CurrentPassword,
                                                                           updatePasswordDTO.NewPassword);

            return(result);
        }
Exemplo n.º 9
0
 public IHttpActionResult ChangePassword([FromBody] UpdatePasswordDTO updatePasswordDTO)
 {
     using (var updatePasswordHandler = new UpdatePasswordHandler(Db, ActiveUser, new ChangePasswordValidator()))
     {
         using (var transaction = new TransactionScope())
         {
             var saveResult = updatePasswordHandler.Save(updatePasswordDTO, dateStamp: DateTime.Now);
             transaction.Complete();
             if (saveResult.Success)
             {
                 return(Ok(new SuccessResponse(saveResult.Model, saveResult.Message)));
             }
             return(Ok(new ErrorResponse(ServiceStatusCode.ValidationError, saveResult.ValidationResult, saveResult.Message)));
         }
     }
 }
Exemplo n.º 10
0
        public ActionResult UpdatePassword(UpdatePasswordDTO dto)
        {
            var username = User.FindFirst("UserName")?.Value;
            var account  = _accountsRepository.CheckLogin(username, dto.CurrentPassword);

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

            account.Password = dto.NewPassword;

            _accountsRepository.Update(account);

            _accountsRepository.SaveChanges();

            return(NoContent());
        }
Exemplo n.º 11
0
        public bool UpdatePassword(UpdatePasswordDTO data)
        {
            using (var cn = new SqlConnection())
            {
                cn.ConnectionString = "Server=(localdb)\\Priceredacted;Database=PriceredactedDB";
                try
                {
                    cn.Open();
                    using (var update = new SqlCommand())
                    {
                        update.Connection  = cn;
                        update.CommandType = CommandType.Text;
                        update.CommandText = "UPDATE UserData SET Password = @PS WHERE Email = @EM";

                        update.Parameters.AddWithValue("@PS", data.NewPassword);//(new SqlParameter("@ID", SqlDbType.Int, 50, "Id"));
                        update.Parameters.AddWithValue("@EM", data.CurrentEmail);

                        SqlDataAdapter da = new SqlDataAdapter("SELECT Email, Id, Password, Username FROM UserData", cn);
                        da.UpdateCommand = update;

                        DataSet ds = new DataSet();
                        da.Fill(ds, "UserData");

                        da.Update(ds.Tables[0]);
                        cn.Close();
                        da.Dispose();

                        return(true);
                    }
                }
                catch (SqlException ex)
                {
                    return(false);
                }
                catch (Exception e)
                {
                    return(false);
                }
                finally
                {
                    cn.Close();
                }
            }
        }
Exemplo n.º 12
0
        public ServiceResponseDTO <CurrentUserDTO> Put([FromBody] UpdatePasswordDTO updatePwdDto)
        {
            var response = new ServiceResponseDTO <CurrentUserDTO>();

            try
            {
                response = _authenticationSvc.Authenticate(updatePwdDto.UserName, updatePwdDto.CurrentPassword);
                if (response.Success)
                {
                    _userService.UpdateUserPassword(updatePwdDto.UserName, updatePwdDto.NewPassword);
                }
            }
            catch (Exception e)
            {
                response.Success = false;
                response.Errors.Add(e.Message);
            }
            return(response);
        }
Exemplo n.º 13
0
        public IActionResult updatePassword(UpdatePasswordDTO user)
        {
            string accessToken = Request.Headers["Authorization"];

            user.accessToken = accessToken;
            try
            {
                _accountService.updatePassword(user);
                return(Ok());
            }
            catch (InvalidParametersException e) {
                return(BadRequest(e.Message));
            }
            catch (AppObjectNotFoundException e) {
                return(NotFound(e.Message));
            }
            catch (AppValidationException) {
                return(Unauthorized());
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Asynchronously update the <see cref="User" /> password in the system.
 /// </summary>
 /// <param name="userName">Name of the user.</param>
 /// <param name="recoveryParams">The recovery parameters.</param>
 /// <returns>True if <see cref="User" /> password is updated, false otherwise.</returns>
 public virtual async Task <bool> UpdatePasswordAsync(string userName, UpdatePasswordDTO recoveryParams)
 {
     try
     {
         using (IBaasicClient client = BaasicClientFactory.Create(Configuration))
         {
             return(await client.PutAsync <UpdatePasswordDTO, bool>(client.GetApiUrl(String.Format("{0}/{1}/change-password", ModuleRelativePath, userName)), recoveryParams));
         }
     }
     catch (BaasicClientException ex)
     {
         if (ex.ErrorCode == (int)HttpStatusCode.NotFound)
         {
             return(false);
         }
         throw;
     }
     catch (Exception)
     {
         throw;
     }
 }
Exemplo n.º 15
0
        // Updates the password of an existing user
        public void updatePassword(UpdatePasswordDTO updatePass)
        {
            if (updatePass.username == null || updatePass.username == "")
            {
                throw new InvalidParametersException("username needs to be defined");
            }
            User currentUser = _accountMapper.findUserByUsername(updatePass.username);

            if (currentUser == null)
            {
                throw new AppObjectNotFoundException("No user found with this username");
            }
            if (!_tokenService.validateUserToken(updatePass.accessToken, currentUser.id))
            {
                throw new AppValidationException("Your session has expired please log back in");
            }
            if (updatePass.newPassword == null || updatePass.newPassword == "")
            {
                throw new InvalidParametersException("newPassword parameter can not be empty");
            }
            _accountMapper.updateUserPassword(updatePass.username, updatePass.newPassword);
            return;
        }
        public async Task <PassChangeStatus> UpdateStudentPassword(int id, UpdatePasswordDTO passwordDTO)
        {
            StudentDTO student
                = await _studentService.GetSingleOrDefault(s => s.StudentId == id);

            bool verifyPass = VerifyOldPassword(
                passwordDTO.OldPassword,
                student.Salt,
                student.PasswordHash);

            if (!verifyPass)
            {
                return(PassChangeStatus.InvalidOldPass);
            }
            else if (passwordDTO.NewPassword != passwordDTO.ConfirmPassword)
            {
                return(PassChangeStatus.PassNoMatch);
            }

            byte[] salt       = Security.GenerateRandomBytes(Constants.SALT_SIZE);
            string saltBase64 = Convert.ToBase64String(salt);

            student.Salt         = saltBase64;
            student.PasswordHash = Security.CreateHash(
                passwordDTO.NewPassword,
                salt,
                Constants.PASSWORD_HASH_SIZE);

            ResultMessage <StudentDTO> updatedStudent = await _studentService.Update(student);

            if (!updatedStudent.IsSuccess)
            {
                return(PassChangeStatus.Error);
            }
            return(PassChangeStatus.Success);
        }
Exemplo n.º 17
0
        public IActionResult UpdatePassword(UpdatePasswordDTO data)
        {
            var User = _AuthRepository.UpdatePassword(data);

            return(User != false?Ok() : NotFound());
        }
Exemplo n.º 18
0
        public ServiceResponse <bool> UpdatePassword([FromBody] UpdatePasswordDTO request)
        {
            var claims = GetUserClaims();

            return(_userService.UpdatePassword(request.Password, claims.UserId));
        }