예제 #1
0
        public AuthControllerTests()
        {
            authClient            = A.Fake <IOpenIdConnectClient>();
            log                   = A.Fake <ILogger <AuthController> >();
            defaultVersionedFiles = A.Fake <IVersionedFiles>();
            defaultConfiguration  = A.Fake <IConfiguration>();
            var requestServices = A.Fake <IServiceProvider>();

            defaultAuthService = A.Fake <IAuthenticationService>();
            session            = new MockHttpSession();
            baseUrlService     = A.Fake <IBaseUrlService>();
            defaultUrlHelper   = A.Fake <IUrlHelper>();
            A.CallTo(() => defaultAuthService.SignInAsync(A <HttpContext> .Ignored, A <string> .Ignored, A <ClaimsPrincipal> .Ignored, A <AuthenticationProperties> .Ignored)).Returns(Task.CompletedTask);

            A.CallTo(() => requestServices.GetService(typeof(IAuthenticationService))).Returns(defaultAuthService);

            A.CallTo(() => baseUrlService.GetBaseUrl(A <HttpRequest> .Ignored, A <IUrlHelper> .Ignored))
            .Returns(baseAddress);

            defaultContext = new DefaultHttpContext
            {
                RequestServices = requestServices,
                Session         = session,
                Request         = { Headers = { new KeyValuePair <string, StringValues>("Referer", refererUrl) } },
            };

            defaultsettings = Options.Create(new AuthSettings
            {
                Audience           = "audience",
                ClientSecret       = "clientSecret123456",
                Issuer             = "issuer",
                DefaultRedirectUrl = "test",
                AuthDssEndpoint    = "test/{url}",
            });

            defaultSettings = Options.Create(new OpenIDConnectSettings
            {
                RedirectUrl        = "test/",
                SignOutRedirectUrl = "test/",
                Issuer             = "issuer",
                AuthdUrl           = "auth",
                AuthorizeUrl       = "AuthorizeUrl",
                ClientId           = "clientid",
                EndSessionUrl      = "Endsesison",
                JWK      = "jjjjjjfhfjjfjfjfjfhfjkhdfkhdfkjhskfhsldkjhfskdljfhsdlkfhsdflksdhsdlkfh",
                Exponent = "AQAB",
            });

            tokenHandler         = A.Fake <SecurityTokenHandler>();
            configurationManager = A.Fake <IConfigurationManager <OpenIdConnectConfiguration> >();
            A.CallTo(() => configurationManager.GetConfigurationAsync(CancellationToken.None)).Returns(
                new OpenIdConnectConfiguration
            {
                AuthorizationEndpoint = "auth",
                EndSessionEndpoint    = "end",
                Issuer = "issuer",
            });

            _urlHelper = A.Fake <IUrlHelper>();
        }
예제 #2
0
        public SitemapControllerTests()
        {
            defaultPathDataService = A.Fake <IPathDataService>();
            defaultLogger          = A.Fake <ILogger <SitemapController> >();
            defaultBaseUrlService  = A.Fake <IBaseUrlService>();

            var pathModels = new List <PathModel>
            {
                new PathModel
                {
                    SitemapURL = "http://SomeSitemapUrl.xyz",
                    IsOnline   = true,
                },
            };

            A.CallTo(() => defaultPathDataService.GetPaths()).Returns(pathModels);

            var user = A.Fake <ClaimsPrincipal>();

            A.CallTo(() => user.Identity.IsAuthenticated).Returns(true);

            defaultHttpContext = A.Fake <HttpContext>();
            defaultHttpContext.Request.Scheme = DummyScheme;
            defaultHttpContext.Request.Host   = new HostString(DummyHost);

            var fakeIdentity = new GenericIdentity("User");
            var principal    = new GenericPrincipal(fakeIdentity, null);

            A.CallTo(() => defaultHttpContext.User).Returns(principal);

            defaultUrlHelper = A.Fake <IUrlHelper>();
            A.CallTo(() => defaultUrlHelper.Action(A <UrlActionContext> .Ignored)).Returns(DummyHomeIndex);

            defaultTokenRetriever = A.Fake <IBearerTokenRetriever>();
            A.CallTo(() => defaultTokenRetriever.GetToken(A <HttpContext> .Ignored)).Returns("SomeToken");

            A.CallTo(() => defaultBaseUrlService.GetBaseUrl(A <HttpRequest> .Ignored, A <IUrlHelper> .Ignored))
            .Returns("http://SomeBaseUrl");

            defaultSitemapService = A.Fake <IApplicationSitemapService>();
            A.CallTo(() => defaultSitemapService.GetAsync(A <ApplicationSitemapModel> .Ignored))
            .Returns(Task.FromResult <IEnumerable <SitemapLocation> >(new List <SitemapLocation>()
            {
                new SitemapLocation
                {
                    Url      = "http://Sitemap.xml",
                    Priority = 1,
                },
            }));

            defaultController = new SitemapController(defaultPathDataService, defaultLogger, defaultTokenRetriever, defaultBaseUrlService, defaultSitemapService)
            {
                ControllerContext = new ControllerContext
                {
                    HttpContext = defaultHttpContext,
                },
                Url = defaultUrlHelper,
            };
        }
        public async Task <IJsonApiDocument> GetRelatedResourceDocument(string primaryResourceId, HttpRequestMessage request,
                                                                        CancellationToken cancellationToken)
        {
            var record = await GetRelatedRecord(primaryResourceId, cancellationToken);

            var baseUrl = _baseUrlService.GetBaseUrl(request);

            return(_singleResourceDocumentBuilder.BuildDocument(record, baseUrl, null, null)); // TODO: allow implementors to specify includes and metadata
        }
