示例#1
0
        public async Task <ApiResult <bool> > UpdatePassword(UserUpdatePassword bundle)
        {
            var user = await _userManager.FindByNameAsync(bundle.Name);

            if (user == null)
            {
                return(new ApiErrorResult <bool>("Tài khoản không tồn tại"));
            }

            var result = await _signInManager.PasswordSignInAsync(user, bundle.OldPassword, false, true);

            if (!result.Succeeded)
            {
                return(new ApiErrorResult <bool>("Nhập mật khẩu sai"));
            }

            var token = await _userManager.GeneratePasswordResetTokenAsync(user);

            var update = await _userManager.ResetPasswordAsync(user, token, bundle.ConfirmPassword);

            if (update.Succeeded)
            {
                return(new ApiSuccessResult <bool>());
            }
            return(new ApiErrorResult <bool>("Mật khẩu phải có ít nhất ký tự đặc biệt và chữ hoa"));
        }
        public async Task <int> UpdatePassword(UserUpdatePassword model)
        {
            var currentUser = await _userStoreExtend.FindByIdAsync(model.Id);

            if (currentUser != null)
            {
                var result = new IdentityResult();
                if (model.OldPassword == null)
                {
                    var code = await _userManager.GeneratePasswordResetTokenAsync(currentUser);

                    result = await _userManager.ResetPasswordAsync(currentUser, code, model.NewPassword);
                }
                else
                {
                    result = await _userManager.ChangePasswordAsync(currentUser, model.OldPassword, model.NewPassword);
                }
                if (result.Succeeded)
                {
                    return(1);
                }
                else
                {
                    return(0);
                }
            }
            return(0);
        }
        public void CanUserChangePasswordTest()
        {
            IUserDAO <User> UserDAO  = new UserDAO(_connection);
            User            testUser = new User();

            testUser.Email     = "*****@*****.**";
            testUser.Password  = "******";
            testUser.FirstName = "Samuel";
            testUser.LastName  = "Cunha";
            testUser.Image     = "ImageLocation";
            Address adr = new Address();

            adr.PostalCode        = "4615-423";
            adr.Street            = "Rua de Real";
            adr.StreetNumber      = 55;
            adr.District          = "Porto";
            adr.Country           = "Portugal";
            testUser.Localization = adr.ToString();

            User returnedUser = UserDAO.Create(testUser);

            UserUpdatePassword newPass = new UserUpdatePassword();

            newPass.ActualPassword = "******";
            newPass.NewPassword    = "******";

            Assert.True(UserDAO.UpdatePassword(newPass, returnedUser.Id));
        }
示例#4
0
 /// <summary>
 /// 修改个人密码
 /// </summary>
 /// <param name="userId"></param>
 /// <returns></returns>
 public int UpdateUserPassword(UserUpdatePassword user)
 {
     using (IDbConnection conn = new SqlConnection(connStr))
     {
         string sql = "UPDATE dbo.UserInfo SET UserPassword=@userpassword WHERE UserId =@userid";
         var    res = conn.Execute(sql, new { userpassword = user.UserPassword, userid = user.UserId });
         return(res);
     }
 }
示例#5
0
        public bool UpdatePasswordValid(UserUpdatePassword model)
        {
            var user = List.FirstOrDefault(x => x.Username == model.Username && x.Password == model.Password);

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

            return(false);
        }
        public async Task <IActionResult> AlterarSenha()
        {
            var user = await _service.GetByName(User.Identity.Name);

            var userUpdatePassword = new UserUpdatePassword();

            userUpdatePassword.Id       = user.Id;
            userUpdatePassword.Username = user.Username;

            return(View(userUpdatePassword));
        }
示例#7
0
 /// <summary>
 /// 更新用户密码
 /// </summary>
 /// <param name="param"></param>
 /// <returns></returns>
 protected Result <String> UpdateUserPassword(UserUpdatePassword param)
 {
     if (IsAuthrized)
     {
         if (UserService.UpdatePassword(param.user_id, param.password))
         {
             return(Result <String> .CreateInstance(ResultCode.Success, "修改密码成功"));
         }
         else
         {
             return(Result <String> .CreateInstance(ResultCode.Fail, "修改密码失败"));
         }
     }
     return(GetAuthFilterResult <String>());
 }
示例#8
0
        public async Task <IActionResult> Update([FromBody] UserUpdatePassword request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = await _userService.UpdatePassword(request);

            if (!result.IsSuccessed)
            {
                return(BadRequest(result));
            }
            return(Ok(result));
        }
        public async Task <UserResult> UpdatePassword(UserUpdatePassword userUpdatePassword)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _userAuth.GetToken());

                StringContent conteudo = new StringContent(JsonConvert.SerializeObject(userUpdatePassword), Encoding.UTF8, "application/json");

                using (var response = await httpClient.PostAsync($"{baseUrl}/UpdatePassword", conteudo))
                {
                    string apiResponse = await response.Content.ReadAsStringAsync();

                    var result = JsonConvert.DeserializeObject <UserResult>(apiResponse);
                    return(result);
                }
            }
        }
        public async Task <IActionResult> AlterarSenha(UserUpdatePassword user)
        {
            if (!ModelState.IsValid)
            {
                return(View(user));
            }

            UserResult result = await _service.UpdatePassword(user);

            if (result.Success == false)
            {
                ModelState.AddModelError(string.Empty, result.Message);
                return(View(user));
            }

            TempDataUtil.Put(TempData, "mensagem", result.Message);
            return(RedirectToAction("Index", "HomeInternal"));
        }
