Exemplo n.º 1
0
        public void SavePassword(ChangePasswordData data)
        {
            Account account = db.Accounts.FirstOrDefault(x => x.Login.Equals(data.Login, StringComparison.OrdinalIgnoreCase));

            if (account == null)
            {
                es.ThrowInfoException("Account to change password does not exist");
            }
            if (account.Locked)
            {
                es.ThrowInfoException("Account {0} is locked", account.Login);
            }

            LoginData loginData = new LoginData()
            {
                Login = data.Login, Password = data.OldPassword
            };

            if (!AccountValid(loginData))
            {
                es.ThrowInfoException("Old password is not valid");
            }

            UpdatePassword(data);
        }
Exemplo n.º 2
0
        public IActionResult EditPassword(string id, [FromBody] ChangePasswordData data)
        {
            string password;

            if (data.NewPassword == "" || data.NewPassword == null)
            {
                return(BadRequest("Password can't be empty or null"));
            }
            try
            {
                if (_context.GetOne(id).Password == CreateHash(data.Password))
                {
                    password = CreateHash(data.NewPassword);
                    _context.EditPassword(id, password);
                    return(Ok());
                }
                else
                {
                    return(BadRequest("Wrong Password"));
                }
            }
            catch (Exception exe)
            {
                return(BadRequest(exe.Message));
            }
        }
Exemplo n.º 3
0
    public IActionResult ChangePassword([FromBody] ChangePasswordData change_password_data)
    {
        var item          = _context.Admin.FirstOrDefault(t => t.Username == change_password_data.Username);
        var session       = HttpContext.Get <LoggableEntities>(_context);
        var current_User  = session == null ? null : session.User;
        var current_Admin = session == null ? null : session.Admin;

        if (item != null &&
            change_password_data.Username != null && change_password_data.Password != null &&
            change_password_data.NewPassword != null && change_password_data.NewPasswordConfirmation != null)
        {
            var allowed_items = ApiTokenValid ? _context.Admin : _context.Admin;
            if (!allowed_items.Any(i => i.Id == item.Id))
            {
                return(Unauthorized());
            }
            if (change_password_data.NewPassword == change_password_data.NewPasswordConfirmation && PasswordHasher.CheckHash(change_password_data.Password, new PasswordAndSalt()
            {
                PasswordHash = item.PasswordHash, PasswordSalt = item.PasswordSalt
            }))
            {
                var new_password = PasswordHasher.Hash(change_password_data.NewPassword);
                item.PasswordHash = new_password.PasswordHash;
                item.PasswordSalt = new_password.PasswordSalt;
                _context.Admin.Update(item);
                _context.SaveChanges();

                HttpContext.ChangedPassword <Admin>(_context, "Admin", item);
                // HttpContext.Login<LoggableEntities, Admin>(_context, "Admin", item, new LoggableEntities() { Admin = item });

                return(Ok());
            }
        }
        return(Unauthorized());
    }
        public async Task <ActionResult <UserUpdateResponseData> > ChangePassword([FromBody] ChangePasswordData model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userId         = this.User.Claims.FirstOrDefault().Value;
            var targetUser     = mapper.Map <User>(model);
            var changePassword = mapper.Map <ChangePassword>(model);

            try
            {
                await authService.CheckIfUserIsLoggedIn(userId);

                var result = await userManagementService.ChangeUserPassword(targetUser, userId, changePassword);

                return(new UserUpdateResponseData()
                {
                    UpdatedUserId = result
                });
            }
            catch (Exception e)
            {
                return(BadRequest(new { error = e.Message }));
            }
        }
Exemplo n.º 5
0
        private bool CheckPassword(ChangePasswordData cd, tKlient client)
        {
            List <String> errorList = new List <String>(2);
            var           res       = WebDataHelper.CheckPasswords(cd.OldPassword, cd.NewPassword, cd.NewPassword2, client, errorList);

            errorList.ForEach(e => ModelState.AddModelError("", e));
            return(res);
        }
Exemplo n.º 6
0
        public WebResult ChangePassword([FromBody] ChangePasswordData data)
        {
            var sUid   = HttpContext?.Session.GetInt32("uid");
            var result = false;

            if (sUid == data.Uid)
            {
                result = _userDao.ChangePassword(data.Uid, data.OldP, data.NewP);
            }
            return(new WebResult(result ? 0 : 1));
        }
Exemplo n.º 7
0
        public async Task <ActionResult> UpdateUserPassword([FromBody] ChangePasswordData passwordData, [FromRoute] int id)
        {
            var updateUserResult = await userService.ChangePassword(passwordData, id);

            if (!updateUserResult.IsSuccessful)
            {
                return(BadRequest(updateUserResult));
            }

            return(Ok(updateUserResult));
        }
