コード例 #1
0
        public void ThenReturnsFalseIfEmployerIdIsNotInUrl(
            EmployerAccountRequirement requirement,
            AuthorizationFilterContext contextFilter,
            EmployerAccountAuthorizationHandler handler)
        {
            //Assign
            var employerIdentifier = new EmployerIdentifier
            {
                AccountId    = "1234",
                EmployerName = "Test Employer",
                Role         = "Owner"
            };

            var employerAccounts = new Dictionary <string, EmployerIdentifier> {
                { "1234", employerIdentifier }
            };
            var claim           = new Claim(EmployerClaims.AccountsClaimsTypeIdentifier, JsonConvert.SerializeObject(employerAccounts));
            var claimsPrinciple = new ClaimsPrincipal(new[] { new ClaimsIdentity(new[] { claim }) });

            var context = new AuthorizationHandlerContext(new[] { requirement }, claimsPrinciple, contextFilter);

            //Act
            var result = handler.IsEmployerAuthorised(context, false);

            //Assert
            Assert.IsFalse(result);
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var controller = filterContext.Controller as Controller;

            if (controller != null)
            {
                var user = controller.User;
                EmployerIdentifier account = null;
                var accountIdFromUrl       =
                    filterContext.RouteData.Values[RouteValues.EmployerAccountId]?.ToString().ToUpper();
                if (user.HasClaim(c => c.Type.Equals(EmployerPsrsClaims.AccountsClaimsTypeIdentifier)))
                {
                    var employerAccountClaim =
                        user.FindFirst(c => c.Type.Equals(EmployerPsrsClaims.AccountsClaimsTypeIdentifier));
                    var employerAccounts =
                        JsonConvert.DeserializeObject <Dictionary <string, EmployerIdentifier> >(
                            employerAccountClaim
                            ?.Value);
                    if (accountIdFromUrl != null)
                    {
                        account = employerAccounts[accountIdFromUrl];
                    }
                }
                controller.ViewBag.ZendeskApiData = new ZenDeskApiData
                {
                    Name         = user.Claims.First(c => c.Type.Equals(EmployerPsrsClaims.NameClaimsTypeIdentifier)).Value,
                    Email        = user.Claims.First(c => c.Type.Equals(EmployerPsrsClaims.EmailClaimsTypeIdentifier)).Value,
                    Organization = account?.EmployerName
                };
            }

            base.OnActionExecuting(filterContext);
        }
コード例 #3
0
        public void ThenFailsIfUserDoesNotHaveAValidRole(
            EmployerAccountRequirement requirement,
            AuthorizationFilterContext contextFilter,
            EmployerAccountAuthorizationHandler handler)
        {
            //Assign
            var employerIdentifier = new EmployerIdentifier
            {
                AccountId    = "1234",
                EmployerName = "Test Employer",
                Role         = "I'm not a role"
            };

            var employerAccounts = new Dictionary <string, EmployerIdentifier> {
                { "1234", employerIdentifier }
            };
            var claim           = new Claim(EmployerClaims.AccountsClaimsTypeIdentifier, JsonConvert.SerializeObject(employerAccounts));
            var claimsPrinciple = new ClaimsPrincipal(new[] { new ClaimsIdentity(new[] { claim }) });

            var context = new AuthorizationHandlerContext(new[] { requirement }, claimsPrinciple, contextFilter);
            var filter  = context.Resource as AuthorizationFilterContext;

            filter.RouteData.Values.Add(RouteValues.EmployerAccountId, 1234);

            //Act
            var result = handler.IsEmployerAuthorised(context, false);

            //Assert
            Assert.IsFalse(result);
        }
        public void SetUp()
        {
            _mockUrlHelper = new Mock <IUrlHelper>(MockBehavior.Strict);
            _employerAccountServiceMock = new Mock <IEmployerAccountService>(MockBehavior.Strict);
            _reportService = new Mock <IReportService>(MockBehavior.Strict);

            _periodServiceMock = new Mock <IPeriodService>(MockBehavior.Strict);
            _periodServiceMock.Setup(s => s.GetCurrentPeriod()).Returns(Period.FromInstantInPeriod(DateTime.UtcNow));

            _mockUserService = new Mock <IUserService>(MockBehavior.Strict);

            _controller =
                new QuestionController(
                    _reportService.Object,
                    _employerAccountServiceMock.Object,
                    null,
                    _periodServiceMock.Object,
                    _mockUserService.Object)
            {
                Url = _mockUrlHelper.Object
            };

            _employerIdentifier = new EmployerIdentifier()
            {
                AccountId = "ABCDE", EmployerName = "EmployerName"
            };

            _employerAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(It.IsAny <HttpContext>())).Returns(_employerIdentifier);
            _employerAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(null)).Returns(_employerIdentifier);
        }