예제 #4
0
        private string GenerateSignOutUrl(string redirectUrl)
        {
            redirectUrl = string.IsNullOrEmpty(redirectUrl) ? Request.Headers["Referer"].ToString() : redirectUrl;

            if (IsAbsoluteUrl(redirectUrl))
            {
                return(redirectUrl);
            }

            return(baseUrlService.GetBaseUrl(Request, Url) + redirectUrl);
        }
예제 #5
0
        public async Task <IJsonApiDocument> BuildDocument(object obj, HttpRequestMessage requestMessage,
                                                           CancellationToken cancellationToken)
        {
            var type = obj.GetType();

            // TODO: test includes
            var includeExpressions = _includeExpressionExtractor.ExtractIncludeExpressions(requestMessage);

            var queryableInterfaces = type.GetInterfaces();
            var queryableInterface  =
                queryableInterfaces.FirstOrDefault(
                    i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IQueryable <>));

            if (queryableInterface != null)
            {
                var queryableElementType = queryableInterface.GenericTypeArguments[0];
                var buildDocumentMethod  =
                    _openBuildDocumentFromQueryableMethod.Value.MakeGenericMethod(queryableElementType);

                var sortExpressions = _sortExpressionExtractor.ExtractSortExpressions(requestMessage);

                dynamic materializedQueryTask = buildDocumentMethod.Invoke(_queryableResourceCollectionDocumentBuilder,
                                                                           new[] { obj, requestMessage, sortExpressions, cancellationToken, includeExpressions });

                return(await materializedQueryTask);
            }

            var isCollection          = false;
            var enumerableElementType = GetEnumerableElementType(type);

            if (enumerableElementType != null)
            {
                isCollection = true;
            }

            var linkBaseUrl = _baseUrlService.GetBaseUrl(requestMessage);

            if (isCollection)
            {
                var buildDocumentMethod =
                    _openBuildDocumentFromEnumerableMethod.Value.MakeGenericMethod(enumerableElementType);
                return
                    ((dynamic)buildDocumentMethod.Invoke(_resourceCollectionDocumentBuilder, new[] { obj, linkBaseUrl, new string[] { }, null, null }));
            }

            // Single resource object
            return(_singleResourceDocumentBuilder.BuildDocument(obj, linkBaseUrl, includeExpressions, null));
        }
        public async Task <IResourceCollectionDocument> BuildDocument <T>(IQueryable <T> query, HttpRequestMessage request, string[] sortExpressions, CancellationToken cancellationToken,
                                                                          string[] includes = null)
        {
            var filteredQuery = _filteringTransformer.Filter(query, request);
            var sortedQuery   = _sortingTransformer.Sort(filteredQuery, sortExpressions);

            var paginationResults = _paginationTransformer.ApplyPagination(sortedQuery, request);
            var paginatedQuery    = paginationResults.PagedQuery;

            var linkBaseUrl = _baseUrlService.GetBaseUrl(request);

            var results = await _enumerationTransformer.Enumerate(paginatedQuery, cancellationToken);

            var metadata = await GetDocumentMetadata(query, filteredQuery, sortedQuery, paginationResults, cancellationToken);

            return(_resourceCollectionDocumentBuilder.BuildDocument(results, linkBaseUrl, includes, metadata, null));
        }
        public virtual async Task <ISingleResourceDocument> GetRecordById(string id, HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var entityQuery     = GetByIdQuery(id);
            var includePaths    = GetIncludePathsForSingleResource() ?? new Expression <Func <TDto, object> >[] { };
            var jsonApiPaths    = includePaths.Select(ConvertToJsonKeyPath).ToArray();
            var mappedQuery     = GetMappedQuery(entityQuery, includePaths);
            var primaryResource = await _queryableEnumerationTransformer.FirstOrDefault(mappedQuery, cancellationToken);

            if (primaryResource == null)
            {
                throw JsonApiException.CreateForNotFound(
                          string.Format("No record exists with type `{0}` and ID `{1}`.", ResourceTypeName, id));
            }

            await OnResourceFetched(primaryResource, cancellationToken);

            var baseUrl = _baseUrlService.GetBaseUrl(request);

            return(_singleResourceDocumentBuilder.BuildDocument(primaryResource, baseUrl, jsonApiPaths, null));
        }
        private void AppendApplicationsSitemaps(Sitemap sitemap, IEnumerable <ApplicationSitemapModel> applicationSitemapModels)
        {
            var baseUrl = baseUrlService.GetBaseUrl(Request, Url);

            // get the task results as individual sitemaps and merge into one
            foreach (var applicationSitemapModel in applicationSitemapModels)
            {
                if (applicationSitemapModel.RetrievalTask.IsCompletedSuccessfully)
                {
                    logger.LogInformation($"{nameof(Action)}: Received child Sitemap for: {applicationSitemapModel.Path}");

                    var mappings = applicationSitemapModel.RetrievalTask.Result;

                    var sitemapLocations = mappings?.ToList();
                    if (sitemapLocations == null || !sitemapLocations.Any())
                    {
                        continue;
                    }

                    foreach (var mapping in sitemapLocations)
                    {
                        // rewrite the URL to swap any child application address prefix for the composite UI address prefix
                        var pathRootUri = new Uri(applicationSitemapModel.SitemapUrl);
                        var appBaseUrl  = $"{pathRootUri.Scheme}://{pathRootUri.Authority}";

                        if (mapping.Url.StartsWith(appBaseUrl, StringComparison.InvariantCultureIgnoreCase))
                        {
                            mapping.Url = mapping.Url.Replace(appBaseUrl, baseUrl, StringComparison.InvariantCultureIgnoreCase);
                        }

                        mapping.Priority = 0.5;
                    }

                    sitemap.AddRange(sitemapLocations);
                }
                else
                {
                    logger.LogError($"{nameof(Action)}: Error getting child Sitemap for: {applicationSitemapModel.Path}");
                }
            }
        }
