public async Task <bool> ResetPassword(string userId, string code, string newPassword) { var user = await database.UserRepository.Get(userId); if (user == null) { return(false); } var resetPasswordToken = user.Tokens.FirstOrDefault(t => t.Code == code && t.TokenType == TokenType.ResetPassword); if (resetPasswordToken == null) { return(false); } string saltedPasswordHash = string.Empty; var passwordSalt = hashGenerator.CreateSalt(); hashGenerator.GenerateHash(newPassword, passwordSalt, out saltedPasswordHash); user.SetPassword(saltedPasswordHash, passwordSalt); if (await database.Complete()) { database.TokenRepository.Delete(resetPasswordToken); return(await database.Complete()); } return(false); }
public async Task <bool> ResetPassword(string userId, string token, string newPassword) { var user = await database.UserRepository.FindById(userId) ?? throw new EntityNotFoundException("Account does not exist", ErrorCodes.EntityNotFound); if (UserBlockedSpecification.Create().IsSatisfied(user)) { throw new BlockException("Your account is blocked"); } var resetPasswordToken = user.Tokens.FirstOrDefault(t => t.Code == token && t.TokenType == TokenType.ResetPassword) ?? throw new TokenException("Token is invalid"); if (TokenExpirationSpecification.Create().IsSatisfied(resetPasswordToken)) { throw new TokenException("Token expired", ErrorCodes.TokenExpired); } string saltedPasswordHash = string.Empty; var passwordSalt = hashGenerator.CreateSalt(); hashGenerator.GenerateHash(newPassword, passwordSalt, out saltedPasswordHash); user.SetPassword(saltedPasswordHash, passwordSalt); if (await database.Complete()) { user.Tokens.Remove(resetPasswordToken); return(await database.Complete()); } return(false); }
public async Task <AuthResult> SignUp(string email, string password, string username) { string saltedPasswordHash = string.Empty; var passwordSalt = hashGenerator.CreateSalt(); hashGenerator.GenerateHash(password, passwordSalt, out saltedPasswordHash); var user = new UserBuilder() .SetEmail(email) .SetUsername(username) .SetPassword(saltedPasswordHash, passwordSalt) .Build(); database.UserRepository.Add(user); if (await database.Complete()) { var registerToken = Token.Create(TokenType.Register); user.Tokens.Add(registerToken); if (await rolesService.AdmitRole(RoleName.User, user)) { return(await database.Complete() ? new AuthResult(registerToken.Code, user) : null); } return(null); } return(null); }
public async Task <SignUpResult> SignUp(string email, string password, string username) { string saltedPasswordHash = string.Empty; var passwordSalt = hashGenerator.CreateSalt(); hashGenerator.GenerateHash(password, passwordSalt, out saltedPasswordHash); var user = new UserBuilder() .SetUsername(username) .SetEmail(email) .SetPassword(saltedPasswordHash, passwordSalt) .Build(); database.UserRepository.Add(user); if (await database.Complete()) { var registerToken = Token.Create(TokenType.Register); database.TokenRepository.Add(registerToken); //Logic adding user to USER role if (await database.Complete()) { return(new SignUpResult(registerToken.Code, user)); } Alertify.Push("Creating register token failed", AlertType.Error); return(null); } Alertify.Push("Creating account failed", AlertType.Error); return(null); }
public Token Login(User user) { try { var dbUser = _userDataAccess.GetUser(user.Login); if (dbUser.Password != _hashGenerator.GenerateHash(user.Password)) { throw new WrongPasswordException(user.Login); } return(_tokenGenerator.GenerateToken(dbUser)); } catch (Exception ex) { Log.Error(ex.Message); return(null); } }
protected string GetFilePath(Uri uri) { string hashedDirectoryName = ""; lock (_hashLocker) { hashedDirectoryName = BitConverter.ToString(_hashGenerator.GenerateHash(ASCIIEncoding.ASCII.GetBytes(uri.AbsoluteUri))); } return(Path.Combine(_uriDbDirectory.FullName, uri.Host, hashedDirectoryName.Substring(0, 4), hashedDirectoryName)); }
/// <summary> /// internal method to add a new key value pair to the buckets /// can throw an exception if they key already exists in the buckets /// assumes there is sufficent room for the new item in the buckets /// uses optimal algorithm to skip to next bucket if occupied /// </summary> /// <param name="buckets">the bucket collection to insert into</param> /// <param name="key">the item key</param> /// <param name="value">the item value</param> private void place(IBucket[] buckets, object key, object value) { const int prime = 101; var h = hash.GenerateHash(key) & 0x7FFFFFFF; var uh = (uint)h; var up = (uint)buckets.Length; var skip = ((uh * prime) % (up - 1)) + 1; var index = (int)(uh % up); //primes make this impossible to endless loop while (true) { var nb = (ISingleItemBucket)buckets[index]; if (nb.Key == null) { nb.Value = value; nb.Key = key; nb.HashCode = h; count++; return; } if (!nb.HasCollision) { if (comparer.AreKeysEqual(nb.Key, key)) { throw new ArgumentException("Cannot place duplicate key in hashtable"); } nb.HasCollision = true; occupancy++; } index = (int)((index + skip) % up); } }
public async Task <bool> ChangePassword(string newPassword, string email, string token) { var user = await GetUserWithToken(email, TokenType.ChangePassword, token); var passwordSalt = hashGenerator.CreateSalt(); var passwordHash = hashGenerator.GenerateHash(newPassword, passwordSalt); user.SetPassword(passwordHash, passwordSalt); if (await database.UserRepository.Update(user)) { return(await database.TokenRepository.Delete(user.Token)); } throw new DatabaseException(); }
public IActionResult GetToken(Guid participantId) { if (participantId == Guid.Empty) { ModelState.AddModelError(nameof(participantId), $"Please provide a valid {nameof(participantId)}"); return(BadRequest(ModelState)); } var expiresOn = DateTime.UtcNow.AddMinutes(20).ToUniversalTime().ToString("dd.MM.yyyy-H:mmZ"); var token = _hashGenerator.GenerateHash(expiresOn, participantId.ToString()); var tokenResponse = new TokenResponse { ExpiresOn = expiresOn, Token = token }; return(Ok(tokenResponse)); }
public Doctor UpdateDoctor(Doctor doctor) { try { doctor.Password = _hashGenerator.GenerateHash(doctor.Password); doctor.Roles = new List <string> { Role.Doctor, Role.Patient }; return(_doctorDataAccess.UpdateDoctor((Doctor)doctor.NoDateTimeAdd())); } catch (Exception ex) { Log.Error(ex, "Encountered an exception while executing DoctorBusiness.UpdateDoctor"); return(null); } }
public async Task <bool> ResetPassword(string email, string token, string newPassword) { var user = await GetAndVerifyUserByEmail(email, token); var passwordSalt = hashGenerator.CreateSalt(); var passwordHash = hashGenerator.GenerateHash(newPassword, passwordSalt); user.SetPassword(passwordHash, passwordSalt); if (await database.UserRepository.Update(user)) { return(await database.TokenRepository.Delete(user.Token)); } throw new DatabaseException(); }
public Patient UpdatePatient(Patient patient) { try { patient.Password = _hashGenerator.GenerateHash(patient.Password); patient.Roles = new List <string> { Role.Patient }; return(_patientDataAccess.UpdatePatient((Patient)patient.NoDateTimeAdd())); } catch (Exception ex) { Log.Error(ex, "Encountered an exception while executing PatientBusiness.UpdatePatient"); return(null); } }
public void GenerateHash_NoCollisions() { List <Uri> randomUris = GenerateRandomDataList(10000); Dictionary <string, byte[]> hashes = new Dictionary <string, byte[]>(); try { foreach (Uri input in randomUris) { hashes.Add(input.AbsoluteUri, _unitUnderTest.GenerateHash(input.AbsoluteUri)); } } catch (Exception e) { Assert.Fail(); } }
public async Task <ChangePasswordResult> ChangePassword(string oldPassword, string newPassword) { var user = await GetCurrentUser(); if (!hashGenerator.VerifyHash(oldPassword, user.PasswordHash, user.PasswordSalt)) { return(new ChangePasswordResult(message: "Old password is invalid")); } string saltedPasswordHash = string.Empty; var passwordSalt = hashGenerator.CreateSalt(); hashGenerator.GenerateHash(newPassword, passwordSalt, out saltedPasswordHash); user.SetPassword(saltedPasswordHash, passwordSalt); return(await database.Complete() ? new ChangePasswordResult(hasChanged: true) : null); }
public async Task <SignUpResult> SignUp(string username, string email, string password, string serial, int referrerId) { var passwordSalt = hashGenerator.CreateSalt(); var passwordHash = hashGenerator.GenerateHash(password, passwordSalt); var user = new UserBuilder() .SetUsername(username) .SetEmail(email) .SetPassword(passwordHash, passwordSalt) .SetSerial(serial) .SetReferrer(referrerId) .Build(); using (var transaction = database.BeginTransaction().Transaction) { if (!await database.UserRepository.Insert(user)) { throw new DatabaseException(); } user = await database.UserRepository.FindUserByUsername(username) ?? throw new EntityNotFoundException("User not found"); var serialToAdd = Serial.Create(user.Id, serial); var registerToken = Token.Create(TokenType.Register, user.Id); if (!await database.SerialRepository.Insert(serialToAdd)) { throw new DatabaseException(); } if (!await database.TokenRepository.Insert(registerToken, false)) { throw new DatabaseException(); } transaction.Complete(); return(new SignUpResult { User = user, TokenCode = registerToken.Code }); } }
public async Task <bool> ChangePassword(string oldPassword, string newPassword) { var user = await GetCurrentUser(); if (!hashGenerator.VerifyHash(oldPassword, user.PasswordHash, user.PasswordSalt)) { Alertify.Push("Old password is invalid", AlertType.Error); return(false); } string saltedPasswordHash = string.Empty; var passwordSalt = hashGenerator.CreateSalt(); hashGenerator.GenerateHash(newPassword, passwordSalt, out saltedPasswordHash); user.SetPassword(saltedPasswordHash, passwordSalt); return(await database.Complete()); }
/// <summary> /// Determines which bucket index in the buckets array should contain the key /// </summary> /// <param name="key">the key to compute the bucket index</param> /// <returns>positive integer</returns> private int GetBucketIndex(object key) => (hash.GenerateHash(key) & 0x7FFFFFFF) % Capacity;
public string Generate(Guid vendorId, Guid sharedSecret) { var valueToHash = string.Concat(vendorId.ToString("N"), _dateTimeProvider.Now.ToString("ddMMyyyy")); return(_hashGenerator.GenerateHash(valueToHash, sharedSecret.ToString("N"))); }