public PasswordHistory GetLocalAdminPasswordHistory(string computerName) { PasswordHistory result = new PasswordHistory(); result.ComputerName = computerName; Principal searchResult = null; try { searchResult = SearchForComputer(computerName); } catch (Exception ex) { throw ex; } DirectoryEntry underlyingComputer = searchResult.GetUnderlyingObject() as DirectoryEntry; Object[] obj = underlyingComputer.Properties["ms-MCS-AdmPwdHistory"].Value as Object[]; foreach (string str in obj) { result.Passwords.Add(str); } return(result); }
public Login ResetPasswordPublic(string userName, string newPassword, out string message) { using (LoanPriceEntities context = new LoanPriceEntities()) { Login model = context.Logins.FirstOrDefault(c => c.Name == userName); if (model == null) { message = "User with this name doesn't exist"; return(model); } else if (model.IsLocked) { message = "User account is locked. We cann't reset password."; return(model); } // Save password history PasswordHistory history = new PasswordHistory(); history.ChangedDate = DateTime.Now; history.ChangedPassword = newPassword; history.Password = model.Password; history.UserId = model.ID; context.PasswordHistories.AddObject(history); model.Password = newPassword; model.LastPasswordReset = DateTime.Now; context.SaveChanges(); message = "Password reseted successfully"; return(model); } }
private CipherIdentityData ToCipherIdentityData() { return(new CipherIdentityData { Name = Name, Notes = Notes, Fields = Fields?.Select(f => f.ToCipherFieldData()), PasswordHistory = PasswordHistory?.Select(ph => ph.ToCipherPasswordHistoryData()), Title = Identity.Title, FirstName = Identity.FirstName, MiddleName = Identity.MiddleName, LastName = Identity.LastName, Address1 = Identity.Address1, Address2 = Identity.Address2, Address3 = Identity.Address3, City = Identity.City, State = Identity.State, PostalCode = Identity.PostalCode, Country = Identity.Country, Company = Identity.Company, Email = Identity.Email, Phone = Identity.Phone, SSN = Identity.SSN, Username = Identity.Username, PassportNumber = Identity.PassportNumber, LicenseNumber = Identity.LicenseNumber, }); }
public AuthUserManagementService(HttpClient httpClient, IOptions <Auth0ManagementApiConfig> auth0ManagementApiConfig, ILogger <AuthUserManagementService> logger, IOptions <PasswordHistory> passwordHistory) { _httpClient = httpClient; _auth0ManagementApiConfig = auth0ManagementApiConfig.Value; _logger = logger; _passwordHistory = passwordHistory.Value; }
private string UserName(PasswordHistory <UsernamePassword> hist) { if (hist.Count > 0) { return(hist[0].UserName); } return(null); }
static internal PasswordHistoryDto ConvertToPasswordHistoryDto(PasswordHistory passwordHistory) { return(new PasswordHistoryDto() { UserName = passwordHistory.UserName, CurrentPassword = (passwordHistory.CurrentPassword.PasswordText, passwordHistory.CurrentPassword.CreatedAt), PreviousPasswords = passwordHistory.PreviousPasswords.Select(psw => (psw.PasswordText, psw.CreatedAt)).ToList() });
public async Task <IHttpActionResult> User(RegisterViewModel model) { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } ApplicationUser user = db.Users.Where(e => e.EmployeeId == model.EmployeeId && e.EmployeeStatus == "Active").SingleOrDefault(); if (user == null) { var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context)); ApplicationUser User = new ApplicationUser(); User.UserName = Convert.ToString(model.EmployeeId); User.PasswordHash = HashPassword(model.Password); User.EmployeeId = model.EmployeeId; User.Email = "*****@*****.**"; User.FirstName = "wajahat"; User.LastName = "Nabi"; User.LastPasswordChangedDate = DateTime.Now; User.SecurityStamp = Guid.NewGuid().ToString("D"); db.Users.Add(User); db.SaveChanges(); UserManager.AddToRole(User.Id, roleManager.FindByName("User").Name); PasswordHistory ph = new PasswordHistory(); ph.userId = User.Id; ph.password = User.PasswordHash; db.PasswordHistories.Add(ph); db.SaveChanges(); return(Ok()); } else if (user.PasswordHash == null) { var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context)); user.UserName = Convert.ToString(model.EmployeeId); user.PasswordHash = HashPassword(model.Password); user.Email = user.bussinessEmail; user.LastPasswordChangedDate = DateTime.Now; user.SecurityStamp = Guid.NewGuid().ToString("D"); db.Users.Add(user); db.Entry(user).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); PasswordHistory ph = new PasswordHistory(); ph.userId = user.Id; ph.password = user.PasswordHash; db.PasswordHistories.Add(ph); db.SaveChanges(); UserManager.AddToRole(user.Id, roleManager.FindByName("User").Name); return(Ok()); } else { return(Conflict()); } }
private PasswordHistory <UsernamePassword> ToHistory(string payload) { PasswordHistory <UsernamePassword> tmp = new PasswordHistory <UsernamePassword>(); StringBuilder sb = new StringBuilder(); char prev = ' '; string user = null; foreach (char cur in payload) { if (cur != escape && cur != sep) { sb.Append(cur); prev = cur; } else { if (cur == escape) { if (prev == escape) { sb.Append(cur); prev = ' '; } else { prev = cur; } } else //cur == sep { if (prev == escape) //literal { sb.Append(cur); } else //separation of items { if (user == null) //we're hitting the user separator { user = sb.ToString(); } else //ok, we're at the end of a payload { tmp.Add(new UsernamePassword(user, sb.ToString())); user = null; } sb.Clear(); } prev = cur; } } } if (sb.Length > 0) //have to deal with the last element { tmp.Add(new UsernamePassword(user, sb.ToString())); } return(tmp); }
public void Should_ignore_non_letter_characters_rule_if_it_is_a_regular_user() { RegularUserPasswordRules regularUserPasswordRules = new RegularUserPasswordRules(); var regularUserPasswordHistory = new PasswordHistory("UserName1", new Password(CurrentPassword), _previousPasswords, regularUserPasswordRules); regularUserPasswordHistory.CreateNewPassword(new Password(ItDoesNotAddNewNonLetterCharacterInLastTwoPasswords)) .Should().BeTrue(); }
public void Should_not_ignore_new_pasword_contained_in_history_if_it_is_a_regular_user() { RegularUserPasswordRules regularUserPasswordRules = new RegularUserPasswordRules(); var regularUserPasswordHistory = new PasswordHistory("UserName1", new Password(CurrentPassword), _previousPasswords, regularUserPasswordRules); regularUserPasswordHistory.CreateNewPassword(new Password(_itContainsUsedPassword)) .Should().BeFalse(); }
/// <summary> /// This methods bubles up any DB exceptions. It would be catch by a global handler at the application level. /// We probably want the application to log the exception, this would be tested as an integration test. /// We observe the result outside the hexagon. /// Notice that we don't need to have one integration test per each integration point (DB, EventGrid, Logging, etc) /// we want to test. A single integration test can cover several integration points. /// /// Using the Result<> (CSharpFunctionalExtensions) return type could be a better approach to using "void/raise exception" in this methods. /// It could be in general a better strategy for the entire application. /// For the sake of time, given that Result<> type is not neccessary to demonstrate the pragmatic approach to unit testing, /// Result<> is not used. /// </summary> /// <param name="passwordHistory"></param> public async Task UpdatePasswordHistoryAsync(PasswordHistory passwordHistory) { await _mediator.DispatchDomainEventsAsync(passwordHistory); //this could through a DB exception _simpleInMemoryDb.UpdatePasswordHistoryDto ( ConvertToPasswordHistoryDto(passwordHistory) ); }
private CipherSecureNoteData ToCipherSecureNoteData() { return(new CipherSecureNoteData { Name = Name, Notes = Notes, Fields = Fields?.Select(f => f.ToCipherFieldData()), PasswordHistory = PasswordHistory?.Select(ph => ph.ToCipherPasswordHistoryData()), Type = SecureNote.Type, }); }
private void SavePasswordHistory(object sender, DialogControllerAcceptingEventArgs e) { IObjectSpace objectSpace = Application.CreateObjectSpace(typeof(PasswordHistory)); PasswordHistory passwordHistory = objectSpace.CreateObject <PasswordHistory>(); passwordHistory.ModificationDate = DateTime.Now; passwordHistory.UserId = SecuritySystem.CurrentUserId.ToString(); objectSpace.CommitChanges(); //TODO: Yeli //Create a store procedure that check password caducity }
private string ToPayload(PasswordHistory <UsernamePassword> hist) { if (hist.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (UsernamePassword cur in hist) { sb.Append(Encode(cur)); sb.Append(sep); } return(sb.ToString()); } return(null); }
public void Constructor_GiveValidArguments_PropertiesAreSet() { var passwordHistory = new PasswordHistory(TestVariables.PasswordHistoryId, "hash", TestVariables.Now); Assert.Equal(TestVariables.PasswordHistoryId, passwordHistory.Id); Assert.Equal("hash", passwordHistory.Hash); Assert.Equal(TestVariables.Now, passwordHistory.WhenUsed); foreach (var prop in passwordHistory.GetType().GetProperties().Where(x => x.PropertyType.Name == "IReadOnlyList`1")) { var val = prop.GetValue(passwordHistory, null); Assert.False(val == null, $"{prop.Name} is null"); } }
public int ChangePasswordfun(Int64 userid, string currentpassword, string newpassword, int pwdCount) { // 1-PASS 2 INVALID CURRENTPASSWORD 3 ALREADY USED int count = 0; Int64 pwdHistoryId; try { UserLogonData userLogonData = new UserLogonData(); PasswordHistory pwdHis = new PasswordHistory(); pwdHis.pwdHistory = userLogonData.GetPasswordHistory(userid); if (pwdHis.pwdHistory.Count >= pwdCount) { pwdHistoryId = Int64.Parse(pwdHis.pwdHistory[0].Ph_Id.ToString()); } else { pwdHistoryId = 0; } count = (from b in pwdHis.pwdHistory where b.DBPassword == newpassword select b).Count(); if (count > 0) { return(3); } else { if (userLogonData.UpdatePassword(userid, newpassword, pwdHistoryId) == true) { return(1); } else { return(0); } } } catch (Exception ex) { throw ex; } }
public void Setup() { _transactionScope = new TransactionScope(); _passwordHistoryRepository = new PasswordHistoryRepository(ConfigurationManager.ConnectionStrings["Unity"].ConnectionString); _applicationUserRepository = new ApplicationUserRepository(ConfigurationManager.ConnectionStrings["Unity"].ConnectionString); _user = BuildMeA.ApplicationUser("user1"); _passwordHistory1 = BuildMeA.PasswordHistory(_user.Id, "password1"); _passwordHistory2 = BuildMeA.PasswordHistory(_user.Id, "password2"); _passwordHistory3 = BuildMeA.PasswordHistory(_user.Id, "password3"); _passwordHistory4 = BuildMeA.PasswordHistory(_user.Id, "password4"); _passwordHistory5 = BuildMeA.PasswordHistory(_user.Id, "password5"); _passwordHistory6 = BuildMeA.PasswordHistory(_user.Id, "password6"); _passwordHistory7 = BuildMeA.PasswordHistory(_user.Id, "password7"); _passwordHistory8 = BuildMeA.PasswordHistory(_user.Id, "password8"); }
public PasswordHistoryTests() { _previousPasswords = _previousPasswords = new List <Password>() { new Password("password1", new DateTime(2020, 04, 04)), new Password(UsedPassword, new DateTime(2020, 01, 01)), new Password("password2", new DateTime(2020, 03, 03)), new Password("password3", new DateTime(2020, 02, 02)) }; _itContainsUsedPassword = $"A{_previousPasswords[0].PasswordText}B!"; _highProfileUserPasswordRules = new HighProfileUserPasswordRules(); _highProfileUserPasswordHistory = new PasswordHistory("UserName1", new Password(CurrentPassword), _previousPasswords, _highProfileUserPasswordRules); }
public Task AddPasswordHistoryItem(IdentityUser user, string password) { var passwordHistory = new PasswordHistory(); passwordHistory.UserId = user.Id; passwordHistory.PasswordHash = _passwordHasher.HashPassword(user, password); passwordHistory.CreatedOn = DateTime.UtcNow; //This configuration can/should be moved to a service passwordHistory.ExpiresOn = DateTime.UtcNow.AddMonths(3); _dbContext.PasswordHistory.Add(passwordHistory); _dbContext.SaveChanges(); return(Task.CompletedTask); }
public async Task <IActionResult> GetPasswordHistoryById(Int64 PasswordHistoryId) { PasswordHistory Items = new PasswordHistory(); try { Items = await _context.PasswordHistory.Where(q => q.PasswordHistoryId == PasswordHistoryId).FirstOrDefaultAsync(); } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(BadRequest($"Ocurrio un error:{ex.Message}")); } return(await Task.Run(() => Ok(Items))); }
public void ChangeOwnPassword(PxPasswordChangeInfo info) { if (PxSession.Current.Principal.UserId != info.UserId) { throw AuthExceptions.TryToChangeOrhersPassword(); } if (string.IsNullOrEmpty(info.New) || !Regex.IsMatch(info.New, PxConfigurationManager.PxConfig.Authentication.Policy.Regex)) { throw AuthExceptions.PasswordRegexNotMatch(); } using (PeakDbContext dbContext = new PeakDbContext()) { User usr = dbContext.Users.FirstOrDefault(x => x.Id == info.UserId); if (usr == null) { throw AuthExceptions.InvalidUserNameOrPassword(); } string encryptedOldPassword = Toolkit.Instance.Security.GetSecureHash(info.Old, usr.PasswordSalt, Encoding.UTF8, HashFormat.Base64); string encryptedNewPassword = Toolkit.Instance.Security.GetSecureHash(info.New, usr.PasswordSalt, Encoding.UTF8, HashFormat.Base64); if (encryptedOldPassword != usr.Password) { throw AuthExceptions.InvalidUserNameOrPassword(); } int passwordHistoryCheckFlag = dbContext.PasswordHistories.Where(x => x.UserId == info.UserId).OrderByDescending(x => x.Date).Take(PxConfigurationManager.PxConfig.Authentication.Policy.LastUsedPasswordsRestriction) .Union(dbContext.PasswordHistories.Where(y => y.UserId == info.UserId && y.Date > (DateTime.Now.AddDays(-PxConfigurationManager.PxConfig.Authentication.Policy.OldPasswordReusabilityPeriod)))) .Where(z => z.Password == encryptedNewPassword).Count(); if (passwordHistoryCheckFlag > 0) { throw AuthExceptions.LastUsedPasswords(PxConfigurationManager.PxConfig.Authentication.Policy.LastUsedPasswordsRestriction, PxConfigurationManager.PxConfig.Authentication.Policy.OldPasswordReusabilityPeriod); } usr.IsPwdMustChange = false; usr.PasswordChangeDate = DateTime.Today; usr.Password = encryptedNewPassword; PxSession session = PxSession.Current; session.Principal.Authentication.IsPasswordMustChanged = false; session.Save(); PasswordHistory history = new PasswordHistory(); history.Date = DateTime.Now; history.Password = encryptedNewPassword; history.UserId = info.UserId; using (TransactionScope trn = new TransactionScope()) { dbContext.SaveChanges(); trn.Complete(); } } }
private CipherCardData ToCipherCardData() { return(new CipherCardData { Name = Name, Notes = Notes, Fields = Fields?.Select(f => f.ToCipherFieldData()), PasswordHistory = PasswordHistory?.Select(ph => ph.ToCipherPasswordHistoryData()), CardholderName = Card.CardholderName, Brand = Card.Brand, Number = Card.Number, ExpMonth = Card.ExpMonth, ExpYear = Card.ExpYear, Code = Card.Code, }); }
public PasswordHistory DecryptUserPassword(User user, PasswordHistory password) { if (Verifier.Text(password.NameAfter)) { password.NameAfter = Gulipso.Gulipso.Decrypt(password.NameAfter, user.Master, Globals.Defaults.InitVector, Globals.Defaults.KeySize); } if (Verifier.Text(password.EmailAfter)) { password.EmailAfter = Gulipso.Gulipso.Decrypt(password.EmailAfter, user.Master, Globals.Defaults.InitVector, Globals.Defaults.KeySize); } if (Verifier.Text(password.UsernameAfter)) { password.UsernameAfter = Gulipso.Gulipso.Decrypt(password.UsernameAfter, user.Master, Globals.Defaults.InitVector, Globals.Defaults.KeySize); } if (Verifier.Text(password.WebsiteAfter)) { password.WebsiteAfter = Gulipso.Gulipso.Decrypt(password.WebsiteAfter, user.Master, Globals.Defaults.InitVector, Globals.Defaults.KeySize); } if (Verifier.Text(password.TextAfter)) { password.TextAfter = Gulipso.Gulipso.Decrypt(password.TextAfter, user.Master, Globals.Defaults.InitVector, Globals.Defaults.KeySize); } if (Verifier.Text(password.NameBefore)) { password.NameBefore = Gulipso.Gulipso.Decrypt(password.NameBefore, user.Master, Globals.Defaults.InitVector, Globals.Defaults.KeySize); } if (Verifier.Text(password.EmailBefore)) { password.EmailBefore = Gulipso.Gulipso.Decrypt(password.EmailBefore, user.Master, Globals.Defaults.InitVector, Globals.Defaults.KeySize); } if (Verifier.Text(password.UsernameBefore)) { password.UsernameBefore = Gulipso.Gulipso.Decrypt(password.UsernameBefore, user.Master, Globals.Defaults.InitVector, Globals.Defaults.KeySize); } if (Verifier.Text(password.WebsiteBefore)) { password.WebsiteBefore = Gulipso.Gulipso.Decrypt(password.WebsiteBefore, user.Master, Globals.Defaults.InitVector, Globals.Defaults.KeySize); } if (Verifier.Text(password.TextBefore)) { password.TextBefore = Gulipso.Gulipso.Decrypt(password.TextBefore, user.Master, Globals.Defaults.InitVector, Globals.Defaults.KeySize); } return(password); }
public bool AddCredential(IUserIdentity user, Security.ICredential credential) { if (user != null && credential != null) { UserPasswordCredential up = credential as UserPasswordCredential; //this is the only type of credential we can use if (up != null) { UsernamePassword hist = up.ToHistoryPair(); //this is what we store in history if (UserPasswordProviderFactory.Instance.ComplexityChecker.IsValid(up.password)) //validate it meets complexity rules { //get the existing credential this will replace, or this may be all together new PersistedCredential curCred = GetPersisted(user.Uid, hist.UserName); if (curCred != null) { PasswordHistory <UsernamePassword> history = GetHistory(user.Uid, hist.UserName); if (!history.MatchesHistory(UsernamePassword.Matches, hist)) //can't add this since it's matching a current history in range { history.Add(hist); //delete and set the new password if (ReplaceCredential(user.Uid, hist.UserName, hist.Password)) { this.historyProvider.Update(user.Uid, history); return(true); } } } else //no existing cred, so this is a new one - but already meets complexity rule { PasswordHistory <UsernamePassword> history = GetHistory(user.Uid, hist.UserName); if (!history.MatchesHistory(UsernamePassword.Matches, hist)) //can't add this since it's matching a current history in range { history.Add(hist); //delete and set the new password if (this.storeProvider.AddCredential(user.Uid, this, hist.UserName, hist.Password)) //the hist is already salted { this.historyProvider.Update(user.Uid, history); //update the history return(true); } } } } //inside this level we have a valid password by complexity } } return(false); }
public void SavePasswordHistory(string userId, string passwordHash) { try { var passwordHistory = new PasswordHistory { UserId = userId, PasswordHash = passwordHash, LogDate = DateTime.Now }; this._passwordHistoryRepository.Create(passwordHistory); } catch (Exception e) { throw new UnityException("Unable to save password history", e); } }
public async Task <ActionResult <PasswordHistory> > Insert([FromBody] PasswordHistory _PasswordHistory) { PasswordHistory _PasswordHistoryq = new PasswordHistory(); try { _PasswordHistoryq = _PasswordHistory; _context.PasswordHistory.Add(_PasswordHistoryq); await _context.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(BadRequest($"Ocurrio un error:{ex.Message}")); } return(await Task.Run(() => Ok(_PasswordHistoryq))); }
public bool ReplaceCredential(IUserIdentity user, Security.ICredential existing, Security.ICredential proposed) { if (user != null && existing != null && proposed != null) { UserPasswordCredential toRemove = existing as UserPasswordCredential; //this is the only type of credential we can use UserPasswordCredential toAdd = proposed as UserPasswordCredential; //this is the only type of credential we can use if (toRemove != null && toAdd != null) { PersistedCredential cred = GetPersisted(user.Uid, toRemove.UserName.ToLowerInvariant()); if (cred != null && toRemove.Matches(cred)) //has to be currently valid to do a replace { UsernamePassword up = toAdd.ToHistoryPair(); if (toRemove.UserName.ToLowerInvariant().Equals(toAdd.UserName.ToLowerInvariant())) { PasswordHistory <UsernamePassword> hist = GetHistory(user.Uid, up.UserName); if (!hist.MatchesHistory(UsernamePassword.Matches, up)) //check for historic collision { if (ReplaceCredential(user.Uid, up.UserName, up.Password)) { hist.Add(up); this.historyProvider.Update(user.Uid, hist); return(true); } } } else //different usernames being used { if (this.storeProvider.DeleteCredential(user.Uid, this, toRemove.UserName.ToLowerInvariant())) { this.historyProvider.Delete(user.Uid); //TODO -- this we need to fix by userId,type if (this.storeProvider.AddCredential(user.Uid, this, up.UserName, up.Password)) { PasswordHistory <UsernamePassword> hist = GetHistory(user.Uid, up.UserName); this.historyProvider.Update(user.Uid, hist); return(true); } } } } } } return(false); }
private CipherLoginData ToCipherLoginData() { return(new CipherLoginData { Name = Name, Notes = Notes, Fields = Fields?.Select(f => f.ToCipherFieldData()), PasswordHistory = PasswordHistory?.Select(ph => ph.ToCipherPasswordHistoryData()), Uris = Login.Uris?.Where(u => u != null) .Select(u => u.ToCipherLoginUriData()), Username = Login.Username, Password = Login.Password, PasswordRevisionDate = Login.PasswordRevisionDate, Totp = Login.Totp, AutofillOnPageLoad = Login.AutofillOnPageLoad, }); }
/// <summary> /// Change password /// </summary> /// <param name="request"></param> /// <returns></returns> public PasswordHistoryResponse ChangePassword(PasswordHistoryRequest request) { PasswordHistoryResponse response = new PasswordHistoryResponse(); using (var transaction = _context.Database.BeginTransaction()) { try { var toBeUpdate = _context.Users.SingleOrDefault(x => x.ID == request.Data.UserID); if (toBeUpdate != null) { toBeUpdate.Password = CommonUtils.Encryptor(request.Data.NewPassword, CommonUtils.KeyEncryptor); _context.SaveChanges(); } var _passHistoryEntity = new PasswordHistory { OrganizationID = request.Data.OrganizationID, UserName = request.Data.UserName, Password = CommonUtils.Encryptor(request.Data.Password, CommonUtils.KeyEncryptor), CreatedBy = request.Data.UserName, CreatedDate = DateTime.Now }; _context.PasswordHistories.Add(_passHistoryEntity); _context.SaveChanges(); transaction.Commit(); response.Message = Messages.UserPasswordUpdated; } catch { transaction.Rollback(); response.Status = false; response.Message = Messages.GeneralError; } } return(response); }
private PasswordHistory <UsernamePassword> GetHistory(Guid userId, string userName) { IEnumerable <PasswordHistory <UsernamePassword> > history = this.historyProvider.Get(userId); if (history != null) { foreach (PasswordHistory <UsernamePassword> cur in history) { if (cur[0].UserName.Equals(userName, StringComparison.Ordinal)) //already case matched { return(cur); } } } //no history, or unmatched user name for user id, maybe configuration changed PasswordHistory <UsernamePassword> curHist = new PasswordHistory <UsernamePassword>(); curHist.MaxHistory = UserPasswordProviderFactory.Instance.MaxHistory; return(curHist); }