Skip to content

Commit

Permalink
Merge pull request #60 from Lombiq/issue/OSOE-621
Browse files Browse the repository at this point in the history
OSOE-621: Feature for adding noindex, nofollow meta tags in non-production in Lombiq.Hosting.Tenants
  • Loading branch information
Psichorex authored May 24, 2023
2 parents 333781e + 5b7d5ef commit 99ba452
Show file tree
Hide file tree
Showing 17 changed files with 392 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using Lombiq.Tests.UI.Services;
using System.Threading.Tasks;

namespace Lombiq.Hosting.Tenants.EnvironmentRobots.Tests.UI.Extensions;

public static class ConfigurationExtensions
{
public static void SetEnvironmentRobotsOptionsConfiguration(
this OrchardCoreUITestExecutorConfiguration configuration,
bool isProduction) =>
configuration.OrchardCoreConfiguration.BeforeAppStart +=
(_, argumentsBuilder) =>
{
argumentsBuilder
.AddWithValue(
"OrchardCore:Lombiq_Hosting_Tenants_EnvironmentRobots:EnvironmentRobotsOptions:IsProduction",
value: isProduction);

return Task.CompletedTask;
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using Atata;
using Lombiq.Tests.UI.Extensions;
using Lombiq.Tests.UI.Services;
using OpenQA.Selenium;
using Shouldly;
using System.Threading.Tasks;

namespace Lombiq.Hosting.Tenants.EnvironmentRobots.Tests.UI.Extensions;

public static class TestCaseUITestContextExtensions
{
public static async Task TestRobotMetaTagIsMissingAsync(this UITestContext context, bool shouldBeMissing)
{
var metaTagXPath = By.XPath($"//meta[@name='robots' and @content='noindex, nofollow']").OfAnyVisibility();

await context.SignInDirectlyAsync();
await context.GoToHomePageAsync();

// The easiest way to check the response header during UI testing is with JavaScript by sending a GET request.
var isHeaderPresent = context.Driver.ExecuteAsyncScript(@"
const callback = arguments[arguments.length - 1];
const xhr = new XMLHttpRequest();
xhr.open('GET', window.location.href);
xhr.send();
xhr.onload = function() {
const xRobotsTag = xhr.getResponseHeader('X-Robots-Tag') ?? '';
callback(xRobotsTag.includes('noindex, nofollow'));
};");

if (shouldBeMissing)
{
context.Missing(metaTagXPath);
isHeaderPresent.ShouldBe(expected: false);
}
else
{
context.Exists(metaTagXPath);
isHeaderPresent.ShouldBe(expected: true);
}
}
}
13 changes: 13 additions & 0 deletions Lombiq.Hosting.Tenants.EnvironmentRobots.Tests.UI/License.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright © 2021, [Lombiq Technologies Ltd.](https://lombiq.com)

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

- Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<PropertyGroup>
<Title>Lombiq Hosting - Tenants EnvironmentRobots for Orchard Core - UI Test Extensions</Title>
<Authors>Lombiq Technologies</Authors>
<Copyright>Copyright © 2023, Lombiq Technologies Ltd.</Copyright>
<Description>Extension methods that test various features in Lombiq Hosting - Tenants EnvironmentRobots, with the help of Lombiq UI Testing Toolbox for Orchard Core. See the project website for detailed documentation.</Description>
<PackageIcon>NuGetIcon.png</PackageIcon>
<PackageTags>OrchardCore;Lombiq;AspNetCore;Multitenancy;SaaS</PackageTags>
<RepositoryUrl>https://github.com/Lombiq/Hosting-Tenants</RepositoryUrl>
<PackageProjectUrl>https://github.com/Lombiq/Hosting-Tenants/blob/dev/Lombiq.Hosting.Tenants.EnvironmentRobots.Tests.UI/Readme.md</PackageProjectUrl>
<PackageLicenseFile>License.md</PackageLicenseFile>
</PropertyGroup>

<ItemGroup Condition="'$(NuGetBuild)' != 'true'">
<ProjectReference Include="..\..\..\..\test\Lombiq.UITestingToolbox\Lombiq.Tests.UI\Lombiq.Tests.UI.csproj" />
</ItemGroup>

<ItemGroup Condition="'$(NuGetBuild)' == 'true'">
<PackageReference Include="Lombiq.Tests.UI" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
<None Include="License.md" Pack="true" PackagePath="" />
<None Include="NuGetIcon.png" Pack="true" PackagePath="" />
<None Include="Readme.md" />
</ItemGroup>

</Project>
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 7 additions & 0 deletions Lombiq.Hosting.Tenants.EnvironmentRobots.Tests.UI/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Lombiq Hosting - Tenants EnvironmentRobots for Orchard Core - UI Test Extensions

## About

Extension methods that test features in Lombiq Hosting - Tenants EnvironmentRobots, with the help of [Lombiq UI Testing Toolbox for Orchard Core](https://github.com/Lombiq/UI-Testing-Toolbox).

Call these from a UI test project to verify the module's basic features; as seen in [Open-Source Orchard Core Extensions](https://github.com/Lombiq/Open-Source-Orchard-Core-Extensions).
10 changes: 10 additions & 0 deletions Lombiq.Hosting.Tenants.EnvironmentRobots/Constants/FeatureNames.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace Lombiq.Hosting.Tenants.EnvironmentRobots.Constants;

public static class FeatureNames
{
public const string Module = "Lombiq.Hosting";

public const string Tenants = Module + "." + nameof(Tenants);

public const string EnvironmentRobots = Tenants + "." + nameof(EnvironmentRobots);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Lombiq.Hosting.Tenants.EnvironmentRobots.Models;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace Lombiq.Hosting.Tenants.EnvironmentRobots.Extensions;
public static class IHostEnvironmentEnvironmentRobotsExtensions
{
public static bool IsProductionWithConfiguration(
this IHostEnvironment hostEnvironment,
IOptions<EnvironmentRobotsOptions> options) =>
options.Value.IsProduction ?? hostEnvironment.IsProduction();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Lombiq.Hosting.Tenants.EnvironmentRobots.Extensions;
using Lombiq.Hosting.Tenants.EnvironmentRobots.Models;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using OrchardCore.ResourceManagement;

namespace Lombiq.Hosting.Tenants.EnvironmentRobots.Filters;

public class EnvironmentRobotsMetaTagFilter : IResultFilter
{
private readonly IHostEnvironment _hostEnvironment;
private readonly IOptions<EnvironmentRobotsOptions> _options;
private readonly IResourceManager _resourceManager;

public EnvironmentRobotsMetaTagFilter(
IHostEnvironment hostEnvironment,
IOptions<EnvironmentRobotsOptions> options,
IResourceManager resourceManager)
{
_hostEnvironment = hostEnvironment;
_options = options;
_resourceManager = resourceManager;
}

public void OnResultExecuting(ResultExecutingContext context)
{
if (!_hostEnvironment.IsProductionWithConfiguration(_options))
{
_resourceManager.RegisterMeta(new MetaEntry
{
Name = "robots",
Content = "noindex, nofollow",
});
}
}

public void OnResultExecuted(ResultExecutedContext context)
{
// Intentionally empty. Required by interface implementation only.
}
}
15 changes: 15 additions & 0 deletions Lombiq.Hosting.Tenants.EnvironmentRobots/License.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Copyright © 2022, [Lombiq Technologies Ltd.](https://lombiq.com)

All rights reserved.

For more information and requests about licensing please [contact us through our website](https://lombiq.com/contact-us).

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

- Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AddRazorSupportForMvc>true</AddRazorSupportForMvc>
<DefaultItemExcludes>$(DefaultItemExcludes);.git*;node_modules\**</DefaultItemExcludes>
</PropertyGroup>

<PropertyGroup>
<Title>Lombiq Hosting - Tenants EnvironmentRobots for Orchard Core</Title>
<Authors>Lombiq Technologies</Authors>
<Copyright>Copyright © 2023, Lombiq Technologies Ltd.</Copyright>
<Description>EnvironmentRobots for Orchard Core: This module contains the EnvironmentRobots feature, which prevents search bots from indexing non-production environments by adding a meta tag and a response header with noindex, nofollow values.</Description>
<PackageIcon>NuGetIcon.png</PackageIcon>
<PackageTags>OrchardCore;Lombiq;AspNetCore;Multitenancy;SaaS</PackageTags>
<RepositoryUrl>https://github.com/Lombiq/Hosting-Tenants</RepositoryUrl>
<PackageProjectUrl>https://github.com/Lombiq/Hosting-Tenants/blob/dev/Lombiq.Hosting.Tenants.EnvironmentRobots/Readme.md</PackageProjectUrl>
<PackageLicenseFile>License.md</PackageLicenseFile>
</PropertyGroup>

<ItemGroup>
<None Include="License.md" Pack="true" PackagePath="" />
<None Include="Readme.md" />
<None Include="NuGetIcon.png" Pack="true" PackagePath="" />
</ItemGroup>

<ItemGroup>
<None Remove="node_modules\**" />
<None Remove="Tests\**" />
</ItemGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="OrchardCore.Infrastructure.Abstractions" Version="1.5.0" />
<PackageReference Include="OrchardCore.Module.Targets" Version="1.5.0" />
<PackageReference Include="OrchardCore.ResourceManagement" Version="1.5.0" />
</ItemGroup>
</Project>
18 changes: 18 additions & 0 deletions Lombiq.Hosting.Tenants.EnvironmentRobots/Manifest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Lombiq.Hosting.Tenants.EnvironmentRobots.Constants;
using OrchardCore.Modules.Manifest;

[assembly: Module(
Name = "Lombiq Hosting - Tenants - Environment Robots",
Author = "Lombiq Technologies",
Website = "https://github.com/Lombiq/Hosting-Tenants",
Version = "0.0.1",
Description = "Prevents search bots from indexing non-production environments by adding a meta tag and a response header with noindex, nofollow values.",
Category = "Hosting"
)]

[assembly: Feature(
Id = FeatureNames.EnvironmentRobots,
Name = "Lombiq Hosting - Tenants - Environment Robots",
Category = "Hosting",
IsAlwaysEnabled = true
)]
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using Lombiq.Hosting.Tenants.EnvironmentRobots.Extensions;
using Lombiq.Hosting.Tenants.EnvironmentRobots.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Lombiq.Hosting.Tenants.EnvironmentRobots.Middlewares;

public class EnvironmentRobotsMiddleware
{
private readonly RequestDelegate _next;
private readonly IHostEnvironment _hostEnvironment;
private readonly IOptions<EnvironmentRobotsOptions> _options;

public EnvironmentRobotsMiddleware(
RequestDelegate next,
IHostEnvironment hostEnvironment,
IOptions<EnvironmentRobotsOptions> options)
{
_next = next;
_hostEnvironment = hostEnvironment;
_options = options;
}

public Task InvokeAsync(HttpContext context)
{
if (!_hostEnvironment.IsProductionWithConfiguration(_options))
{
var headerValue = context.Response.Headers["X-Robots-Tag"].FirstOrDefault() ?? string.Empty;

var directives = new List<string> { headerValue };

if (!headerValue.Contains("noindex"))
{
directives.Add("noindex");
}

if (!headerValue.Contains("nofollow"))
{
directives.Add("nofollow");
}

if (directives.Count > 1)
{
context.Response.Headers["X-Robots-Tag"] = $"{string.Join(", ", directives)}";
}
}

return _next(context);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Microsoft.Extensions.Hosting;

namespace Lombiq.Hosting.Tenants.EnvironmentRobots.Models;

/// <summary>
/// Further configuration options for the module.
/// </summary>
public class EnvironmentRobotsOptions
{
/// <summary>
/// Gets or sets a value indicating whether to add a meta tag and response header with noindex, nofollow values when
/// the app is not running in a production environment. It adds the tags when <see cref="IsProduction"/> is <see
/// langword="false"/>. When set it overrides <see cref="HostEnvironmentEnvExtensions.IsProduction"/>'s result,
/// which the module is using by default.
/// </summary>
public bool? IsProduction { get; set; }
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
32 changes: 32 additions & 0 deletions Lombiq.Hosting.Tenants.EnvironmentRobots/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Lombiq Hosting - Tenants Environment Robots for Orchard Core

[![Lombiq.Hosting.Tenants.EnvironmentRobots NuGet](https://img.shields.io/nuget/v/Lombiq.Hosting.Tenants.EnvironmentRobots?label=Lombiq.Hosting.Tenants.EnvironmentRobots)](https://www.nuget.org/packages/Lombiq.Hosting.Tenants.EnvironmentRobots/)

## About

A module that prevents search bots from indexing non-production environments.

## Documentation

This module contains the feature below.

### `Lombiq.Hosting.Tenants.EnvironmentRobots`

The module works by adding a `X-Robots-Tag` header with the value `noindex`, `nofollow` to the HTTP response of non-production apps. This instructs search engines not to index or follow the links on these pages. Additionally, the module also adds a `<meta name="robots" content="noindex, nofollow">` tag to the HTML head of non-production apps for the same purpose.

The module determines whether a app is non-production based on the `IsProduction` option in the `EnvironmentRobotsOptions` class. By default, this option is set to `null`, which means the module will use the `IHostEnvironment.IsProduction()` method to check the environment name. However, you can override this option by setting it to `true` or `false` in the `appsettings.json` file under the `Lombiq_Hosting_Tenants_EnvironmentRobots:EnvironmentRobotsOptions:IsProduction` section as follows:

```json
"OrchardCore": {
"Lombiq_Hosting_Tenants_EnvironmentRobots": {
"EnvironmentRobotsOptions": {
"IsProduction": true
}
}
}
```

To use the module, follow these steps:

- Enable the `Lombiq.Hosting.Tenants.EnvironmentRobots` feature from the admin dashboard.
- Optionally, configure the `IsProduction` option as described above.
Loading

0 comments on commit 99ba452

Please sign in to comment.