コード例 #5
0
        public async Task ThenSucceedsIfEmployerIsAuthorised(
            EmployerAccountRequirement requirement,
            AuthorizationFilterContext contextFilter,
            EmployerAccountAuthorizationHandler handler)
        {
            //Assign
            var employerIdentifier = new EmployerIdentifier
            {
                AccountId    = "1234",
                EmployerName = "Test Employer",
                Role         = "Owner"
            };

            var employerAccounts = new Dictionary <string, EmployerIdentifier> {
                { "1234", employerIdentifier }
            };
            var claim           = new Claim(EmployerClaims.AccountsClaimsTypeIdentifier, JsonConvert.SerializeObject(employerAccounts));
            var claimsPrinciple = new ClaimsPrincipal(new[] { new ClaimsIdentity(new[] { claim }) });

            var context = new AuthorizationHandlerContext(new[] { requirement }, claimsPrinciple, contextFilter);
            var filter  = context.Resource as AuthorizationFilterContext;

            filter.RouteData.Values.Add(RouteValues.EmployerAccountId, 1234);

            //Act
            await handler.HandleAsync(context);

            //Assert
            Assert.IsTrue(context.HasSucceeded);
        }
コード例 #6
0
        protected override Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            var employerIdentifier = new EmployerIdentifier
            {
                Role         = "Owner",
                EmployerName = "Test",
                AccountId    = _employerAccountId
            };
            var dictionary = new Dictionary <string, EmployerIdentifier> {
                { _employerAccountId, employerIdentifier }
            };

            var claims = new[]
            {
                new Claim(EmployerClaims.IdamsUserIdClaimTypeIdentifier, Guid.NewGuid().ToString()),
                new Claim(EmployerClaims.AccountsClaimsTypeIdentifier, JsonConvert.SerializeObject(dictionary)),
            };
            var identity  = new ClaimsIdentity(claims, "IntegrationTest");
            var principal = new ClaimsPrincipal(identity);
            var ticket    = new AuthenticationTicket(principal, "IntegrationTest");

            var result = AuthenticateResult.Success(ticket);

            return(Task.FromResult(result));
        }
コード例 #7
0
        public void ThenReturnsTrueIfEmployerIsAuthorised(
            [Frozen] Mock <IEmployerAccountService> employerAccountService,
            EmployerAccountRequirement requirement,
            AuthorizationFilterContext contextFilter,
            EmployerAccountAuthorizationHandler handler)
        {
            //Assign
            var employerIdentifier = new EmployerIdentifier
            {
                AccountId    = "1234",
                EmployerName = "Test Employer",
                Role         = "Owner"
            };

            var employerAccounts = new Dictionary <string, EmployerIdentifier> {
                { "1234", employerIdentifier }
            };
            var claim           = new Claim(EmployerClaims.AccountsClaimsTypeIdentifier, JsonConvert.SerializeObject(employerAccounts));
            var claimsPrinciple = new ClaimsPrincipal(new[] { new ClaimsIdentity(new[] { claim }) });

            var context = new AuthorizationHandlerContext(new[] { requirement }, claimsPrinciple, contextFilter);
            var filter  = context.Resource as AuthorizationFilterContext;

            filter.RouteData.Values.Add(RouteValues.EmployerAccountId, 1234);

            //Act
            var result = handler.IsEmployerAuthorised(context, false);

            //Assert
            Assert.IsTrue(result);
        }
 protected override Task AuthorizeRequirementAgainstCurrentAccountIdEmployerIdentifierInformation(
     AuthorizationHandlerContext context,
     TestRequirement requirement,
     EmployerIdentifier employerIdentifier)
 {
     throw new System.NotImplementedException();
 }
