Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OSOE-621: Feature for adding noindex, nofollow meta tags in non-production in Lombiq.Hosting.Tenants #60

Merged
merged 23 commits into from
May 24, 2023
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
495e3ce
Adding new project
DemeSzabolcs May 18, 2023
3bd4cc8
Adding the middleware
DemeSzabolcs May 18, 2023
6d60184
Refactoring middleware and Startup.cs
DemeSzabolcs May 18, 2023
5faa718
Simplifying middleware
DemeSzabolcs May 18, 2023
6fb7e02
Renaming module to EnvironmentRobots
DemeSzabolcs May 18, 2023
4807ebb
Refactoring module by also adding meta filter
DemeSzabolcs May 18, 2023
bc76da6
Adding Readme.md
DemeSzabolcs May 18, 2023
bf9bf8a
Updating Readme
DemeSzabolcs May 18, 2023
8134710
Merge remote-tracking branch 'origin/dev' into issue/OSOE-621
DemeSzabolcs May 18, 2023
782b304
Fixing Readme errors
DemeSzabolcs May 18, 2023
f0c5891
Tweaking documentation
DemeSzabolcs May 18, 2023
e77e942
Adding EnvironmentRobots Test project
DemeSzabolcs May 19, 2023
ee378b1
Adding TestCaseUITestContextExtensions and ConfigurationExtensions
DemeSzabolcs May 19, 2023
b7da742
Typo
DemeSzabolcs May 19, 2023
b6ad7ec
Renaming variable in TestCaseUITestContextExtensions
DemeSzabolcs May 19, 2023
387ef03
Correcting Readme link
DemeSzabolcs May 19, 2023
aa5731c
Typo
DemeSzabolcs May 19, 2023
857941b
Refactoring middleware so it respects existing X Robots Tag
DemeSzabolcs May 19, 2023
f8b672b
Correcting Readme.md
DemeSzabolcs May 21, 2023
efe4942
Minor refactorings
DemeSzabolcs May 21, 2023
2579c4d
Update Lombiq.Hosting.Tenants.EnvironmentRobots.Tests.UI/Readme.md
DemeSzabolcs May 22, 2023
4a2a9ca
Update Lombiq.Hosting.Tenants.EnvironmentRobots/Middlewares/Environme…
DemeSzabolcs May 22, 2023
5b7d5ef
Minor refactorings
DemeSzabolcs May 22, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();

// Checking the response header with JavaScript.
Psichorex marked this conversation as resolved.
Show resolved Hide resolved
var isHeaderPresent = context.Driver.ExecuteAsyncScript(@"
var callback = arguments[arguments.length - 1];
Psichorex marked this conversation as resolved.
Show resolved Hide resolved
var xhr = new XMLHttpRequest();
xhr.open('GET', window.location.href);
xhr.send();
xhr.onload = function() {
var xRobotsTag = xhr.getResponseHeader('X-Robots-Tag') ?? '';
callback(xRobotsTag.includes ('noindex, nofollow'));
Psichorex marked this conversation as resolved.
Show resolved Hide resolved
};");

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 tests features in Lombiq Hosting - Tenants EnvironmentRobots, with the help of [Lombiq UI Testing Toolbox for Orchard Core](https://github.com/Lombiq/UI-Testing-Toolbox).
DemeSzabolcs marked this conversation as resolved.
Show resolved Hide resolved

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();
Psichorex marked this conversation as resolved.
Show resolved Hide resolved
Psichorex marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
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 left empty, we don't need the function, but we need to add it because of the interface
Psichorex marked this conversation as resolved.
Show resolved Hide resolved
// implementation.
}
}
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,47 @@
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>();

if (!headerValue.Contains("noindex")) directives.Add("noindex");
Psichorex marked this conversation as resolved.
Show resolved Hide resolved
if (!headerValue.Contains("nofollow")) directives.Add("nofollow");

if (directives.Any())
{
context.Response.Headers["X-Robots-Tag"] = $"{headerValue}, {string.Join(", ", directives)}";
DemeSzabolcs marked this conversation as resolved.
Show resolved Hide resolved
}
}

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; }
Psichorex marked this conversation as resolved.
Show resolved Hide resolved
}
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