Exemplo n.º 8
0
 public IActionResult ChangePassword([FromBody] ChangePasswordData data)
 {
     service.CurrentUser = CurrentUser;
     if (service.ChangePassword(data))
     {
         return(Ok());
     }
     else
     {
         return(Unauthorized());
     }
 }
Exemplo n.º 9
0
        public bool ChangePassword(ChangePasswordData data, Guid token)
        {
            var user = db.Session.Include(x => x.PortalUser).First(x => x.SessionKey == token);

            if (!user.PortalUser.Password.Equals(Utils.GetMD5(data.OldPassword), StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }
            user.PortalUser.Password = Utils.GetMD5(data.NewPassword);
            db.SaveChanges();
            return(true);
        }
        public async Task <IHttpActionResult> ChangePassword(ChangePasswordData data)
        {
            var result = await AppUserManager.ChangePasswordAsync(Guid.Parse(User.Identity.GetUserId()), data.OldPassword, data.NewPassword);

            if (result.Succeeded)
            {
                Logger.ServiceLog.Info("Пользователь успешно изменил пароль к аккаунту.");
                return(Ok());
            }

            Logger.ServiceLog.Warn("Пользователь не сменил пароль.");
            return(GetErrorResult(result));
        }
        public IHttpActionResult UpdatePassword(ChangePasswordData passwordData)
        {
            try
            {
                var isUpdate = _accountService.ChangePassword(passwordData);

                return(Ok(isUpdate));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemplo n.º 12
0
        public bool ChangePassword(ChangePasswordData data)
        {
            var passwordHasher     = new PasswordHasher <User>();
            var verificationResult = passwordHasher.VerifyHashedPassword(CurrentUser, CurrentUser.PasswordHash, data.OldPassword);

            if (verificationResult == PasswordVerificationResult.Failed)
            {
                return(false);
            }
            CurrentUser.PasswordHash = passwordHasher.HashPassword(CurrentUser, data.NewPassword);
            dbContext.Update(CurrentUser);
            dbContext.SaveChanges();
            return(true);
        }
Exemplo n.º 13
0
        public async Task <IActionResult> ChangePassword(
            [FromRoute] Guid id,
            [FromBody] ChangePasswordData data,
            [FromServices] IHttpContextAccessor httpContextAccessor,
            [FromServices] IUserRepository userRepository
            )
        {
            if (data == null)
            {
                return(BadRequest(nameof(data)));
            }
            if (string.IsNullOrEmpty(data.OldPassword))
            {
                return(BadRequest(nameof(data.OldPassword)));
            }
            if (string.IsNullOrEmpty(data.NewPassword))
            {
                return(BadRequest(nameof(data.NewPassword)));
            }

            var authenticatedUser = httpContextAccessor.GetAuthenticatedUser(userRepository);

            if (id != authenticatedUser.Id)
            {
                return(Conflict(new Exception("The given identifier mismatch the authenticated user")));
            }

            try
            {
                await repo.ChangePassword(id, data);

                await repo.SaveChangesAsync();
            }
            catch (MissingArgumentsException missingArgumentsException)
            {
                return(BadRequest(missingArgumentsException));
            }
            catch (NotFoundException notFoundException)
            {
                return(NotFound(notFoundException));
            }
            catch (Exception exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, exception));
            }

            return(NoContent());
        }
Exemplo n.º 14
0
 public void UpdatePassword(ChangePasswordData data)
 {
     using (SqlConnection connection = new SqlConnection(op.Value.Data.LinksConnection.ConnectionString))
     {
         string sql = "spUpdatePassword";
         using (SqlCommand command = new SqlCommand(sql, connection))
         {
             command.CommandType = CommandType.StoredProcedure;
             command.Parameters.AddWithValue("@Login", data.Login);
             command.Parameters.AddWithValue("@OldPassword", data.OldPassword);
             command.Parameters.AddWithValue("@NewPassword", data.NewPassword);
             connection.Open();
             command.ExecuteNonQuery();
         }
     }
 }
Exemplo n.º 15
0
        public bool ChangePassword(ChangePasswordData passwordData)
        {
            var account = _accountRepository.FirstOrDefault(x => x.Id == passwordData.AccountId);

            if (account != null && GetPasswordHash(passwordData.OldPassword) == account.Password)
            {
                if (passwordData.NewPassword == passwordData.OldPassword)
                {
                    throw new Exception("Cannot use old password!");
                }

                var password = GetPasswordHash(passwordData.NewPassword);
                return(_accountRepository.ChangePassword(passwordData.AccountId, password));
            }

            return(false);
        }
Exemplo n.º 16
0
        public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordData data)
        {
            if (data == null)
            {
                _logger.LogError("Tried to change password with data = null.");
                return(BadRequest("You must provide both old and new password."));
            }

            if (string.IsNullOrEmpty(data.OldPassword))
            {
                _logger.LogError("Tried to change password with old password set to null.");
                return(BadRequest("Cannot change password with old password set to null."));
            }

            if (string.IsNullOrEmpty(data.NewPassword))
            {
                _logger.LogError("Tried to change password with new password set to null.");
                return(BadRequest("Cannot change password with new password set to null."));
            }

            var currentUser = await _userRepository.FindByUserName(User.Identity.Name);

            if (!currentUser.VerifyPassword(data.OldPassword))
            {
                _logger.LogTrace($"Cannot change password: User '{User.Identity.Name}' provided incorrect old password.");
                return(BadRequest("Old password is incorrect"));
            }

            currentUser.DecryptUserSecret(data.OldPassword);

            var userSecret = currentUser.UserSecret;

            currentUser.DecryptData(userSecret);

            currentUser.SetPassword(data.NewPassword);

            currentUser.EncryptData(userSecret);

            await _userRepository.Update(currentUser);

            return(NoContent());
        }