예제 #9
0
        private void AppendApplicationsRobots(Robot robot, IEnumerable <ApplicationRobotModel> applicationRobotModels)
        {
            var baseUrl = baseUrlService.GetBaseUrl(Request, Url);

            // get the task results as individual robots and merge into one
            foreach (var applicationRobotModel in applicationRobotModels)
            {
                if (applicationRobotModel.RetrievalTask.IsCompletedSuccessfully)
                {
                    logger.LogInformation($"{nameof(Action)}: Received child robots.txt for: {applicationRobotModel.Path}");

                    var applicationRobotsText = applicationRobotModel.RetrievalTask.Result;

                    if (!string.IsNullOrWhiteSpace(applicationRobotsText))
                    {
                        AppendApplicationRobotData(applicationRobotModel, applicationRobotsText, baseUrl, robot);
                    }
                }
                else
                {
                    logger.LogError($"{nameof(Action)}: Error getting child robots.txt for: {applicationRobotModel.Path}");
                }
            }
        }
예제 #10
0
        public async Task <IActionResult> Action(ActionGetRequestModel requestViewModel)
        {
            var viewModel = versionedFiles.BuildDefaultPageViewModel(configuration);

            if (requestViewModel != null)
            {
                requestViewModel.Path = requestViewModel.Path?.ToLowerInvariant();
                requestViewModel.Data = requestViewModel.Data?.ToLowerInvariant();

                var errorRequestViewModel = new ActionGetRequestModel
                {
                    Path = AlertPathName,
                    Data = $"{(int)HttpStatusCode.NotFound}",
                };
                var requestItems = new[]
                {
                    requestViewModel,
                    errorRequestViewModel,
                    new ActionGetRequestModel
                    {
                        Path = AlertPathName,
                        Data = $"{(int)HttpStatusCode.InternalServerError}",
                    },
                };

                foreach (var requestItem in requestItems)
                {
                    try
                    {
                        logger.LogInformation($"{nameof(Action)}: Getting child response for: {requestItem.Path}/{requestItem.Data}");

                        await neo4JService.InsertNewRequest(Request).ConfigureAwait(false);

                        var application = await applicationService.GetApplicationAsync(requestItem).ConfigureAwait(false);

                        if (application?.AppRegistrationModel == null)
                        {
                            var errorString = $"The path '{requestItem.Path}' is not registered";

                            logger.LogWarning($"{nameof(Action)}: {errorString}");

                            Response.StatusCode = (int)HttpStatusCode.NotFound;
                        }
                        else if (application.AppRegistrationModel.ExternalURL != null)
                        {
                            logger.LogInformation($"{nameof(Action)}: Redirecting to external for: {application.AppRegistrationModel.Path}/{application.Article}");

                            return(Redirect(application.AppRegistrationModel.ExternalURL.ToString()));
                        }
                        else
                        {
                            await mapper.Map(application, viewModel).ConfigureAwait(false);

                            applicationService.RequestBaseUrl = baseUrlService.GetBaseUrl(Request, Url);

                            await applicationService.GetMarkupAsync(application, viewModel, Request.QueryString.Value).ConfigureAwait(false);

                            logger.LogInformation($"{nameof(Action)}: Received child response for: {application.AppRegistrationModel.Path}/{application.Article}");

                            if (string.Compare(application.AppRegistrationModel.Path, AlertPathName, true, CultureInfo.InvariantCulture) == 0 && int.TryParse(application.Article, out var statusCode))
                            {
                                Response.StatusCode = statusCode;
                            }

                            break;
                        }
                    }
                    catch (EnhancedHttpException ex)
                    {
                        var errorString = $"The content {ex.Url} responded with {ex.StatusCode}";

                        logger.LogWarning($"{nameof(Action)}: {errorString}");

                        Response.StatusCode        = (int)ex.StatusCode;
                        errorRequestViewModel.Data = $"{Response.StatusCode}";
                    }
                    catch (RedirectException ex)
                    {
                        var redirectTo = ex.Location?.OriginalString;

                        logger.LogInformation(ex, $"{nameof(Action)}: Redirecting from: {ex.OldLocation?.ToString()} to: {redirectTo}");

                        Response.Redirect(redirectTo, ex.IsPermenant);
                        break;
                    }
                }
            }

            return(View(MainRenderViewName, Map(viewModel)));
        }
