public static void DeletePassword(PasswordModel password) { using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString())) { cnn.Execute("DELETE FROM Password WHERE PasswordId = @PasswordId", password); } }
public ActionResult ResetPassword(string UserId) { PasswordModel ResetPasswordModel = new PasswordModel(); ResetPasswordModel.UserId = UserId; return(View(ResetPasswordModel)); }
public void Init() { UserModel user = new UserModel("Patrick", "1234"); passwordWithoutWebsite = new PasswordModel("Facebook", "12345", user); passwordWithWebsite = new PasswordModel("Facebook", "12345", user, "https://facebook.com"); }
public ActionResult Create(PasswordModel password) { try { userInfo = GetUserInfo(); UserModel user; user = dbContext.GetUserById(userInfo.Id); password.IdUser = userInfo.Id; password.PasswordHash = EncryptionHelper.EncryptPasswordAES(password.PasswordHash, userInfo.LoggedUserPassword); CreatePassword(password); PasswordChange.LogPasswordCreate( dbContext.GetPasswordByHash(password.PasswordHash), dbContext); ActivityLog.Log(userInfo.Id, ActionType.CreatePassword, dbContext); return(RedirectToAction(nameof(Index), new { idUser = password.IdUser })); } catch { return(View()); } }
// GET: Passwords/Details/5 public ActionResult Details(string passwordHash) { userInfo = GetUserInfo(); PasswordModel password = dbContext.GetPasswordByHash(passwordHash); if (password != null) { password.PasswordHash = EncryptionHelper.DecryptPasswordAES(password.PasswordHash, userInfo.LoggedUserPassword); ActivityLog.Log( GetUserInfo().Id, ActionType.ViewPassword, dbContext); return(View(password)); } else { return(View( "EnterSharingKey", new SharePasswordKey() { KeyHash = passwordHash })); } }
public ActionResult ChangePass(PasswordModel model) { if (ModelState.IsValid) { if (model.NewPassword != model.RepeatPassword) { ModelState.AddModelError("", "Mật khẩu mới không trùng khớp!"); } else { var dao = new UserDao(); string userName = Session["UserName"].ToString(); var user = dao.GetByUsername(userName); var hashpass = new SaltedPassword(); int result = dao.ChangePass(userName, hashpass.EncodePassword(model.OldPassword, user.SaltPass), hashpass.EncodePassword(model.RepeatPassword, user.SaltPass)); if (result == 1) { return(RedirectToAction("Index", "Login")); } else { ModelState.AddModelError("", "Mật khẩu đăng nhập sai!"); } } } else { ModelState.AddModelError("", "Cập nhật thất bại, vui lòng liên hệ với quản trị viên!"); } return(View()); }
public ActionResult ChangePassword(PasswordModel m) { try { pPlsUsers_Result rslt = con.pPlsUsers("p", null, m.UserName, m.OldPassword, m.NewPassword, null, null, null, null, User.Identity.Name).FirstOrDefault(); if (rslt.Code == "000") { TempData["Message"] = rslt.Message; TempData["IsPopup"] = "y"; return(RedirectToAction("Index", "Users")); } else { ModelState.AddModelError("", "Error! Code[" + rslt.Code + "]: " + rslt.Message); } } catch { ModelState.AddModelError("", "Techinical Error Occurred While Processing Your Request"); } return(View(m)); }
public HttpResponseMessage ForgotPassword([FromBody] PasswordModel changePassword) { try { //if (Mail.networkIsAvailable()) //{ string username = changePassword.Username; User user = UserPL.RetrieveUserByUsername(username); if (user != null) { Mail.SendForgotPasswordMail(user); return(Request.CreateResponse(HttpStatusCode.OK, user.Email)); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid username")); } //} //else //{ //return Request.CreateResponse(HttpStatusCode.BadRequest, "Kindly ensure that internet connection is available in order to reset your password."); //} } catch (Exception ex) { ErrorHandler.WriteError(ex); var response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); return(response); } }
public HttpResponseMessage ConfirmUsername([FromBody] PasswordModel changePassword) { try { string key = System.Configuration.ConfigurationManager.AppSettings.Get("ekey"); string username = Crypter.Decrypt(key, changePassword.Username); User user = UserPL.RetrieveUserByUsername(username); if (user != null) { //Add a mail for password reset object response = new { Status = "Successful", Username = user.Username }; return(Request.CreateResponse(HttpStatusCode.OK, response)); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid username")); } } catch (Exception ex) { ErrorHandler.WriteError(ex); var response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); return(response); } }
public virtual ActionResult Check([Bind(Include = "Name,Code")] PasswordModel model) { if(model==null) return RedirectToAction("Index"); if (!CodeHelper.ValidateCode(model.Code, "PasswordCode")) { model.Errors = model.Errors ?? new List<ErrorInfo> { new ErrorInfo { Key = "CodeError", Message = "验证码错误" } }; } else { var account =GetPasswordApplicationService().CheckAccount(model.Name); if (account == null) { model.Errors = model.Errors ?? new List<ErrorInfo> { new ErrorInfo { Key = "AccountNoExist", Message = "账户不存在" } }; } else { HidePartEntity(model, account); } } if (model.Errors != null && model.Errors.Count > 0) return View("Index", model); model.Step = 2; return View("Check", model); }
public bool?ResetPassword(PasswordModel model) { try { var user = _repo.GetActive().Where(p => p.Email == model.Email).FirstOrDefault(); if (user == null) { return(null); } var token = _aspNetUserTokensRepo.Get().Where(p => p.UserId == user.Id && p.Name == user.Name && p.Value == model.Token).FirstOrDefault(); if (token == null) { return(false); } UniLogUtil utils = new UniLogUtil(); user.PasswordHash = utils.GetMd5HashData(model.NewPassword); _repo.Update(user); _repo.SaveChanges(); return(true); } catch (Exception) { throw; } }
private PasswordModel HashPassword(string password, byte[] salt = null) { var model = new PasswordModel(); // generate a 128-bit salt using a secure PRNG if (salt == null) { salt = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); } } model.Salt = Convert.ToBase64String(salt); model.Hash = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: salt, // TODO Use argon2 when available prf: KeyDerivationPrf.HMACSHA512, iterationCount: 10000, numBytesRequested: 256 / 8)); return(model); }
public void ExecuteSave(object o) { // User needs to input all fields if (String.IsNullOrEmpty(Name) || String.IsNullOrEmpty(Website) || String.IsNullOrEmpty(Username) || String.IsNullOrEmpty(Password)) { return; } byte[] masterKey = CryptoUtil.MasterKey; byte[] passwordBytes = ASCIIEncoding.ASCII.GetBytes(this.Password); // Convert the encrypted password to a base64 string for storage string passwordToStore = Convert.ToBase64String(CryptoUtil.AES_GCMEncrypt(passwordBytes, masterKey)); // TODO: Check if password contains non-base64 chars PasswordModel newPassword = new PasswordModel() { Name = this.Name, Website = this.Website, Username = this.Username, Password = passwordToStore }; // Places the new PasswordModel into the database with the encrypted password SQLiteDataAccess.SavePassword(newPassword); // TODO: Place this password into a secure string // Sets password for the bindable collection to the decrypted version newPassword.Password = this.Password; VaultVM.Passwords.Add(newPassword); // After saving, goes back to the basic display view of the selected password VaultVM.PassScreenType = new DisplayPasswordViewModel(SelectedPassword, VaultVM); }
public async Task <SessionInfo> SignUpAsync(PasswordModel password) { var user = await sessionInfoProvider.GetTwitchUserAsync(HttpContext.Session); authManager.SignUp(user.Id, user.Login, user.DisplayName, user.Email, password.Password); return(await sessionInfoProvider.StoreAsync(HttpContext.Session)); }
protected PasswordScreen(PasswordModel _selectedPassword, VaultViewModel _vaultViewModel) { SelectedPassword = _selectedPassword; VaultVM = _vaultViewModel; dialogCoordinator = DialogCoordinator.Instance; }
public HttpResponseMessage AuthenticateUser([FromBody] PasswordModel passwordModel) { try { string password = PasswordHash.MD5Hash(passwordModel.Password); var userObj = UserPL.AuthenticateUser(passwordModel.Username, password); if (userObj == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Username/Password")); } else if (userObj.ID == 0) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Username/Password")); } else { return(Request.CreateResponse(HttpStatusCode.OK, userObj)); } } catch (Exception ex) { ErrorHandler.WriteError(ex); var response = Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message); return(response); } }
public void PasswordValidator_ValidateAValidPassword_PasswordShouldBeValid(int userId, string guid, DateTime generatedDate, int secondsPassed, bool expectedResult) { //Arrange var storedPasswordModel = new PasswordModel() { CreationDateTicks = generatedDate.Ticks, Guid = guid, UserId = userId }; var storedPasswordModelJson = JsonConvert.SerializeObject(storedPasswordModel); var inputPassword = EncryptAndEncodePassword(storedPasswordModelJson); var listOfStoredPasswords = new List <string>() { storedPasswordModelJson }; _passwordGuidRepositoryMock.Setup(x => x.ReadActiveGuid()).Returns(listOfStoredPasswords); var passwordValidator = new PasswordValidatorService(_passwordGuidRepositoryMock.Object); //Act var valid = passwordValidator.ValidatePassword(inputPassword, userId, generatedDate.AddSeconds(secondsPassed)); //Assert Assert.AreEqual(expectedResult, valid); }
public async Task <IActionResult> Password(PasswordModel model) { if (!ModelState.IsValid) { return(Error(ModelState.Values.SelectMany(v => v.Errors).FirstOrDefault().ErrorMessage)); } AuthenticatedUser = await GetAuthenticatedUserFromDatabaseAsync(); if (AuthenticatedUser.PasswordCheck(model.PasswordConfirmPassword)) { model.Password = model.Password.SHA512(); if (AuthenticatedUser.Password != model.Password) { AuthenticatedUser.Password = model.Password; AuthenticatedUser.LastChangedOn = DateTime.Now; await Context.SaveChangesAsync(); } return(Succes("Parolanız değiştirildi", null, 201)); } else { return(Error("Kimliğinizi doğrulayamadık: Onay parolası")); } }
public ActionResult PasswordChange(PasswordModel model) { Client Client = _clientProfileControl.GetClient((int)Session["AccountId"]); if (ModelState.IsValid) { if (!Client.DoEncyptedPassowrdsMacth(model.OldPassword)) { var errMessage = "Entered password is wrong"; ModelState.AddModelError("", errMessage); return(View(model)); } if (!model.DoPasswordsMatch()) { var errMessage = "The entered password matches the current one"; ModelState.AddModelError("", errMessage + "! Pick a new password"); return(View(model)); } model.ExcryptThePassword(); _clientProfileControl.EditPassword(Client.Id, model.NewPassword); } return(RedirectToAction("EditProfile", new { @client = Client })); }
public IActionResult changePassword(int id, [FromBody] PasswordModel password) { var accountFound = this.entityCRUD.GetAll <ManagingAccount>(x => x.Id == id).FirstOrDefault(); if (accountFound is null) { return(BadRequest(new ErrorModel { Messege = "Không tìm thấy tài khoản" })); } else { var newPassword = this.passwordService.PasswordHash(password.Password); accountFound.Password = newPassword; if (this.entityCRUD.Update <ManagingAccount, ManagingAccount>(accountFound, accountFound).Result) { return(Ok(id)); } else { return(BadRequest(new ErrorModel { Messege = "Có lỗi xảy ra vui lòng thử lại sau" })); } } }
public void PasswordFor_ComplexExpressions_IgnoresValueFromViewDataModelStateAndModel( Expression <Func <PasswordModel, string> > expression, string expected) { // Arrange var model = new PasswordModel(); var helper = DefaultTemplatesUtilities.GetHtmlHelper(model); helper.ViewData.TemplateInfo.HtmlFieldPrefix = "pre"; helper.ViewData.ModelState.SetModelValue("pre.Property3[key]", "MProp3Val", "MProp3Val"); helper.ViewData.ModelState.SetModelValue("pre.Property4.Property5", "MProp5Val", "MProp5Val"); helper.ViewData.ModelState.SetModelValue("pre.Property4.Property6[0]", "MProp6Val", "MProp6Val"); helper.ViewData["pre.Property3[key]"] = "VDProp3Val"; helper.ViewData["pre.Property4.Property5"] = "VDProp5Val"; helper.ViewData["pre.Property4.Property6"] = "VDProp6Val"; helper.ViewData.Model.Property3["key"] = "Prop3Val"; helper.ViewData.Model.Property4.Property5 = "Prop5Val"; helper.ViewData.Model.Property4.Property6.Add("Prop6Val"); // Act var result = helper.PasswordFor(expression); // Assert Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result)); }
/// <summary> /// 隐藏部分信息 /// </summary> /// <param name="model"></param> /// <param name="account"></param> protected virtual void HidePartEntity(PasswordModel model, AccountEntity account) { if (!string.IsNullOrEmpty(account.Mobile) && account.IsActiveMobile) { var builder = new StringBuilder(); if (account.Mobile.Length == 11) { builder.Append(account.Mobile.Substring(0, 3)); builder.Append("****"); builder.Append(account.Mobile.Substring(7, 4)); model.AccountMobile = builder.ToString(); } } if (!string.IsNullOrEmpty(account.Email) && account.IsActiveEmail) { var builder = new StringBuilder(); var values = account.Email.Split('@'); if (values.Length > 1) { if (values[0].Length > 2) { builder.Append(values[0].Substring(0, 2)); } for (int i = 2; i < values[0].Length; i++) { builder.Append("*"); } builder.Append("@"); builder.Append(values[1]); model.AcountEmail = builder.ToString(); } } }
public ActionResult EditPassword(PasswordModel newPass) { if (ModelState.IsValid) { try { var username = ((User)Session["currentUser"]).Username; var user = db.Users.FirstOrDefault(x => x.Username == username); var oldPasswordHash = CreateHash(user.Salt, newPass.OldPassword); if (oldPasswordHash != user.Password) { Response.Write("incorrect password!"); return(View()); } var newPasswordHash = CreateHash(user.Salt, newPass.NewPassword); user.Password = newPasswordHash; db.Entry(user).State = EntityState.Modified; db.SaveChanges(); } catch { RedirectToAction("Error", "Home"); } } return(View()); }
public virtual ActionResult CheckCode([Bind(Include = "Name,ValidateValue,ValidateType")] PasswordModel model) { if (model == null) { return(RedirectToAction("Index")); } var dto = GetPasswordApplicationService() .CheckCode(model.Name, model.ValidateValue, (CodeType)model.ValidateType); if (dto.IsTimeout) { FillTimeoutError(model); return(View("Index", model)); } if (dto.Result) { model.Step = 3; return(View("Reset", model)); } model.Errors = model.Errors ?? new List <ErrorInfo> { new ErrorInfo { Key = "ValidateValueError", Message = "验证码错误" } }; return(View("Check", model)); }
public virtual ActionResult Reset([Bind(Include = "Name,Password,SurePassword")] PasswordModel model) { if (model == null) { return(RedirectToAction("Index")); } if (model.Password != model.SurePassword) { model.Errors = model.Errors ?? new List <ErrorInfo> { new ErrorInfo { Key = "SurePasswordError", Message = "两次输入的密码不一致" } }; } else { var dto = GetPasswordApplicationService().Reset(model.Name, model.Password); if (dto.IsTimeout) { return(RedirectToAction("Index")); } if (dto.Result) { model.Step = 4; return(RedirectToAction("Finish")); } model.Errors = dto.Errors; } return(View("Reset", model)); }
public async Task <IActionResult> ChangePassword(PasswordModel model) { try { if (ModelState.IsValid) { AppUser user = await userManager.FindByNameAsync(User.Identity.Name); if (user == null) { ModelState.AddModelError("", "Your username is not found"); } else { IdentityResult result = await userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword); if (result.Succeeded) { await signInManager.SignInAsync(user, false); //prevent validate security stamp log user out return(RedirectToAction(nameof(Index))); } AddErrorFromResult(result); } } return(RedirectToAction(nameof(ChangePassword))); } catch (Exception ex) { logger.Error(ex.Message); throw; } }
public async Task ChangePassword([FromBody] PasswordModel model) { if (!ModelState.IsValid) { throw this.Exception(ModelState); } if (model.Password != model.ConfirmPassword) { throw this.Exception("密码不一致"); } var user = await _userManager.FindByNameAsync(User.Identity.Name); if (user == null) { throw this.Exception("用户不存在"); } var result = await _userService.ChangePasswordAsync(user, model.CurrentPassword, model.Password, (key, message) => { ModelState.AddModelError(key, message); }); if (!ModelState.IsValid) { throw this.Exception(ModelState); } if (!result) { throw this.Exception("操作失败"); } }
public IHttpActionResult Patch(PasswordModel model) { var entity = Manager.GetById(model.Id); if (entity == null) { return(NotFound()); } ValidatePassword(model); if (ModelState.IsValid) { entity.Password = StringHelper.GetMD5Hash(model.password); entity.Key = StringHelper.GetMD5Hash(String.Format("{0}_{1}", entity.Login, model.password)); Manager.SaveChanges(); return(Ok(model)); } else { return(BadRequest(ModelState)); } }
public ActionResult DefinePassword(PasswordModel pwd) { try { if (pwd.Password != pwd.ConfirmPassword) { ModelState.AddModelError("confirmpassword", "password do not match"); return(View()); } else { if (ModelState.IsValid) { var user = usermanager.GetUserByID(pwd.UserId); user.Password = pwd.Password; usermanager.UpdateUser(user); TempData["errormessage"] = "Password defined.Please Log in"; return(RedirectToAction("Login", "Account")); } } return(View()); } catch (Exception e) { ViewBag.message = "Unable to define password"; return(View("Error")); } }
public async Task <IActionResult> ChangePassword(PasswordModel model) { var userId = User.GetUserId(); await _loggingService.SaveAuditLog($"Updating password for user with user id {userId} process initiated.", AuditActionEnum.Update); if (!ModelState.IsValid) { return(BadRequest(ModelState.FirstError())); } var user = await _userRepository.GetUserById(userId); if (user == null) { return(BadRequest()); } var submittedCurrentPasswordIsValid = user.ValidatePassword(model.CurrentPassword); if (!submittedCurrentPasswordIsValid) { return(BadRequest("Den angivede adgangskode er forkert.")); } var encryptionModel = EncryptionHelper.EncryptWithSalt(model.NewPassword); user.Password = encryptionModel.Text; user.Salt = encryptionModel.Salt; await _userRepository.SaveChangesAsync(); return(Ok()); }
public ActionResult ChangePassword(PasswordModel model) { ViewBag.ReturnUrl = Url.Action("ChangePassword"); if (ModelState.IsValid) { UserMembershipModel user = new UserMembershipModel(); user.username = User.Identity.Name; user.currentPassword = model.MatKhauHienTai; user.newPassword = model.MatKhauMoi; if (service.ChangePassword(user)) { return RedirectToAction("ChangePassword", new { Message = ManageMessageId.ChangePasswordSuccess }); } else { ModelState.AddModelError("", "Cập nhật thất bại!"); } } return View(model); }
public void PasswordFor_GeneratesPlaceholderAttribute_WhenDisplayAttributePromptIsSet() { // Arrange var expected = @"<input id=""HtmlEncode[[Property7]]"" name=""HtmlEncode[[Property7]]"" placeholder=""HtmlEncode[[placeholder]]"" type=""HtmlEncode[[password]]"" />"; var model = new PasswordModel(); var helper = DefaultTemplatesUtilities.GetHtmlHelper(model); // Act var result = helper.PasswordFor(m => m.Property7, htmlAttributes: null); // Assert Assert.Equal(expected, HtmlContentUtilities.HtmlContentToString(result)); }