Exemplo n.º 17
0
 public ActionResult ChangePassword(ChangePasswordData data)
 {
     if (!data.Equals(null))
     {
         var cookie     = Request.Cookies[FormsAuthentication.FormsCookieName];
         var ticketInfo = FormsAuthentication.Decrypt(cookie.Value);
         if (IsPasswordValid(ticketInfo.UserData, data.OldPassword))
         {
             User UpdateUser = userRepository.GetUserByUserName(ticketInfo.UserData);
             UpdateUser.Password = data.NewPassword;
             userRepository.SaveUser(UpdateUser); // update user password
             return(Json(new { result = "success", message = "Your password was changed successfuly" }));
         }
         else
         {
             return(Json(new { result = "Invalid old password", message = "Wrong old password!" }));
         }
     }
     return(Json(new { result = "JSON IS NULL" }));
 }
        public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordData data)
        {
            string token = this.GetToken();

            if (!db.IsAuthenticated(token))
            {
                return(Unauthorized());
            }

            if (db.ChangePassword(data, Guid.Parse(token)))
            {
                this.SaveUserAction(this.GetUserAction("Смяна парола", ""));

                return(Ok());
            }
            else
            {
                return(Unauthorized());
            }
        }
Exemplo n.º 19
0
        public IActionResult SavePassword([FromBody] ChangePasswordData data)
        {
            return(es.Execute(() =>
            {
                if (data == null || !data.Valid())
                {
                    es.ThrowInfoException("No data to change password");
                }

                if (string.Equals(data.OldPassword, data.NewPassword))
                {
                    es.ThrowInfoException("Passwords are the same");
                }

                if (!accountService.Login.Equals(data.Login, StringComparison.OrdinalIgnoreCase))
                {
                    es.ThrowInfoException("Account to save does not match logged in account;");
                }

                accountService.SavePassword(data);
                return new JsonResult(new GenericResult());
            }, true));
        }
    public IActionResult ChangePassword([FromBody] ChangePasswordData change_password_data)
    {
        if (ModelState.IsValid == false || change_password_data.NewPassword != change_password_data.NewPasswordConfirmation)
        {
            return(BadRequest());
        }

        var currentSessionId = HttpContext.Get <Session>(_context).Id;
        var session          = HttpContext.Get <LoggableEntities>(_context);
        var current_Admin    = session == null ? null : session.Admin;

        if (current_Admin != null)
        {
            var admin = _context.Admin.FirstOrDefault(u => u.Id == current_Admin.Id);

            if (!PasswordHasher.CheckHash(change_password_data.Password, new PasswordAndSalt()
            {
                PasswordHash = admin.PasswordHash, PasswordSalt = admin.PasswordSalt
            }))
            {
                return(Unauthorized());
            }

            var hassedPassword = PasswordHasher.Hash(change_password_data.NewPassword);

            admin.PasswordHash = hassedPassword.PasswordHash;
            admin.PasswordSalt = hassedPassword.PasswordSalt;

            _context.Admin.Update(admin);
            _context.SaveChanges();

            return(Ok());
        }


        return(Unauthorized());
    }
