public async Task ShouldCallMediatorToDelete()
        {
            DeleteApprenticeshipCommand arg = null;

            _mockMediator.Setup(x => x.Send(It.IsAny <DeleteApprenticeshipCommand>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new Unit())
            .Callback <DeleteApprenticeshipCommand, CancellationToken>((command, token) => arg = command);

            _mockMediator.Setup(x => x.Send(It.IsAny <GetApprenticeshipQueryRequest>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new GetApprenticeshipQueryResponse {
                Apprenticeship = new Apprenticeship()
            });

            var signInUser = new SignInUserModel {
                DisplayName = "Bob", Email = "*****@*****.**"
            };

            await _orchestrator.DeleteApprenticeship("user123", new Web.Models.DeleteConfirmationViewModel
            {
                ProviderId             = 123L,
                HashedCommitmentId     = "ABBA99",
                HashedApprenticeshipId = "ABBA66"
            }, signInUser);

            _mockMediator.Verify(x => x.Send(It.IsAny <DeleteApprenticeshipCommand>(), It.IsAny <CancellationToken>()), Times.Once);
            arg.ProviderId.Should().Be(123);
            arg.ApprenticeshipId.Should().Be(321);
            arg.UserDisplayName.Should().Be(signInUser.DisplayName);
            arg.UserEmailAddress.Should().Be(signInUser.Email);
        }
        public bool ValidateLoginCredentials(SignInUserModel user)
        {
            bool credenciaisValidas = false;

            if (user != null && !String.IsNullOrWhiteSpace(user.Email))
            {
                // Verifica a existência do usuário nas tabelas do
                // ASP.NET Core Identity
                var userIdentity = _userManager
                                   .FindByNameAsync(user.Email).Result;
                if (userIdentity != null)
                {
                    // Efetua o login com base no Id do usuário e sua senha
                    var resultadoLogin = _signInManager
                                         .CheckPasswordSignInAsync(userIdentity, user.Password, false)
                                         .Result;
                    if (resultadoLogin.Succeeded)
                    {
                        // Verifica se o usuário em questão possui
                        // a role Acesso-APIProdutos
                        //credenciaisValidas = _userManager.IsInRoleAsync(
                        //    userIdentity, Roles.Admin).Result
                        //    || _userManager.IsInRoleAsync(userIdentity, Roles.Cliente).Result
                        //    || _userManager.IsInRoleAsync(userIdentity, Roles.Prestador).Result;

                        credenciaisValidas = true;
                    }
                }
            }

            return(credenciaisValidas);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> SignIn(SignInUserModel signInUserModel)
        {
            if (ModelState.IsValid)
            {
                var result = await _accountService.SignInAsync(signInUserModel);

                if (!result.Succeeded)
                {
                    if (result.IsNotAllowed)
                    {
                        ModelState.AddModelError("", "Not allowed");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid credentials");
                    }

                    return(View(signInUserModel));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }

            return(View());
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Login(SignInUserModel signInUserModel, string returnUrl)
        {
            if (signInUserModel.Email.IndexOf('@') > -1)
            {
                //Validate email format
                string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                    @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                    @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
                Regex re = new Regex(emailRegex);
                if (!re.IsMatch(signInUserModel.Email))
                {
                    ModelState.AddModelError("Email", "Email is not valid");
                }
            }
            else
            {
                //validate Username format
                string emailRegex = @"^[a-zA-Z0-9]*$";
                Regex  re         = new Regex(emailRegex);
                if (!re.IsMatch(signInUserModel.Email))
                {
                    ModelState.AddModelError("Email", "Username is not valid");
                }
            }

            if (ModelState.IsValid)
            {
                var userName = signInUserModel.Email;
                if (userName.IndexOf('@') > -1)
                {
                    var user = await _userManager.FindByEmailAsync(signInUserModel.Email);

                    if (user == null)
                    {
                        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                        return(View(signInUserModel));
                    }
                    else
                    {
                        userName = user.UserName;
                    }
                }
                var result = await _signInManager.PasswordSignInAsync(userName, signInUserModel.Password, signInUserModel.RememberMe, false);

                if (result.Succeeded)
                {
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return(LocalRedirect(returnUrl));
                    }
                    return(RedirectToAction("Index", "Home"));
                }

                ModelState.AddModelError("", "Invalid Credintials");
            }
            return(View(signInUserModel));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> LogIn([FromBody] SignInUserModel loginModel)
        {
            var result = await signInUserCommand.Execute(loginModel);

            if (result.IsSuccessful)
            {
                return(Ok(result));
            }
            return(BadRequest(result));
        }
        public async Task ShouldCallMediatorPassingInMappedApprenticeships()
        {
            const string dataLine     = "\n\rABBA123,Chris,Froberg,1998-12-08,,,25,2,2020-08,2025-08,1500,,Employer ref,Provider ref,1113335559";
            const string fileContents = HeaderLine + dataLine;
            var          textStream   = new MemoryStream(UTF8.GetBytes(fileContents));

            _file.Setup(m => m.InputStream).Returns(textStream);

            BulkUploadApprenticeshipsCommand commandArgument = null;

            _mockMediator.Setup(x => x.Send(It.IsAny <BulkUploadApprenticeshipsCommand>(), new CancellationToken()))
            .ReturnsAsync(new Unit())
            .Callback <BulkUploadApprenticeshipsCommand, CancellationToken>((command, token) => commandArgument = command);

            _mockMediator.Setup(m => m.Send(It.IsAny <GetCommitmentQueryRequest>(), new CancellationToken()))
            .Returns(Task.FromResult(new GetCommitmentQueryResponse
            {
                Commitment = new CommitmentView
                {
                    AgreementStatus = AgreementStatus.NotAgreed,
                    EditStatus      = EditStatus.ProviderOnly
                }
            }));

            var model = new UploadApprenticeshipsViewModel {
                Attachment = _file.Object, HashedCommitmentId = "ABBA123", ProviderId = 111
            };
            var signinUser = new SignInUserModel {
                DisplayName = "Bob", Email = "*****@*****.**"
            };

            await _sut.UploadFile("user123", model, signinUser);

            _mockMediator.Verify(x => x.Send(It.IsAny <BulkUploadApprenticeshipsCommand>(), new CancellationToken()), Times.Once);

            commandArgument.ProviderId.Should().Be(111);
            commandArgument.CommitmentId.Should().Be(123);

            commandArgument.Apprenticeships.Should().NotBeEmpty();
            commandArgument.Apprenticeships.ToList()[0].FirstName.Should().Be("Chris");
            commandArgument.Apprenticeships.ToList()[0].LastName.Should().Be("Froberg");
            commandArgument.Apprenticeships.ToList()[0].DateOfBirth.Should().Be(new DateTime(1998, 12, 8));
            commandArgument.Apprenticeships.ToList()[0].TrainingType.Should().Be(DAS.Commitments.Api.Types.Apprenticeship.Types.TrainingType.Standard);
            commandArgument.Apprenticeships.ToList()[0].TrainingCode.Should().Be("2");
            commandArgument.Apprenticeships.ToList()[0].StartDate.Should().Be(new DateTime(2020, 8, 1));
            commandArgument.Apprenticeships.ToList()[0].EndDate.Should().Be(new DateTime(2025, 8, 1));
            commandArgument.Apprenticeships.ToList()[0].Cost.Should().Be(1500);
            commandArgument.Apprenticeships.ToList()[0].ProviderRef.Should().Be("Provider ref");
            commandArgument.Apprenticeships.ToList()[0].ULN.Should().Be("1113335559");
            commandArgument.UserEmailAddress.Should().Be(signinUser.Email);
            commandArgument.UserDisplayName.Should().Be(signinUser.DisplayName);
            commandArgument.UserId.Should().Be("user123");
        }
Exemplo n.º 7
0
        public void SignIn(LogonViewModel user)
        {
            AccountModule module   = new AccountModule();
            Employee      userInfo = module.GetPrototypeEmployeeByAccountID(user.Account, this.PortalDB);

            if (userInfo == null)
            {
                throw new Exception("請輸入正確帳號或密碼");
            }
            m_user = this.CreateUser(userInfo);
            Context.Session["UserInfo"] = m_user;
        }
Exemplo n.º 8
0
        public CustomJsonResult SignIn(SignInUserModel model)
        {
            SimpleUserDto user = this.userService.GetUserByCredentials(model.Name, model.Password);

            if (user == null)
            {
                return(this.ErrorResult()); //todo: handle this on client
            }

            this.Session.SetCurrentUserId(user.Id);
            FormsAuthentication.SetAuthCookie(model.Name, model.RememberMe);

            return(this.SuccessResult());
        }
Exemplo n.º 9
0
        public SuccessUserMessage GetUser(SignInUserModel obj)
        {
            SuccessUserMessage objuser = new SuccessUserMessage();

            try
            {
                return(_caseService.GetUser(obj.UserName, obj.Password));
            }
            catch (Exception ex)
            {
                objuser.Status  = false;
                objuser.Message = ex.Message.ToString();
                return(objuser);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 建立SignInUserModel實體
        /// </summary>
        /// <param name="empInfo"></param>
        /// <returns></returns>
        private SignInUserModel CreateUser(Employee empInfo)
        {
            AccountModule   module = new AccountModule();
            string          depId  = string.Empty;
            SignInUserModel user   = new SignInUserModel();

            user.ID           = empInfo.EmployeeID;
            user.ADAccount    = empInfo.ADAccount;
            user.Name         = empInfo.EmployeeName;
            user.NationalType = empInfo.NationalType;
            depId             = empInfo.DepartmentID_FK;
            user.Department   = module.GetDepartmentInfoByID(depId);
            user.Roles        = module.GetUserRoleAndMenuListByEmpID(user.ID);
            user.MenuList     = module.GetMenuListByRoleList(user.Roles);
            return(user);
        }
Exemplo n.º 11
0
 public ActionResult <object> Post(
     [FromBody] SignInUserModel usuario,
     [FromServices] AccessManager accessManager)
 {
     if (accessManager.ValidateLoginCredentials(usuario))
     {
         ClaimsPrincipal claims = this.User;
         return(Ok(accessManager.GenerateToken(usuario, claims)));
     }
     else
     {
         return(Unauthorized(new
         {
             Authenticated = false,
             Message = "Falha ao autenticar"
         }));
     }
 }
Exemplo n.º 12
0
        public async Task <SignInUserResult> Login(SignInUserModel loginModel)
        {
            var loginAsJson = JsonSerializer.Serialize(loginModel);
            var response    = await _httpClient.PutAsync("api/Accounts/Login", new StringContent(loginAsJson, Encoding.UTF8, "application/json"));

            var loginResult = JsonSerializer.Deserialize <SignInUserResult>(await response.Content.ReadAsStringAsync(), new JsonSerializerOptions {
                PropertyNameCaseInsensitive = true
            });

            if (!response.IsSuccessStatusCode)
            {
                return(loginResult);
            }

            await _localStorage.SetItemAsync(tokenStore, loginResult.Token);

            ((ApiAuthStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(loginModel.Email);
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", loginResult.Token);

            return(loginResult);
        }
Exemplo n.º 13
0
        public async Task ShouldCallMediatorToSubmitUndo(bool isApproved)
        {
            //Arrange
            var providerId       = 1;
            var apprenticeshipId = "appid";
            var userId           = "tester";
            var loginUser        = new SignInUserModel {
                DisplayName = "Bob", Email = "*****@*****.**"
            };

            //Act
            await _orchestrator.SubmitUndoApprenticeshipUpdate(providerId, apprenticeshipId, userId, loginUser);

            //Assert
            _mediator.Verify(x => x.Send(
                                 It.Is <UndoApprenticeshipUpdateCommand>(r =>
                                                                         r.ProviderId == providerId &&
                                                                         r.UserId == userId &&
                                                                         r.UserDisplayName == loginUser.DisplayName &&
                                                                         r.UserEmailAddress == loginUser.Email
                                                                         ), It.IsAny <CancellationToken>()), Times.Once());
        }
        public async Task <IActionResult> SignIn(SignInUserModel signInUserModel)
        {
            if (ModelState.IsValid)
            {
                //Wyszukanie użytkownika
                var user = await _userManager.FindByNameAsync(signInUserModel.Email);

                //Jeśli mamy tego użytkownika..
                if (user != null)
                {
                    //To próbujemy się zalogować
                    var signInResult = await _signInManager.PasswordSignInAsync(user, signInUserModel.Password, false, false);

                    if (signInResult.Succeeded)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                ModelState.AddModelError("", "Niepoprawne dane logowania");
            }

            return(View(signInUserModel));
        }
Exemplo n.º 15
0
        public async Task ShouldCallMediatorToCreate()
        {
            var    providerId             = 123;
            string userId                 = "ABC";
            var    expectedApprenticeship = new ApprenticeshipUpdate();
            var    viewModel              = new CreateApprenticeshipUpdateViewModel();
            var    signedInUser           = new SignInUserModel()
            {
                DisplayName = "Bob", Email = "*****@*****.**"
            };

            _mockApprenticeshipMapper.Setup(x => x.MapApprenticeshipUpdate(viewModel)).Returns(expectedApprenticeship);

            await _orchestrator.CreateApprenticeshipUpdate(viewModel, providerId, userId, signedInUser);

            _mockMediator.Verify(
                x =>
                x.Send(
                    It.Is <CreateApprenticeshipUpdateCommand>(
                        c =>
                        c.ProviderId == providerId && c.UserId == userId && c.ApprenticeshipUpdate == expectedApprenticeship && c.UserDisplayName == signedInUser.DisplayName &&
                        c.UserEmailAddress == signedInUser.Email), It.IsAny <CancellationToken>()), Times.Once);
        }
        public Token GenerateToken(SignInUserModel user, ClaimsPrincipal claims)
        {
            ClaimsIdentity identity = new ClaimsIdentity(
                new GenericIdentity(user.Email, "Login"),
                new[] {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.Email)
            }
                );

            DateTime dataCriacao   = DateTime.Now;
            DateTime dataExpiracao = dataCriacao +
                                     TimeSpan.FromSeconds(_tokenConfigurations.Seconds);

            var handler       = new JwtSecurityTokenHandler();
            var securityToken = handler.CreateToken(new SecurityTokenDescriptor
            {
                Issuer             = _tokenConfigurations.Issuer,
                Audience           = _tokenConfigurations.Audience,
                SigningCredentials = _signingConfigurations.SigningCredentials,
                Subject            = identity,
                NotBefore          = dataCriacao,
                Expires            = dataExpiracao
            });
            var token = handler.WriteToken(securityToken);


            return(new Token()
            {
                Authenticated = true,
                Created = dataCriacao.ToString("yyyy-MM-dd HH:mm:ss"),
                Expiration = dataExpiracao.ToString("yyyy-MM-dd HH:mm:ss"),
                AccessToken = token,
                Message = "OK",
                Roles = _userManager.GetRolesAsync(_userManager.FindByNameAsync(user.Email).Result).Result.ToArray <String>()
            });
        }
Exemplo n.º 17
0
        public async Task <IActionResult> SignIn([FromBody] SignInUserModel signInUserModel)
        {
            var signInUser = signInUserModel.ConvertToSignIn();

            if (!signInUser.IsValid())
            {
                return(CustomResponse(signInUser.ValidationResult));
            }

            var result = await __signInManager.PasswordSignInAsync(signInUser.Email, signInUser.Password, false, true);

            if (result.Succeeded)
            {
                return(CustomResponse(await GenerateJWT(signInUser.Email)));
            }

            if (result.IsLockedOut)
            {
                AdicionarErroProcessamento("Usuário temporariamente bloqueado por tentativas inválidas.");
                return(CustomResponse());
            }
            AdicionarErroProcessamento("Usuário ou senha incorretos.");
            return(CustomResponse(""));
        }
Exemplo n.º 18
0
        public async Task DeleteCommitment(string userId, long providerId, string hashedCommitmentId, SignInUserModel signinUser)
        {
            var commitmentId = HashingService.DecodeValue(hashedCommitmentId);

            Logger.Info($"Deleting commitment {hashedCommitmentId}", providerId, commitmentId);

            await Mediator.Send(new DeleteCommitmentCommand
            {
                UserId           = userId,
                ProviderId       = providerId,
                CommitmentId     = commitmentId,
                UserDisplayName  = signinUser.DisplayName,
                UserEmailAddress = signinUser.Email
            });
        }
Exemplo n.º 19
0
        public async Task <BulkUploadResultViewModel> UploadFile(string userId, UploadApprenticeshipsViewModel uploadApprenticeshipsViewModel, SignInUserModel signInUser)
        {
            var commitmentId = HashingService.DecodeValue(uploadApprenticeshipsViewModel.HashedCommitmentId);
            var providerId   = uploadApprenticeshipsViewModel.ProviderId;
            var fileName     = uploadApprenticeshipsViewModel.Attachment?.FileName ?? "<unknown>";

            var commitment = await GetCommitment(providerId, commitmentId);

            AssertCommitmentStatus(commitment);
            await AssertAutoReservationEnabled(commitment);

            Logger.Info($"Uploading File - Filename:{fileName}", uploadApprenticeshipsViewModel.ProviderId, commitmentId);

            var fileValidationResult = await _bulkUploader.ValidateFileStructure(uploadApprenticeshipsViewModel, providerId, commitment);

            if (fileValidationResult.Errors.Any())
            {
                return(new BulkUploadResultViewModel
                {
                    BulkUploadId = fileValidationResult.BulkUploadId,
                    HasFileLevelErrors = true,
                    FileLevelErrors = fileValidationResult.Errors
                });
            }

            Logger.Info("Uploading file of apprentices.", providerId, commitmentId);

            var rowValidationResult = await _bulkUploader.ValidateFileRows(fileValidationResult.Data, providerId, fileValidationResult.BulkUploadId);

            var sw            = Stopwatch.StartNew();
            var overlapErrors = await GetOverlapErrors(fileValidationResult.Data.ToList());

            Logger.Trace($"Validating overlaps took {sw.ElapsedMilliseconds}");

            var rowErrors = rowValidationResult.Errors.ToList();

            rowErrors.AddRange(overlapErrors);
            var hashedBulkUploadId = HashingService.HashValue(fileValidationResult.BulkUploadId);

            if (rowErrors.Any())
            {
                Logger.Info($"{rowErrors.Count} Upload errors", providerId, commitmentId);
                return(new BulkUploadResultViewModel
                {
                    BulkUploadId = fileValidationResult.BulkUploadId,
                    BulkUploadReference = hashedBulkUploadId,
                    HasRowLevelErrors = true,
                    RowLevelErrors = rowErrors
                });
            }

            try
            {
                await Mediator.Send(new BulkUploadApprenticeshipsCommand
                {
                    UserId           = userId,
                    ProviderId       = providerId,
                    CommitmentId     = commitmentId,
                    Apprenticeships  = await _mapper.MapFrom(commitmentId, rowValidationResult.Data),
                    UserEmailAddress = signInUser.Email,
                    UserDisplayName  = signInUser.DisplayName
                });
            }
            catch (Exception)
            {
                var overlaps = (await GetOverlapErrors(fileValidationResult.Data.ToList())).ToList();
                if (overlaps.Any())
                {
                    return(new BulkUploadResultViewModel
                    {
                        BulkUploadId = fileValidationResult.BulkUploadId,
                        HasRowLevelErrors = true,
                        RowLevelErrors = overlaps
                    });
                }

                throw;
            }

            return(new BulkUploadResultViewModel {
                BulkUploadId = fileValidationResult.BulkUploadId
            });
        }
Exemplo n.º 20
0
        public async Task <string> CreateCohort(int providerId, ConfirmEmployerViewModel confirmEmployerViewModel, string userId, SignInUserModel signinUser)
        {
            Logger.Info($"Creating cohort", providerId);

            var employerAccountId = _publicHashingService.DecodeValue(confirmEmployerViewModel.EmployerAccountPublicHashedId);

            var relationshipData = await Mediator.Send(new GetProviderRelationshipsWithPermissionQueryRequest
            {
                Permission = Operation.CreateCohort,
                ProviderId = providerId
            });

            //Check that the relationship is a valid selection
            var relationship = relationshipData.ProviderRelationships.SingleOrDefault(x =>
                                                                                      x.AccountPublicHashedId == confirmEmployerViewModel.EmployerAccountPublicHashedId &&
                                                                                      x.AccountLegalEntityPublicHashedId == confirmEmployerViewModel.EmployerAccountLegalEntityPublicHashedId
                                                                                      );

            if (relationship == null)
            {
                throw new InvalidOperationException(
                          $"Error creating cohort - operation not permitted for Provider: {providerId}, Employer Account {employerAccountId}, Legal Entity {confirmEmployerViewModel.EmployerAccountLegalEntityPublicHashedId} ");
            }

            var providerResponse = await Mediator.Send(new GetProviderQueryRequest { UKPRN = providerId });

            var employerAccountHashedId = HashingService.HashValue(employerAccountId);

            var accountResponse = await Mediator.Send(new GetEmployerAccountLegalEntitiesRequest
            {
                UserId          = userId,
                HashedAccountId = employerAccountHashedId
            });

            var legalEntity = accountResponse.LegalEntities.SingleOrDefault(x =>
                                                                            x.AccountLegalEntityPublicHashedId ==
                                                                            confirmEmployerViewModel.EmployerAccountLegalEntityPublicHashedId);

            if (legalEntity == null)
            {
                throw new InvalidOperationException(
                          $"Error getting Employer Account Legal entity for {confirmEmployerViewModel.EmployerAccountLegalEntityPublicHashedId}");
            }

            var createCommitmentRequest = new CreateCommitmentCommand
            {
                UserId     = userId,
                Commitment = new Commitment
                {
                    Reference                        = Guid.NewGuid().ToString().ToUpper(),
                    EmployerAccountId                = employerAccountId,
                    LegalEntityId                    = legalEntity.Code,
                    LegalEntityName                  = legalEntity.Name,
                    LegalEntityAddress               = legalEntity.RegisteredAddress,
                    LegalEntityOrganisationType      = (OrganisationType)legalEntity.Source,
                    AccountLegalEntityPublicHashedId = legalEntity.AccountLegalEntityPublicHashedId,
                    ProviderId                       = providerId,
                    ProviderName                     = providerResponse.ProvidersView.Provider.ProviderName,
                    CommitmentStatus                 = CommitmentStatus.New,
                    EditStatus                       = EditStatus.ProviderOnly,
                    ProviderLastUpdateInfo           = new LastUpdateInfo {
                        Name = signinUser.DisplayName, EmailAddress = signinUser.Email
                    }
                }
            };

            var response = await Mediator.Send(createCommitmentRequest);

            return(HashingService.HashValue(response.CommitmentId));
        }
        public void Arrange()
        {
            _permissionsResponse = new GetProviderRelationshipsWithPermissionQueryResponse
            {
                ProviderRelationships = new List <AccountProviderLegalEntityDto>
                {
                    new AccountProviderLegalEntityDto
                    {
                        AccountPublicHashedId            = _employerAccountPublicHashedId,
                        AccountId                        = _employerAccountId,
                        AccountLegalEntityId             = _employerAccountLegalEntityId,
                        AccountLegalEntityPublicHashedId = _employerAccountLegalEntityPublicHashedId
                    }
                }
            };

            _hashingService = new Mock <IHashingService>();
            _hashingService.Setup(x => x.HashValue(It.Is <long>(l => l == _apiResponse))).Returns("CohortRef");

            _publicHashingService = new Mock <IPublicHashingService>();
            _publicHashingService.Setup(x => x.DecodeValue(It.Is <string>(s => s == _employerAccountPublicHashedId))).Returns(_employerAccountId);
            _publicHashingService.Setup(x => x.DecodeValue(It.Is <string>(s => s == _employerAccountLegalEntityPublicHashedId)))
            .Returns(_employerAccountLegalEntityId);

            _mediator = new Mock <IMediator>();
            _mediator.Setup(x => x.Send(It.IsAny <GetProviderRelationshipsWithPermissionQueryRequest>(),
                                        new CancellationToken()))
            .ReturnsAsync(_permissionsResponse);

            _provider = new GetProviderQueryResponse
            {
                ProvidersView = new ProvidersView
                {
                    CreatedDate = new DateTime(2018, 11, 6),
                    Provider    = new Provider
                    {
                        ProviderName = "Test Provider"
                    }
                }
            };
            _mediator.Setup(x => x.Send(It.IsAny <GetProviderQueryRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(_provider);

            _legalEntity = new LegalEntity
            {
                Id = 1,
                AccountLegalEntityPublicHashedId = _employerAccountLegalEntityPublicHashedId,
                Code = "code",
                Name = "Test Legal Entity",
                RegisteredAddress = "Test Address",
                Source            = 1
            };
            _mediator.Setup(x =>
                            x.Send(It.IsAny <GetEmployerAccountLegalEntitiesRequest>(), It.IsAny <CancellationToken>())).ReturnsAsync(
                () => new GetEmployerAccountLegalEntitiesResponse
            {
                LegalEntities = new List <LegalEntity>
                {
                    _legalEntity
                }
            });

            _mediator.Setup(x => x.Send(It.IsAny <CreateCommitmentCommand>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new CreateCommitmentCommandResponse {
                CommitmentId = _apiResponse
            });

            _signInUserModel = new SignInUserModel {
                DisplayName = "DisplayName", Email = "*****@*****.**"
            };

            _confirmEmployerViewModel = new ConfirmEmployerViewModel
            {
                EmployerAccountLegalEntityPublicHashedId = _employerAccountLegalEntityPublicHashedId,
                EmployerAccountPublicHashedId            = _employerAccountPublicHashedId
            };

            _orchestrator = new CreateCohortOrchestrator(_mediator.Object,
                                                         _hashingService.Object,
                                                         Mock.Of <IProviderCommitmentsLogger>(),
                                                         _publicHashingService.Object);
        }
Exemplo n.º 22
0
 public static SignInUser ConvertToSignIn(this SignInUserModel model)
 => new SignInUser(model.Email, model.Password);
Exemplo n.º 23
0
        public ActionResult SignIn(SignInUserModel signUser, FormCollection form, string returnUrl)
        {
            if ( ModelState.IsValid )
            {
                UserRepository userRepository = new UserRepository();
                UserModel user = userRepository.GetByUsername( signUser.Login );
                if ( user != null && user.Password == signUser.Password.HashMD5() )
                {
                    if ( user.ActivationCode == null )
                    {
                        AuthenticateUser( signUser.Login, signUser.Remember );

                        if ( !String.IsNullOrEmpty( returnUrl ) )
                        {
                            return Redirect( returnUrl );
                        }
                        else
                        {
                            return RedirectToAction( "Index", "Home" );
                        }
                    }
                    else
                    {
                        ViewBag.ErrorMessage = "Your account hasn't been activated yet. " +
                            "Please visit the activation link from the e-mail message we've sent you.";
                        return View( signUser );
                    }
                }
                else
                {
                    ViewBag.ErrorMessage = "Specified username and/or password is incorrect.";
                    return View( signUser );
                }
            }

            return View( signUser );
        }
Exemplo n.º 24
0
        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
            });
        }
Exemplo n.º 25
0
        public async Task <SignInResult> SignInAsync(SignInUserModel signInUserModel)
        {
            var result = await _signInManager.PasswordSignInAsync(signInUserModel.Email, signInUserModel.Password, signInUserModel.RememberMe, true);

            return(result);
        }
Exemplo n.º 26
0
        public async Task <string> DeleteApprenticeship(string userId, DeleteConfirmationViewModel viewModel, SignInUserModel signinUser)
        {
            var apprenticeshipId = HashingService.DecodeValue(viewModel.HashedApprenticeshipId);

            Logger.Info($"Deleting apprenticeship {apprenticeshipId}", providerId: viewModel.ProviderId, apprenticeshipId: apprenticeshipId);

            var apprenticeship = await Mediator.Send(new GetApprenticeshipQueryRequest
            {
                ProviderId       = viewModel.ProviderId,
                ApprenticeshipId = apprenticeshipId
            });

            await Mediator.Send(new DeleteApprenticeshipCommand
            {
                UserId           = userId,
                ProviderId       = viewModel.ProviderId,
                ApprenticeshipId = apprenticeshipId,
                UserDisplayName  = signinUser.DisplayName,
                UserEmailAddress = signinUser.Email
            });

            return(apprenticeship.Apprenticeship.ApprenticeshipName);
        }
Exemplo n.º 27
0
 //Login
 public async Task <SignInResult> PasswordSignInAsync(SignInUserModel signInModel)
 {
     return(await _signInManager.PasswordSignInAsync(signInModel.Email, signInModel.Password, signInModel.RememberMe, false));
 }