示例#11
0
        public async Task <IActionResult> AlterarSenha(UserUpdatePassword user)
        {
            if (!ModelState.IsValid)
            {
                return(View(user));
            }

            UserResult result = await _service.UpdatePassword(user);

            if (result.Success == false)
            {
                var notifications = Agrupar.GroupNotifications(result);
                ModelState.AddModelError(string.Empty, notifications);
                return(View(user));
            }

            return(View("Mensagem"));
        }
示例#12
0
        public IActionResult UpdatePassword(UserUpdatePassword passwordUpdateModel)
        {
            try
            {
                int?id = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity);

                if (id == null)
                {
                    return(Unauthorized(new ErrorExceptionModel("Sem Autorização ou sem sessão inciada")));
                }

                UserDAO userDAO = new UserDAO(_connection);
                bool    newPass = userDAO.UpdatePassword(passwordUpdateModel, id);
                return(Ok(new SuccessExceptionModel("Password alterada com sucesso!")));
            }
            catch (Exception ex)
            {
                return(BadRequest(new ErrorExceptionModel(ex.Message)));
            }
        }
        public ActionResult ChangePassword_Update(UserUpdatePassword model)
        {
            if (string.IsNullOrEmpty(model.CurrentPassword))
            {
                return JsonError("Current password is empty");
            }

            if (string.IsNullOrEmpty(model.NewPassword))
            {
                return JsonError("New password is empty");
            }

            if (string.IsNullOrEmpty(model.NewPassword))
            {
                return JsonError("New password (x2) is empty");
            }

            var user = User_GetByID(AuthenticatedUserID);

            // check old password
            var PasswordHasher = new SaltedHash();
            if (PasswordHasher.VerifyHashString(model.CurrentPassword, user.PasswordHash, user.Salt))
            {
                if (model.NewPassword == model.NewPassword2)
                {
                    var p = PasswordGenerate(model.NewPassword);
                    user.PasswordHash = p.Id;
                    user.Salt = p.Name;
                    Db.Update<ABUserAuth>(user);
                }
                else
                {
                    return JsonError("New password is not same");
                }
            }
            else
            {
                return JsonError("Current password is not correct");
            }
            return JsonSuccess("", "Password updated");
        }
        public async Task <UserResult> UpdatePassword(UserUpdatePassword userUpdatePassword)
        {
            if (!_repository.UpdatePasswordValid(userUpdatePassword))
            {
                return new UserResult()
                       {
                           Success = false, Message = "Senha antiga não confere ", Object = null
                       }
            }
            ;

            User user = new User();

            user.Username = userUpdatePassword.Username;
            user.Id       = userUpdatePassword.Id;
            user.Password = userUpdatePassword.Password;

            _repository.UpdatePassword(userUpdatePassword.NewPassword, user);
            return(new UserResult()
            {
                Success = true, Message = "Senha atualizada com sucesso! ", Object = user
            });
        }
示例#15
0
        /// <summary>
        /// Método que atualiza a password
        /// de um determindado utilizador
        /// </summary>
        /// <param name="newPass">Nova palavra-passe</param>
        /// <param name="id">Id do utilizador que pretende alterar
        /// a sua palavra-passe</param>
        /// <returns>
        /// True caso a password seja atualizada com sucesso
        /// False caso contrário
        /// </returns>
        public bool UpdatePassword(UserUpdatePassword newPass, int?id)
        {
            User user = FindById((int)id);

            if (user == null)
            {
                throw new Exception("O utilizador não existe!");
            }

            if (PasswordEncrypt.VerifyHash(newPass.ActualPassword, user.Password, user.PasswordSalt))
            {
                using (SqlCommand cmd = _connection.Fetch().CreateCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "UPDATE dbo.[User] " +
                                      "SET Password = @pass, PasswordSalt = @salt " +
                                      "WHERE Id = @id";

                    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;

                    var password = PasswordEncrypt.Encrypt(newPass.NewPassword);
                    cmd.Parameters.Add("@pass", SqlDbType.NVarChar).Value = password.Item2;
                    cmd.Parameters.Add("@salt", SqlDbType.NVarChar).Value = password.Item1;

                    if (cmd.ExecuteNonQuery() == 0)
                    {
                        return(false);
                    }
                }

                return(true);
            }
            else
            {
                throw new Exception("A password antiga é inválida!");
            }
        }
示例#16
0
        public async Task <ApiResult <bool> > UpdatePassword(UserUpdatePassword bundle)
        {
            var client = _httpClientFactory.CreateClient();

            client.BaseAddress = new Uri(_configuration["BaseAddress"]);

            var sessions = _httpContextAccessor.HttpContext.Session.GetString("Token");

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sessions);

            var json        = JsonConvert.SerializeObject(bundle);
            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await client.PutAsync($"/api/user/change-password", httpContent);

            var result = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                return(JsonConvert.DeserializeObject <ApiSuccessResult <bool> >(result));
            }

            return(JsonConvert.DeserializeObject <ApiErrorResult <bool> >(result));
        }
示例#17
0
        public ActionResult <OperateResult <Auth_User> > UpdatePwd([FromBody] UserUpdatePassword param)
        {
            var userId = new Guid(User.Identity.Name);

            return(Json(_service.UpdatePassword(param, userId)));
        }
示例#18
0
 public Result <String> UpdatePassword(UserUpdatePassword param)
 {
     return(base.UpdateUserPassword(param));
 }
示例#19
0
        public async Task <IActionResult> UpdatePassword(UserUpdatePassword bundle)
        {
            var result = await _userApiClient.UpdatePassword(bundle);

            return(Ok(result));
        }
示例#20
0
 public object Put(UserUpdatePassword user)
 {
     return UserService.UpdateUserPassword(user.Id, user.OldPassword, user.NewPassword);
 }
示例#21
0
 public UserUpdatePasswordCommand(string username, UserUpdatePassword data, User user) : base(username, user)
 {
     UpdatePassword = data;
 }