Exemplo n.º 21
0
        public async Task ChangePassword(System.Guid userId, ChangePasswordData data)
        {
            if (data == null)
            {
                throw new MissingArgumentsException(nameof(data));
            }
            if (string.IsNullOrEmpty(data.OldPassword))
            {
                throw new MissingArgumentsException(data.OldPassword);
            }
            if (string.IsNullOrEmpty(data.NewPassword))
            {
                throw new MissingArgumentsException(data.NewPassword);
            }

            var user = await _db.User.FirstOrDefaultAsync(x => x.Id == userId && x.Password == data.OldPassword);

            if (user == null)
            {
                throw new NotFoundException(typeof(User));
            }

            user.SetPassword(data.NewPassword);
        }
Exemplo n.º 22
0
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task <OutputDto> ChangePasswordAsync(ChangePasswordData data)
        {
            Guid userId;

            if (!Guid.TryParse(data.UserId, out userId))
            {
                throw new OneZeroException("修改密码失败:传入的用户ID格式错误", ResponseCode.ExpectedException);
            }

            var user = await _userRepository.Entities.Where(v => v.Id.Equals(userId)).FirstOrDefaultAsync();

            if (user != null && !string.IsNullOrWhiteSpace(data.NewPasswordData) && data.NewPasswordData != data.OldPasswordData && user.PasswordHash == data.OldPasswordData.MD5Hash())
            {
                user.PasswordHash = data.NewPasswordData.MD5Hash();
                await _userRepository.UpdateAsync(user);

                output.Message = "修改成功";
            }
            else
            {
                output.Message = "修改失败:请保证新密码正确有效,且不与旧密码一样";
            }
            return(output);
        }
Exemplo n.º 23
0
 public ActionResult UpdateEmailPassword(ChangePasswordData model)
 {
     _settingsService.UpdateEmailPassword(model.EmailPassword);
     return(Json(ResultModel.Success));
 }
Exemplo n.º 24
0
        public async Task <GenericResponse> ChangePassword(ChangePasswordData changePasswordData, int id)
        {
            if (changePasswordData == null)
            {
                return(new GenericResponse(false, UserResponseMessage.UserDataNotProvided));
            }

            if (string.IsNullOrEmpty(changePasswordData.NewPassword) || string.IsNullOrEmpty(changePasswordData.NewPasswordAgain))
            {
                return(new GenericResponse(false, UserResponseMessage.NewPasswordNotProvided));
            }

            if (changePasswordData.NewPassword != changePasswordData.NewPasswordAgain)
            {
                return(new GenericResponse(false, UserResponseMessage.NewPasswordsNotIdentical));
            }

            var userToUpdatePassword = await unitOfWork.UserRepository.GetUserByIdAsync(id);

            if (userToUpdatePassword == null)
            {
                return(new GenericResponse(false, UserResponseMessage.UserWithGivenIdNotExists));
            }

            var oldPasswordHashed = new HashPassword(changePasswordData.OldPassword, userToUpdatePassword.Login);

            if (userToUpdatePassword.Password != oldPasswordHashed.HashedPassword)
            {
                return(new GenericResponse(false, UserResponseMessage.IncorrectOldPassword));
            }

            HashPassword hash = new HashPassword(changePasswordData.NewPassword, userToUpdatePassword.Login);

            if (userToUpdatePassword.Password == hash.HashedPassword)
            {
                return(new GenericResponse(false, UserResponseMessage.NewPasswordHasToBeDifferent));
            }

            bool isPasswordSecure = IsPasswordSecure(changePasswordData.NewPassword, userToUpdatePassword.FirstName, userToUpdatePassword.LastName, userToUpdatePassword.Login);

            if (!isPasswordSecure)
            {
                return(new GenericResponse(false, UserResponseMessage.NotSafePassword));
            }

            hash = new HashPassword(changePasswordData.NewPassword, userToUpdatePassword.Login);
            userToUpdatePassword.Password = hash.HashedPassword;
            try
            {
                await unitOfWork.UserRepository.UpdateUser(userToUpdatePassword);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(new GenericResponse(false, ex.InnerException.Message));
            }
            catch (DbUpdateException ex)
            {
                return(new GenericResponse(false, ex.InnerException.Message));
            }
            return(new GenericResponse(true, UserResponseMessage.PasswordChanged));
        }
Exemplo n.º 25
0
 public async Task ChangePasswordAsync(ChangePasswordData data)
 {
     Validate.NotNull(data, "Change password data");
     // TODO: Add email notification about password change
     throw new NotImplementedException();
 }