コード例 #9
0
        public async Task ThenFailsIfEmployerIdIsNotInUrl(
            EmployerAccountRequirement requirement,
            AuthorizationFilterContext contextFilter,
            EmployerAccountAuthorizationHandler handler)
        {
            //Assign
            var employerIdentifier = new EmployerIdentifier
            {
                AccountId    = "1234",
                EmployerName = "Test Employer",
                Role         = "Owner"
            };

            var employerAccounts = new Dictionary <string, EmployerIdentifier> {
                { "1234", employerIdentifier }
            };
            var claim           = new Claim(EmployerClaims.AccountsClaimsTypeIdentifier, JsonConvert.SerializeObject(employerAccounts));
            var claimsPrinciple = new ClaimsPrincipal(new[] { new ClaimsIdentity(new[] { claim }) });

            var context = new AuthorizationHandlerContext(new[] { requirement }, claimsPrinciple, contextFilter);

            //Act
            await handler.HandleAsync(context);

            //Assert
            Assert.IsFalse(context.HasSucceeded);
        }
        private static bool CheckUserRoleForAccess(EmployerIdentifier employerIdentifier)
        {
            if (!Enum.TryParse <EmployerUserRole>(employerIdentifier.Role, true, out var userRole))
            {
                return(false);
            }

            return(userRole == EmployerUserRole.Owner || userRole == EmployerUserRole.Transactor);
        }
        protected override Task AuthorizeRequirementAgainstCurrentAccountIdEmployerIdentifierInformation(
            AuthorizationHandlerContext context,
            CanSubmitReport requirement,
            EmployerIdentifier employerIdentifier)
        {
            if (employerIdentifier.Role.Equals(EmployerPsrsRoleNames.Owner, StringComparison.OrdinalIgnoreCase))
            {
                context.Succeed(requirement);
            }

            return(Task.CompletedTask);
        }
        private async Task <string> GetUserRole(EmployerIdentifier employerAccount, string userId)
        {
            var accounts = await _accountApiClient.GetAccountUsers(employerAccount.AccountId);

            if (accounts == null || !accounts.Any())
            {
                return(null);
            }
            var teamMember = accounts.FirstOrDefault(c => String.Equals(c.UserRef, userId, StringComparison.CurrentCultureIgnoreCase));

            return(teamMember?.Role);
        }
        public static Action <ConfigurationExpression> ConfigureIoc()
        {
            return(config =>
            {
                config.Scan(_ =>
                {
                    _.AssemblyContainingType(typeof(Startup));
                    _.WithDefaultConventions();
                    _.SingleImplementationsOfInterface();
                });

                config.For <IWebConfiguration>().Use(new WebConfiguration
                {
                    SqlConnectionString = TestHelper.ConnectionString,
                });
                config.For <IReportService>().Use <ReportService>();
                config.For <IReportRepository>().Use <SQLReportRepository>().Ctor <string>().Is(TestHelper.ConnectionString);
                config.For <IEmployerAccountService>().Use <EmployerAccountService>();
                config.For <IFileProvider>().Singleton().Use(new PhysicalFileProvider(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));

                config.Scan(scanner =>
                {
                    scanner.AssemblyContainingType <GetReportRequest>();                       // Our assembly with requests & handlers
                    scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <>));  // Handlers with no response
                    scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <,>)); // Handlers with a response
                    scanner.ConnectImplementationsToTypesClosing(typeof(INotificationHandler <>));
                });

                config.For <SingleInstanceFactory>().Use <SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
                config.For <MultiInstanceFactory>().Use <MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));
                config.For <IMediator>().Use <Mediator>();
                config.For(typeof(ILogger <UserService>)).Use(Mock.Of <ILogger <UserService> >());
                config.For <IAuthorizationService>().Use(Mock.Of <IAuthorizationService>());

                var mockEmployerAccountService = new Mock <IEmployerAccountService>();
                var employerIdentifier = new EmployerIdentifier {
                    AccountId = "111", EmployerName = "222"
                };
                mockEmployerAccountService.Setup(e => e.GetCurrentEmployerAccountId(It.IsAny <HttpContext>())).Returns(employerIdentifier);
                config.For <IEmployerAccountService>().Use(mockEmployerAccountService.Object);

                var mapConfig = new MapperConfiguration(cfg => cfg.AddProfile <ReportMappingProfile>());
                var mapper = mapConfig.CreateMapper();
                config.For <IMapper>().Use(mapper);
            });
        }
        protected override void Given()
        {
            base.Given();


            _mockUrlHelper              = new Mock <IUrlHelper>();
            _mockReportService          = new Mock <IReportService>();
            _employeeAccountServiceMock = new Mock <IEmployerAccountService>();
            _userServiceMock            = new Mock <IUserService>();
            _periodServiceMock          = new Mock <IPeriodService>();

            MockAuthorizationService = new Mock <IAuthorizationService>();

            _periodServiceMock.Setup(s => s.GetCurrentPeriod()).Returns(Period.FromInstantInPeriod(DateTime.UtcNow));

            _mockReportService
            .Setup(
                m =>
                m.CanBeEdited(
                    It.IsAny <Report>()))
            .Returns(true);

            SUT = new ReportController(
                _mockReportService.Object,
                _employeeAccountServiceMock.Object,
                _userServiceMock.Object,
                null,
                _periodServiceMock.Object,
                MockAuthorizationService.Object,
                Mock.Of <IMediator>())
            {
                Url = _mockUrlHelper.Object
            };

            _employerIdentifier = new EmployerIdentifier()
            {
                AccountId = "ABCDE", EmployerName = "EmployerName"
            };

            _employeeAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(It.IsAny <HttpContext>()))
            .Returns(_employerIdentifier);
            _employeeAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(null))
            .Returns(_employerIdentifier);

            _userServiceMock.Setup(s => s.GetUserModel(null)).Returns(new UserModel());
        }