예제 #11
0
 /// <summary>
 /// Gets the base URL for link creation from the current request
 /// </summary>
 protected string GetBaseUrlFromRequest(HttpRequestMessage request)
 {
     return(_baseUrlService.GetBaseUrl(request));
 }
예제 #12
0
        public async Task <IActionResult> Action(ActionGetRequestModel requestViewModel)
        {
            var viewModel = versionedFiles.BuildDefaultPageViewModel(configuration);

            if (requestViewModel != null)
            {
                var requestItems = GetRequestItemModels(requestViewModel);

                foreach (var requestItem in requestItems)
                {
                    try
                    {
                        logger.LogInformation($"{nameof(Action)}: Getting child response for: {requestItem.Path}");

                        var application = await applicationService.GetApplicationAsync(requestItem.Path).ConfigureAwait(false);

                        if (application?.Path == null)
                        {
                            var errorString = $"The path '{requestItem.Path}' is not registered";

                            logger.LogWarning($"{nameof(Action)}: {errorString}");

                            Response.StatusCode = (int)HttpStatusCode.NotFound;
                        }
                        else if (!string.IsNullOrWhiteSpace(application.Path.ExternalURL))
                        {
                            logger.LogInformation($"{nameof(Action)}: Redirecting to external for: {requestItem.Path}");

                            return(Redirect(application.Path.ExternalURL));
                        }
                        else
                        {
                            mapper.Map(application, viewModel);

                            applicationService.RequestBaseUrl = baseUrlService.GetBaseUrl(Request, Url);

                            await applicationService.GetMarkupAsync(application, requestItem.Data, viewModel, Request.QueryString.Value).ConfigureAwait(false);

                            logger.LogInformation($"{nameof(Action)}: Received child response for: {requestItem.Path}");

                            if (string.Compare(requestItem.Path, AlertPathName, true, CultureInfo.InvariantCulture) == 0 && int.TryParse(requestItem.Data, out var statusCode))
                            {
                                Response.StatusCode = statusCode;
                            }

                            break;
                        }
                    }
                    catch (EnhancedHttpException ex)
                    {
                        var errorString = $"The content {ex.Url} responded with {ex.StatusCode}";

                        logger.LogWarning($"{nameof(Action)}: {errorString}");

                        Response.StatusCode = (int)ex.StatusCode;
                        requestItems.First(m => m.Data == $"{(int)HttpStatusCode.NotFound}").Data = $"{Response.StatusCode}";
                    }
                    catch (RedirectException ex)
                    {
                        var redirectTo = ex.Location?.OriginalString;

                        logger.LogInformation(ex, $"{nameof(Action)}: Redirecting from: {ex.OldLocation?.ToString()} to: {redirectTo}");

                        Response.Redirect(redirectTo, ex.IsPermenant);
                    }
                }
            }

            return(View(MainRenderViewName, Map(viewModel)));
        }