GetOrchestratorResponseUpdateApprenticeshipViewModelFromCookie(string hashedAccountId, string hashedApprenticeshipId) { var mappedModel = _apprenticeshipsViewModelCookieStorageService.Get(CookieName); var apprenticeshipId = HashingService.DecodeValue(hashedApprenticeshipId); var accountId = HashingService.DecodeValue(hashedAccountId); var apprenticeshipResult = await Mediator.SendAsync( new GetApprenticeshipQueryRequest { AccountId = accountId, ApprenticeshipId = apprenticeshipId }); var apprenticeship = _apprenticeshipMapper.MapToApprenticeshipDetailsViewModel(apprenticeshipResult.Apprenticeship); mappedModel.OriginalApprenticeship = apprenticeship; mappedModel.HashedAccountId = hashedAccountId; mappedModel.HashedApprenticeshipId = hashedApprenticeshipId; return(new OrchestratorResponse <UpdateApprenticeshipViewModel> { Data = mappedModel }); }
public async Task UpdateStopDate(string hashedAccountId, string hashedApprenticeshipId, EditApprenticeshipStopDateViewModel model, string externalUserId, string userName, string userEmail) { var accountId = HashingService.DecodeValue(hashedAccountId); var apprenticeshipId = HashingService.DecodeValue(hashedApprenticeshipId); Logger.Info($"Updating Apprenticeship stop date. AccountId: {accountId}, ApprenticeshipId: {apprenticeshipId}"); await CheckUserAuthorization(async() => { var data = await Mediator.SendAsync(new GetApprenticeshipQueryRequest { AccountId = accountId, ApprenticeshipId = apprenticeshipId }); await Mediator.SendAsync(new UpdateApprenticeshipStopDateCommand { UserId = externalUserId, ApprenticeshipId = apprenticeshipId, EmployerAccountId = accountId, NewStopDate = model.NewStopDate.DateTime.Value, UserEmailAddress = userEmail, UserDisplayName = userName, CommitmentId = data.Apprenticeship.CommitmentId }); }, hashedAccountId, externalUserId); }
public async Task UpdateStatus(string hashedAccountId, string hashedApprenticeshipId, ChangeStatusViewModel model, string externalUserId, string userName, string userEmail) { var accountId = HashingService.DecodeValue(hashedAccountId); var apprenticeshipId = HashingService.DecodeValue(hashedApprenticeshipId); Logger.Info( $"Updating Apprenticeship status to {model.ChangeType}. AccountId: {accountId}, ApprenticeshipId: {apprenticeshipId}"); await CheckUserAuthorization(async() => { var data = await Mediator.SendAsync(new GetApprenticeshipQueryRequest { AccountId = accountId, ApprenticeshipId = apprenticeshipId }); CheckApprenticeshipStateValidForChange(data.Apprenticeship); await Mediator.SendAsync(new UpdateApprenticeshipStatusCommand { UserId = externalUserId, ApprenticeshipId = apprenticeshipId, EmployerAccountId = accountId, ChangeType = (Domain.Models.Apprenticeship.ChangeStatusType)model.ChangeType, DateOfChange = model.DateOfChange.DateTime.Value, UserEmailAddress = userEmail, UserDisplayName = userName, MadeRedundant = model.MadeRedundant }); }, hashedAccountId, externalUserId); }
public async Task <OrchestratorResponse <ChangeStatusChoiceViewModel> > GetChangeStatusChoiceNavigation(string hashedAccountId, string hashedApprenticeshipId, string externalUserId) { var accountId = HashingService.DecodeValue(hashedAccountId); var apprenticeshipId = HashingService.DecodeValue(hashedApprenticeshipId); Logger.Info( $"Determining navigation for type of change status selection. AccountId: {accountId}, ApprenticeshipId: {apprenticeshipId}"); return(await CheckUserAuthorization(async() => { var data = await Mediator.SendAsync(new GetApprenticeshipQueryRequest { AccountId = accountId, ApprenticeshipId = apprenticeshipId }); CheckApprenticeshipStateValidForChange(data.Apprenticeship); var isPaused = data.Apprenticeship.PaymentStatus == PaymentStatus.Paused; var apprenticeDetailsV2Link = _linkGenerator.CommitmentsV2Link($"{hashedAccountId}/apprentices/{hashedApprenticeshipId}/details"); return new OrchestratorResponse <ChangeStatusChoiceViewModel> { Data = new ChangeStatusChoiceViewModel { IsCurrentlyPaused = isPaused, ApprenticeDetailsV2Link = apprenticeDetailsV2Link } }; }, hashedAccountId, externalUserId)); }
private async Task AddReservationValidationErrors(ConcurrentDictionary <string, string> errors, ApprenticeshipViewModel model) { void AddToErrors(ReservationValidationResult data) { foreach (var error in data.ValidationErrors) { errors.TryAdd(error.PropertyName, error.Reason); } } if (model.ReservationId == null) { Logger.Info($"Apprenticeship: {HashingService.DecodeValue(model.HashedApprenticeshipId)} Reservation-id:null - no reservation validation required"); return; } if (model.StartDate?.DateTime == null) { Logger.Info($"Apprenticeship: {HashingService.DecodeValue(model.HashedApprenticeshipId)} Reservation-id:{model.ReservationId} start date required for reservation validation"); return; } var response = await Mediator.SendAsync( new GetReservationValidationRequest { StartDate = model.StartDate.DateTime.Value, TrainingCode = model.TrainingCode, ReservationId = model.ReservationId.Value } ); AddToErrors(response.Data); }
public async Task <FinishEditingViewModel> GetFinishEditing(long providerId, string hashedCommitmentId) { var commitmentId = HashingService.DecodeValue(hashedCommitmentId); Logger.Info($"Get info for finish editing options for provider:{providerId} commitment:{commitmentId}", providerId: providerId, commitmentId: commitmentId); var commitment = await GetCommitment(providerId, commitmentId); AssertCommitmentStatus(commitment, EditStatus.ProviderOnly); AssertCommitmentStatus(commitment, AgreementStatus.EmployerAgreed, AgreementStatus.ProviderAgreed, AgreementStatus.NotAgreed); var overlaps = await Mediator.Send( new GetOverlappingApprenticeshipsQueryRequest { Apprenticeship = commitment.Apprenticeships }); return(new FinishEditingViewModel { HashedCommitmentId = hashedCommitmentId, ProviderId = providerId, ReadyForApproval = commitment.CanBeApproved, ApprovalState = GetApprovalState(commitment), HasApprenticeships = commitment.Apprenticeships.Any(), InvalidApprenticeshipCount = commitment.Apprenticeships.Count(x => !x.CanBeApproved), HasSignedTheAgreement = await IsSignedAgreement(providerId) == ProviderAgreementStatus.Agreed, SignAgreementUrl = _configuration.ContractAgreementsUrl, HasOverlappingErrors = overlaps.Overlaps.Any() }); }
public void TestUpdatePassword() { HashingService hashed = new HashingService(); using (var mock = AutoMock.GetLoose()) { var person = new Person { Id = 1, LastName = "EditedDrew", FirstName = "Drew", Ssn = "123456789", Gender = "Male", DateOfBirth = DateTime.Now, RoleId = 1, StatusId = 1, Email = "*****@*****.**", StreetAddress = "1149 Grove", Zipcode = "30145", Phone = "7777777777", Password = "******", Username = "******" }; mock.Mock <IPersonDAL>().Setup(x => x.GetDesiredPersons(It.IsAny <string>())).Returns(GetSamplePeople()); var personDAL = mock.Create <IPersonDAL>(); personDAL.UpdatePassword(person); mock.Mock <IPersonDAL>().Verify(x => x.UpdatePassword(person), Times.Exactly(1)); } }
public AccountModule(ServiceBusClient busClient, HashingService hashingService) { this.busClient = busClient; this.hashingService = hashingService; Post("/SignUp", async _ => await SignUp()); }
/// <summary> /// Verifies a person's login information and retrieves full name and role /// </summary> /// <param name="username">As a string</param> /// <param name="password">As a string</param> /// <returns></returns> public DataTable GetLogin(string username, string password) { DataTable dt = new DataTable(); HashingService hash = new HashingService(); string selectStatement = "SELECT p.id, p.username, p.password, (p.first_name + ' ' + p.last_name) AS 'name', r.roleTitle " + "FROM person p " + "JOIN role r ON p.roleID = r.id " + "WHERE username = @username AND password = @password"; using (SqlConnection connection = ScheduleBuilder_DB_Connection.GetConnection()) { connection.Open(); SqlCommand sqlCommand = new SqlCommand(selectStatement, connection); sqlCommand.Parameters.AddWithValue("@username", username); sqlCommand.Parameters.AddWithValue("@password", hash.PasswordHashing(password)); SqlDataReader reader = sqlCommand.ExecuteReader(); dt.Columns.Add("id", typeof(int)); dt.Columns.Add("username", typeof(string)); dt.Columns.Add("password", typeof(string)); dt.Columns.Add("name", typeof(string)); dt.Columns.Add("roleTitle", typeof(string)); dt.Load(reader); } return(dt); }
public void VerifyPassword_ComparingWrongPassword_ShouldNotBeEqual() { // Arrange HashingSettings settings = new HashingSettings(HashingMethodType.SHA256); HashingService hashingService = new HashingService(settings); string username = "******"; string correctPassword = "******"; string wrongPassword = "******"; IHashedUser hashedUser = null; bool passwordMatched = false; // Act hashedUser = hashingService.CreateHashedUser(username, correctPassword); passwordMatched = hashingService.VerifyPassword(wrongPassword, hashedUser.Password, hashedUser.Salt); Console.WriteLine("Original Correct Password: "******"Original Wrong Password: "******"Hashed Password: "******"Hashed Salt: " + hashedUser.Salt); // Assert Assert.IsFalse(passwordMatched); }
public T Execute <T>(CMDDatabaseContext context) where T : class { context.ValidateApplicationToken(_applicationToken); try { context.ValidateAuthorityApplicationToken(_authorityApplicationToken); } catch (Exception) { var message = string.Format("Legacy call to create a UserToken without an authority was used.{0}Application: {1}{0}User: {2}", Environment.NewLine, _applicationToken, _userId); DAL.LogException(new Exception(message), LogCategory.Runnable); } var token = HashingService.GenerateToken(); var userToken = new UserToken { UserId = _userId, Token = token, }; userToken.EndDate = userToken.StartDate.AddDays(_validDays); return(context.Create(userToken, false) as T); }
public async Task ThenIAmAbleToGetAnAccountByTheInternalId() { //Arrange var accountId = 1923701937; var hashedAccountId = "ABC123"; HashingService.Setup(x => x.HashValue(accountId)).Returns(hashedAccountId); ApiService.Setup(x => x.GetAccount(hashedAccountId, It.IsAny <CancellationToken>())).ReturnsAsync(new AccountDetailViewModel { AccountId = accountId, ApprenticeshipEmployerType = ApprenticeshipEmployerType.Levy.ToString(), LegalEntities = new ResourceList(new List <ResourceViewModel>()), PayeSchemes = new ResourceList(new List <ResourceViewModel>()) }); Mediator.Setup(x => x.SendAsync(It.IsAny <GetAccountBalancesRequest>())).ReturnsAsync(new GetAccountBalancesResponse { Accounts = new List <AccountBalance> { new AccountBalance() } }); Mediator.Setup(x => x.SendAsync(It.IsAny <GetTransferAllowanceQuery>())).ReturnsAsync(new GetTransferAllowanceResponse { TransferAllowance = new TransferAllowance() }); //Act var response = await Controller.GetAccount(accountId); //Assert Assert.IsNotNull(response); Assert.IsInstanceOf <OkNegotiatedContentResult <AccountDetailViewModel> >(response); }
public async Task <OrchestratorResponse <ApprenticeshipDetailsViewModel> > GetApprenticeship(string hashedAccountId, string hashedApprenticeshipId, string externalUserId) { var accountId = HashingService.DecodeValue(hashedAccountId); var apprenticeshipId = HashingService.DecodeValue(hashedApprenticeshipId); Logger.Info( $"Getting On-programme apprenticeships Provider: {accountId}, ApprenticeshipId: {apprenticeshipId}"); return(await CheckUserAuthorization(async() => { var data = await Mediator.SendAsync( new GetApprenticeshipQueryRequest { AccountId = accountId, ApprenticeshipId = apprenticeshipId }); var detailsViewModel = _apprenticeshipMapper.MapToApprenticeshipDetailsViewModel(data.Apprenticeship); detailsViewModel.PendingDataLockRestart = data.Apprenticeship.DataLockCourseTriaged; detailsViewModel.PendingDataLockChange = data.Apprenticeship.DataLockPriceTriaged || data.Apprenticeship.DataLockCourseChangeTriaged; return new OrchestratorResponse <ApprenticeshipDetailsViewModel> { Data = detailsViewModel }; }, hashedAccountId, externalUserId)); }
public BasicAuthHandler(IOptionsMonitor <BasicAuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, MinerContext dbContext, HashingService hashingService) : base(options, logger, encoder, clock) { DbContext = dbContext; HashingService = hashingService; }
public Recognizer() { Id = Guid.NewGuid().ToString(); Key = HashingService.GenerateSHA256(Convert.FromBase64String(Guid.NewGuid().ToString().Replace("-", "")), Convert.FromBase64String(ApplicationDbContext._hashSalt)); LastActivityDateTime = DateTime.UtcNow.AddHours(8); LastActivityAction = "IDLE"; }
/// <summary> /// retireve a person's login information /// </summary> /// <param name="username">As a string</param> /// <param name="password">As a string</param> /// <returns></returns> public DataTable GetLogin(string username, string password) { HashingService hashing = new HashingService(); DataTable dt = new DataTable(); string selectStatement = "SELECT l.personID, l.userName, l.password, (p.firstName + ' ' + p.lastName) AS name" + " FROM login l JOIN person p ON p.personID = l.personID WHERE userName = @username AND password = @password"; using (SqlConnection connection = HealthcareDBConnection.GetConnection()) { connection.Open(); SqlCommand sc = new SqlCommand(selectStatement, connection); sc.Parameters.AddWithValue("@username", username); sc.Parameters.AddWithValue("@password", hashing.PasswordHashing(password)); SqlDataReader reader = sc.ExecuteReader(); dt.Columns.Add("personID", typeof(int)); dt.Columns.Add("userName", typeof(string)); dt.Columns.Add("password", typeof(string)); dt.Columns.Add("name", typeof(string)); dt.Load(reader); } return(dt); }
static void Main(string[] args) { const string title = "SFA.DAS.HashingService.Console v0.1"; Console.Title = title; Console.ForegroundColor = ConsoleColor.Yellow; Console.BackgroundColor = ConsoleColor.Blue; Console.WriteLine(title); Console.ResetColor(); Console.WriteLine(); Console.WriteLine("Enter 'hashstring' setting:"); var hashstring = Console.ReadLine(); if (hashstring == "") { hashstring = "TEST: Dummy hash code London is a city in UK"; } Console.WriteLine("Enter 'allowed characters' setting:"); var allowedChars = Console.ReadLine(); if (allowedChars == "") { allowedChars = "12345QWERTYUIOPNDGHAK"; } _service = new HashingService(allowedChars, hashstring); PrintMenu(); }
public UserLoginCommand( UserRepository userRepository, HashingService hashingService) { this.userRepository = userRepository; this.hashingService = hashingService; }
public UserController(MinerContext dbContext, HashingService hashingService, CustomizationOption customizationOptions, UserService userService) { DbContext = dbContext; HashingService = hashingService; CustomizationOptions = customizationOptions; UserService = userService; }
public async Task SendProviderApprenticeshipStopNotification(Apprenticeship apprenticeship, DateTime stopDate) { if (!_configuration.CommitmentNotification.SendEmail) { Logger.Info("Sending email notifications disabled by config."); return; } var emailMessage = new EmailMessage { TemplateId = "ProviderApprenticeshipStopNotification", Tokens = new Dictionary <string, string> { { "EMPLOYER", apprenticeship.LegalEntityName }, { "APPRENTICE", apprenticeship.ApprenticeshipName }, { "DATE", stopDate.ToString("dd/MM/yyyy") }, { "URL", $"{apprenticeship.ProviderId}/apprentices/manage/{HashingService.HashValue(apprenticeship.Id)}/details" } } }; Logger.Info($"Sending email to all provider recipients for Provider {apprenticeship.ProviderId}, template {emailMessage.TemplateId}"); await _providerEmailService.SendEmailToAllProviderRecipients( apprenticeship.ProviderId, string.Empty, emailMessage); }
/// <summary> /// Updates a persons password with a new password based on email input in controller /// </summary> /// <param name="person"></param> /// <param name="newPassword"></param> public void UpdatePasswordOnly(Person person, string newPassword) { HashingService hashed = new HashingService(); string update = @"UPDATE dbo.person SET password = @password WHERE id = @id"; int count = 0; try { using (SqlConnection connection = ScheduleBuilder_DB_Connection.GetConnection()) { connection.Open(); using (SqlCommand updateCommand = new SqlCommand(update, connection)) { updateCommand.Parameters.AddWithValue("@password", hashed.PasswordHashing(newPassword)); updateCommand.Parameters.AddWithValue("@id", person.Id); count = updateCommand.ExecuteNonQuery(); } connection.Close(); } } catch (SqlException ex) { throw ex; } }
public void Execute(CMDDatabaseContext context) { var hashedPassword = HashingService.Hash(GenerateDefaultPassword(), _user.PasswordSalt); _user.PasswordHash = hashedPassword; context.SaveChanges(); }
public async Task <OrchestratorResponse <UpdateApprenticeshipViewModel> > GetConfirmChangesModel( string hashedAccountId, string hashedApprenticeshipId, string externalUserId, ApprenticeshipViewModel apprenticeship) { //todo: could pick up first 2 params from apprenticeship var accountId = HashingService.DecodeValue(hashedAccountId); var apprenticeshipId = HashingService.DecodeValue(hashedApprenticeshipId); Logger.Debug($"Getting confirm change model: {accountId}, ApprenticeshipId: {apprenticeshipId}"); return(await CheckUserAuthorization(async() => { await AssertApprenticeshipStatus(accountId, apprenticeshipId); var data = await Mediator.SendAsync(new GetApprenticeshipQueryRequest { AccountId = accountId, ApprenticeshipId = apprenticeshipId }); var apprenticeships = _apprenticeshipMapper.CompareAndMapToApprenticeshipViewModel(data.Apprenticeship, apprenticeship); return new OrchestratorResponse <UpdateApprenticeshipViewModel> { Data = await apprenticeships }; }, hashedAccountId, externalUserId)); }
public UserService(IUserDAO userDAO) { this._userDAO = userDAO; this.IsUserLoggedIn = false; // Setup hashing service. this._hashingService = new HashingService(new HashingSettings(HashingMethodType.SHA256)); }
public async Task SubmitCommitment(string currentUserId, long providerId, string hashedCommitmentId, SaveStatus saveStatus, string message, SignInUserModel currentUser) { var commitmentId = HashingService.DecodeValue(hashedCommitmentId); await AssertCommitmentStatus(commitmentId, providerId); Logger.Info($"Submitting ({saveStatus}) Commitment for provider:{providerId} commitment:{commitmentId}", providerId: providerId, commitmentId: commitmentId); if (saveStatus == SaveStatus.Approve || saveStatus == SaveStatus.ApproveAndSend) { var isSigned = await IsSignedAgreement(providerId) == ProviderAgreementStatus.Agreed; if (!isSigned) { throw new InvalidStateException("Cannot approve commitment when no agreement signed"); } } LastAction lastAction; switch (saveStatus) { case SaveStatus.AmendAndSend: lastAction = LastAction.Amend; break; case SaveStatus.Approve: lastAction = LastAction.Approve; break; case SaveStatus.ApproveAndSend: lastAction = LastAction.Approve; break; case SaveStatus.Save: lastAction = LastAction.None; break; default: lastAction = LastAction.None; break; } await Mediator.Send( new SubmitCommitmentCommand { ProviderId = providerId, HashedCommitmentId = hashedCommitmentId, CommitmentId = commitmentId, Message = message, LastAction = lastAction, CreateTask = (saveStatus == SaveStatus.ApproveAndSend || saveStatus == SaveStatus.AmendAndSend), UserDisplayName = currentUser.DisplayName, UserEmailAddress = currentUser.Email, UserId = currentUserId }); }
public MemberCapture() { Id = Guid.NewGuid().ToString(); string key = Guid.NewGuid().ToString(); Code = HashingService.GenerateSHA256(Convert.FromBase64String(key.Replace("-", "")), Convert.FromBase64String(ApplicationDbContext._hashSalt)).Replace('+', 'x'); Type = 0; Status = 1; }
public async Task GetHashOfEmptyAsync() { var hashF = new XXHash64(); var hashing = new HashingService(hashF); var stream = new MemoryStream(new byte[] { }); var hash = await hashing.GetFileHash(stream, CancellationToken.None); hash.Should().Be(hashF.HashOfEmpty); }
public UserSignUpCommand( UserRepository userRepository, HashingService hashingService, SecurePseudoRandomGenerator securePseudoRandomGenerator) { this.userRepository = userRepository; this.hashingService = hashingService; this.securePseudoRandomGenerator = securePseudoRandomGenerator; }
public void Then_AlphaNumeric_HashId_Should_Not_BeEqual_To_Encoded_Value(string hashId) { //Act var _sut = new HashingService(AllowedCharacters, Hashstring); var encodedValue = _sut.HashValue(hashId); //Assert hashId.Should().NotBe(encodedValue); }
public AppLoginSession(string key, HttpRequest request) { Id = Guid.NewGuid().ToString(); Status = 0; DateCreated = DateTime.UtcNow.AddHours(8); Key = HashingService.GenerateSHA256(Convert.FromBase64String(key.Replace("-", "")), Convert.FromBase64String(ApplicationDbContext._hashSalt)); IpAddress = request.Host.Value; UserAgent = request.Headers["User-Agent"].ToString(); }