コード例 #15
0
        public async Task ThenSucceedsIfEmployerAccountIdIsFoundAfterAccountIdRefresh(
            [Frozen] Mock <IEmployerAccountService> employerAccountService,
            EmployerAccountRequirement requirement,
            AuthorizationFilterContext contextFilter,
            EmployerAccountAuthorizationHandler handler)
        {
            //Assign
            var employerAccounts     = new Dictionary <string, EmployerIdentifier>();
            var employerAccountClaim = new Claim(EmployerClaims.AccountsClaimsTypeIdentifier, JsonConvert.SerializeObject(employerAccounts));

            var userId    = Guid.NewGuid().ToString();
            var userClaim = new Claim(EmployerClaims.IdamsUserIdClaimTypeIdentifier, userId);

            var claimsPrinciple = new ClaimsPrincipal(new[] { new ClaimsIdentity(new[] { employerAccountClaim, userClaim }) });

            var context = new AuthorizationHandlerContext(new[] { requirement }, claimsPrinciple, contextFilter);
            var filter  = context.Resource as AuthorizationFilterContext;

            filter.RouteData.Values.Add(RouteValues.EmployerAccountId, 1234);


            var employerIdentifier = new EmployerIdentifier
            {
                AccountId    = "1234",
                EmployerName = "Test Corp",
                Role         = "Owner"
            };
            var refreshedEmployerAccounts = new Dictionary <string, EmployerIdentifier> {
                { "1234", employerIdentifier }
            };
            var refreshedEmployerAccountClaim = new Claim(EmployerClaims.AccountsClaimsTypeIdentifier, JsonConvert.SerializeObject(refreshedEmployerAccounts));

            employerAccountService.Setup(s => s.GetClaim(It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(refreshedEmployerAccountClaim);

            //Act
            await handler.HandleAsync(context);

            //Assert
            Assert.IsTrue(context.HasSucceeded);
        }
コード例 #16
0
        public void SetUp()
        {
            _mockUrlHelper = new Mock <IUrlHelper>(MockBehavior.Strict);
            _employerAccountServiceMock = new Mock <IEmployerAccountService>(MockBehavior.Strict);
            _reportService     = new Mock <IReportService>(MockBehavior.Strict);
            _periodServiceMock = new Mock <IPeriodService>(MockBehavior.Strict);
            _mockUserService   = new Mock <IUserService>(MockBehavior.Strict);


            _employerIdentifier = new EmployerIdentifier()
            {
                AccountId = "ABCDE", EmployerName = "EmployerName"
            };

            _employerAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(It.IsAny <HttpContext>()))
            .Returns(_employerIdentifier);
            _employerAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(null))
            .Returns(_employerIdentifier);

            _controller = new QuestionController(_reportService.Object, _employerAccountServiceMock.Object, null, _periodServiceMock.Object, _mockUserService.Object)
            {
                Url = _mockUrlHelper.Object
            };


            _currentValidAndNotSubmittedReport =
                new ReportBuilder()
                .WithValidSections()
                .WithEmployerId("ABCDEF")
                .ForCurrentPeriod()
                .WhereReportIsNotAlreadySubmitted()
                .Build();

            //_sectionModel = new SectionModel
            //{
            //    Report = ReportTestModelBuilder.CurrentReportWithValidSections("ABCDE"),
            //    CurrentSection = ReportTestModelBuilder.SectionOne.SubSections.FirstOrDefault()
            //};
        }
コード例 #17
0
        public Given_A_ReportController()
        {
            MockUrlHelper               = new Mock <IUrlHelper>(MockBehavior.Strict);
            _mockReportService          = new Mock <IReportService>(MockBehavior.Strict);
            _employeeAccountServiceMock = new Mock <IEmployerAccountService>(MockBehavior.Strict);
            _userServiceMock            = new Mock <IUserService>(MockBehavior.Strict);
            _periodServiceMock          = new Mock <IPeriodService>(MockBehavior.Strict);

            MockAuthorizationService = new Mock <IAuthorizationService>();

            MockMediatr = new Mock <IMediator>();

            _periodServiceMock.Setup(s => s.GetCurrentPeriod()).Returns(Period.FromInstantInPeriod(DateTime.UtcNow));

            _controller = new ReportController(
                _mockReportService.Object,
                _employeeAccountServiceMock.Object,
                _userServiceMock.Object,
                null,
                _periodServiceMock.Object,
                MockAuthorizationService.Object,
                MockMediatr.Object)
            {
                Url = MockUrlHelper.Object
            };

            _employerIdentifier = new EmployerIdentifier()
            {
                AccountId = "ABCDE", EmployerName = "EmployerName"
            };

            _employeeAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(It.IsAny <HttpContext>()))
            .Returns(_employerIdentifier);
            _employeeAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(null))
            .Returns(_employerIdentifier);

            _userServiceMock.Setup(s => s.GetUserModel(null)).Returns(new UserModel());
        }
コード例 #18
0
        protected override void Given()
        {
            _webConfiguration = new WebConfiguration();
            _webConfiguration.RootDomainUrl = "beetroot";

            _mockReportService          = new Mock <IReportService>(MockBehavior.Strict);
            _employeeAccountServiceMock = new Mock <IEmployerAccountService>(MockBehavior.Strict);
            _mockPeriodService          = new Mock <IPeriodService>();
            _authorizationServiceMock   = new Mock <IAuthorizationService>(MockBehavior.Strict);

            _mockPeriodService.Setup(r => r.GetCurrentPeriod()).Returns(CurrentPeriod);

            _employerIdentifier = new EmployerIdentifier()
            {
                AccountId = "ABCDE", EmployerName = "EmployerName"
            };
            _employeeAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(It.IsAny <HttpContext>()))
            .Returns(_employerIdentifier);
            _employeeAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(null))
            .Returns(_employerIdentifier);

            SUT = new HomeController(_mockReportService.Object, _employeeAccountServiceMock.Object, _webConfiguration, _mockPeriodService.Object, _authorizationServiceMock.Object);
        }
        public void SetUp()
        {
            CurrentValidNotSubmittedReport =
                new ReportBuilder()
                .WithValidSections()
                .WithEmployerId("VWZXYX")
                .ForCurrentPeriod()
                .WhereReportIsNotAlreadySubmitted()
                .Build();

            ReportList = new List <Report>(3);

            ReportList.Add(CurrentValidNotSubmittedReport);

            ReportList.Add(
                new ReportBuilder()
                .WithValidSections()
                .WithEmployerId("ABCDEF")
                .ForCurrentPeriod()
                .WhereReportIsNotAlreadySubmitted()
                .Build());

            ReportList.Add(
                new ReportBuilder()
                .WithValidSections()
                .WithEmployerId("ABCDEF")
                .ForPeriod(Period.FromInstantInPeriod(DateTime.UtcNow.AddYears(-1)))
                .WhereReportIsNotAlreadySubmitted()
                .Build());

            _mockUrlHelper              = new Mock <IUrlHelper>(MockBehavior.Strict);
            _mockReportService          = new Mock <IReportService>(MockBehavior.Strict);
            _employeeAccountServiceMock = new Mock <IEmployerAccountService>(MockBehavior.Strict);
            _userServiceMock            = new Mock <IUserService>(MockBehavior.Strict);
            _periodServiceMock          = new Mock <IPeriodService>(MockBehavior.Strict);

            _periodServiceMock.Setup(s => s.GetCurrentPeriod()).Returns(Period.FromInstantInPeriod(DateTime.UtcNow));

            _controller = new ReportController(
                _mockReportService.Object,
                _employeeAccountServiceMock.Object,
                _userServiceMock.Object,
                null,
                _periodServiceMock.Object,
                BuildAlwaysSucessMockAuthorizationService(),
                Mock.Of <IMediator>()
                )
            {
                Url = _mockUrlHelper.Object
            };

            _employerIdentifier = new EmployerIdentifier()
            {
                AccountId = "ABCDE", EmployerName = "EmployerName"
            };

            _employeeAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(It.IsAny <HttpContext>()))
            .Returns(_employerIdentifier);
            _employeeAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(null))
            .Returns(_employerIdentifier);

            _userServiceMock.Setup(s => s.GetUserModel(null)).Returns(new UserModel());



            //  _mockReportService.Setup(s => s.GetCurrentReportPeriod()).Returns("1617");
        }
        protected override void Given()
        {
            base.Given();


            _mockUrlHelper              = new Mock <IUrlHelper>();
            _mockReportService          = new Mock <IReportService>();
            _employeeAccountServiceMock = new Mock <IEmployerAccountService>();
            _userServiceMock            = new Mock <IUserService>();
            _periodServiceMock          = new Mock <IPeriodService>();

            MockAuthorizationService = new Mock <IAuthorizationService>();

            _periodServiceMock.Setup(s => s.GetCurrentPeriod()).Returns(Period.FromInstantInPeriod(DateTime.UtcNow));

            _mockReportService
            .Setup(
                m =>
                m.GetReport(
                    It.IsAny <string>(),
                    It.IsAny <string>()))
            .Returns(
                new Report
            {
                Submitted = true
            });

            _mockReportService
            .Setup(
                m =>
                m.CanBeEdited(
                    It.IsAny <Report>()))
            .Returns(
                false);

            _mockUrlHelper
            .Setup(
                m =>
                m.Action(
                    It.Is <UrlActionContext>(
                        ctx =>
                        ctx.Action.Equals("Index", StringComparison.OrdinalIgnoreCase) &&
                        ctx.Controller.Equals("Home", StringComparison.OrdinalIgnoreCase))
                    ))
            .Returns(
                ExpectedUrl);


            SUT = new ReportController(
                _mockReportService.Object,
                _employeeAccountServiceMock.Object,
                _userServiceMock.Object,
                null,
                _periodServiceMock.Object,
                MockAuthorizationService.Object,
                Mock.Of <IMediator>())
            {
                Url = _mockUrlHelper.Object
            };

            _employerIdentifier = new EmployerIdentifier()
            {
                AccountId = "ABCDE", EmployerName = "EmployerName"
            };

            _employeeAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(It.IsAny <HttpContext>()))
            .Returns(_employerIdentifier);
            _employeeAccountServiceMock.Setup(s => s.GetCurrentEmployerAccountId(null))
            .Returns(_employerIdentifier);

            _userServiceMock.Setup(s => s.GetUserModel(null)).Returns(new UserModel());
        }
        public bool IsEmployerAuthorised(AuthorizationHandlerContext context, bool allowAllUserRoles)
        {
            if (!(context.Resource is AuthorizationFilterContext mvcContext) || !mvcContext.RouteData.Values.ContainsKey(RouteValues.EmployerAccountId))
            {
                return(false);
            }


            var accountIdFromUrl     = mvcContext.RouteData.Values[RouteValues.EmployerAccountId].ToString().ToUpper();
            var employerAccountClaim = context.User.FindFirst(c => c.Type.Equals(EmployerClaims.AccountsClaimsTypeIdentifier));

            if (employerAccountClaim?.Value == null)
            {
                return(false);
            }

            Dictionary <string, EmployerIdentifier> employerAccounts;

            try
            {
                employerAccounts = JsonConvert.DeserializeObject <Dictionary <string, EmployerIdentifier> >(employerAccountClaim.Value);
            }
            catch (JsonReaderException e)
            {
                _logger.LogError(e, "Could not deserialize employer account claim for user", employerAccountClaim.Value);
                return(false);
            }

            EmployerIdentifier employerIdentifier = null;

            if (employerAccounts != null)
            {
                employerIdentifier = employerAccounts.ContainsKey(accountIdFromUrl)
                    ? employerAccounts[accountIdFromUrl] : null;
            }

            if (employerAccounts == null || !employerAccounts.ContainsKey(accountIdFromUrl))
            {
                if (!context.User.HasClaim(c => c.Type.Equals(EmployerClaims.IdamsUserIdClaimTypeIdentifier)))
                {
                    return(false);
                }

                var userClaim = context.User.Claims
                                .First(c => c.Type.Equals(EmployerClaims.IdamsUserIdClaimTypeIdentifier));

                var userId = userClaim.Value;

                var updatedAccountClaim = _accountsService.GetClaim(userId, EmployerClaims.AccountsClaimsTypeIdentifier).Result;

                var updatedEmployerAccounts = JsonConvert.DeserializeObject <Dictionary <string, EmployerIdentifier> >(updatedAccountClaim?.Value);

                userClaim.Subject.AddClaim(updatedAccountClaim);

                if (!updatedEmployerAccounts.ContainsKey(accountIdFromUrl))
                {
                    return(false);
                }

                employerIdentifier = updatedEmployerAccounts[accountIdFromUrl];
            }

            if (!mvcContext.HttpContext.Items.ContainsKey(ContextItemKeys.EmployerIdentifier))
            {
                mvcContext.HttpContext.Items.Add(ContextItemKeys.EmployerIdentifier, employerAccounts.GetValueOrDefault(accountIdFromUrl));
            }

            if (!allowAllUserRoles && !CheckUserRoleForAccess(employerIdentifier))
            {
                return(false);
            }

            return(true);
        }
 protected abstract Task AuthorizeRequirementAgainstCurrentAccountIdEmployerIdentifierInformation(AuthorizationHandlerContext context, TypeOfRequirement requirement, EmployerIdentifier employerIdentifier);