Skip to content

Commit

Permalink
Merge pull request #53 from Lombiq/issue/NEST-422
Browse files Browse the repository at this point in the history
NEST-422: Media storage quota management for OC sites
  • Loading branch information
DemeSzabolcs authored Apr 19, 2023
2 parents a3018a3 + 3ec66f7 commit 9dd7732
Show file tree
Hide file tree
Showing 25 changed files with 551 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Lombiq.Tests.UI.Services;
using System;
using System.Linq;
using System.Threading.Tasks;

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

public static class MediaStorageManagementExtensions
{
public static void SetMediaStorageManagementOptionsForUITest(
this OrchardCoreUITestExecutorConfiguration configuration,
long maximumSpace)
{
configuration.OrchardCoreConfiguration.BeforeAppStart +=
(_, argumentsBuilder) =>
{
argumentsBuilder
.AddWithValue(
"OrchardCore:Lombiq_Hosting_Tenants_MediaStorageManagement:Media_Storage_Management_Options:MaximumSpace",
maximumSpace);

return Task.CompletedTask;
};

configuration.AssertBrowserLog =
logEntries =>
{
// By default, apart from some commonly known exceptions, the browser log should be empty. However,
// Media Storage Quota feature causes a 400 on upload if the file is over the limit, so we need to make
// sure not to fail on that.
var messagesWithoutToggle = logEntries.Where(logEntry =>
!logEntry.Message.ContainsOrdinalIgnoreCase(
@"/Admin/Media/Upload - Failed to load resource: the server responded with a status of 400"));
OrchardCoreUITestExecutorConfiguration.AssertBrowserLogIsEmpty(messagesWithoutToggle);
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Lombiq.Tests.UI.Extensions;
using Lombiq.Tests.UI.Services;
using OpenQA.Selenium;
using Shouldly;
using System.Threading.Tasks;

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

public static class TestCaseUITestContextExtensions
{
public static async Task TestMediaStorageManagementBehaviorAsync(this UITestContext context)
{
await context.SignInDirectlyAsync();

await context.GoToAdminRelativeUrlAsync("/Media");

context.UploadSamplePngByIdOfAnyVisibility("fileupload"); // #spell-check-ignore-line

// Workaround for pending uploads, until you make an action the page is stuck on "Uploads Pending".
context.WaitForPageLoad();
await context.ClickReliablyOnAsync(By.CssSelector("body"));
await context.ClickReliablyOnAsync(By.CssSelector(".text-danger"));
context.Get(By.CssSelector(".error-message")).Text.ShouldContain("Error: You may only store");
}
}
13 changes: 13 additions & 0 deletions Lombiq.Hosting.Tenants.MediaStorageManagement.Tests.UI/License.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright © 2023, [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,39 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<PropertyGroup>
<Title>Lombiq Hosting - Tenants Media Storage Management - 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 Media Storage Management, 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;Tenants;LombiqHostingSuite;Shouldly;xUnit;UITesting;Testing</PackageTags>
<RepositoryUrl>https://github.com/Lombiq/Hosting-Tenants</RepositoryUrl>
<PackageProjectUrl>https://github.com/Lombiq/Hosting-Tenants/blob/dev/Lombiq.Hosting.Tenants.MediaStorageManagement.Tests.UI/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 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>

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

## About

Extension methods that test various features in Lombiq Hosting - Tenants Media Storage Management, 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).

## Contributing and support

Bug reports, feature requests, comments, questions, code contributions and love letters are warmly welcome. You can send them to us via GitHub issues and pull requests. Please adhere to our [open-source guidelines](https://lombiq.com/open-source-guidelines) while doing so.

This project is developed by [Lombiq Technologies](https://lombiq.com/). Commercial-grade support is available through Lombiq.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Lombiq.Hosting.Tenants.MediaStorageManagement.Constants;

public static class FeatureNames
{
public const string MediaStorageManagement = "Lombiq.Hosting.Tenants.MediaStorageManagement";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace Lombiq.Hosting.Tenants.MediaStorageManagement.Constants;

public static class MediaStorageManagementOptionsConstants
{
/// <summary>
/// Default MaximumStorageQuota in bytes representing 1GB.
/// </summary>
public const long MaximumStorageQuota = 1_073_741_824;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Lombiq.Hosting.Tenants.MediaStorageManagement.Service;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;

namespace Lombiq.Hosting.Tenants.MediaStorageManagement.Filters;

public class MediaStorageQuotaActionFilter : IAsyncAuthorizationFilter, IOrderedFilter
{
public int Order => 950; // Should be above the InternalMediaSizeFilter (900) to override its value.

public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
var maxFileSize = await context
.HttpContext
.RequestServices
.GetRequiredService<IMediaStorageQuotaService>()
.GetRemainingMediaSpaceQuotaLeftAsync();

var formOptions = new FormOptions
{
MultipartBodyLengthLimit = maxFileSize,
};

context.HttpContext.Features.Set<IFormFeature>(new FormFeature(context.HttpContext.Request, formOptions));

var maxRequestBodySizeFeature = context.HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>();
if (maxRequestBodySizeFeature is { IsReadOnly: false })
{
maxRequestBodySizeFeature.MaxRequestBodySize = maxFileSize;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using Lombiq.Hosting.Tenants.MediaStorageManagement.Service;
using Lombiq.Hosting.Tenants.MediaStorageManagement.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Layout;
using OrchardCore.Media.Controllers;
using OrchardCore.Mvc.Core.Utilities;
using System.Threading.Tasks;

namespace Lombiq.Hosting.Tenants.MediaStorageManagement.Filters;

public class UploadFileSizeShapeFilter : IAsyncResultFilter
{
private readonly IShapeFactory _shapeFactory;
private readonly ILayoutAccessor _layoutAccessor;
private readonly IMediaStorageQuotaService _mediaStorageQuotaService;

public UploadFileSizeShapeFilter(
IShapeFactory shapeFactory,
ILayoutAccessor layoutAccessor,
IMediaStorageQuotaService mediaStorageQuotaService)
{
_shapeFactory = shapeFactory;
_layoutAccessor = layoutAccessor;
_mediaStorageQuotaService = mediaStorageQuotaService;
}

public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
if (!context.IsAdmin())
{
await next();
return;
}

var actionRouteController = context.ActionDescriptor.RouteValues["Controller"];
var actionRouteArea = context.ActionDescriptor.RouteValues["Area"];
var actionRouteValue = context.ActionDescriptor.RouteValues["Action"];

if (actionRouteController == typeof(AdminController).ControllerName() &&
actionRouteArea == $"{nameof(OrchardCore)}.{nameof(OrchardCore.Media)}" &&
actionRouteValue is nameof(AdminController.Index) &&
context.Result is ViewResult)
{
var layout = await _layoutAccessor.GetLayoutAsync();
var contentZone = layout.Zones["Footer"];
var maximumSpace = _mediaStorageQuotaService.MaxSpaceForTenantInMegabytes();
await contentZone.AddAsync(await _shapeFactory.CreateAsync<UploadFileSizeViewModel>(
"UploadFileSize",
viewModel => viewModel.MaximumSpace = maximumSpace));
}

await next();
}
}
13 changes: 13 additions & 0 deletions Lombiq.Hosting.Tenants.MediaStorageManagement/License.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright © 2023, [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,52 @@
<Project Sdk="Microsoft.NET.Sdk.Razor">

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

<PropertyGroup>
<Title>Lombiq Hosting - Tenants Media Storage Management for Orchard Core</Title>
<Authors>Lombiq Technologies</Authors>
<Copyright>Copyright © 2023, Lombiq Technologies Ltd.</Copyright>
<Description>Lombiq Hosting - Tenants Media Storage Management for Orchard Core: With the help of this module, you can set restrictions regarding maximum media space per tenant. 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.MediaStorageManagement/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.Module.Targets" Version="1.5.0" />
<PackageReference Include="OrchardCore.Media" Version="1.5.0" />
<PackageReference Include="OrchardCore.ResourceManagement" Version="1.5.0" />
<PackageReference Include="OrchardCore.DisplayManagement" Version="1.5.0" />
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
</ItemGroup>

<ItemGroup Condition="'$(NuGetBuild)' != 'true'">
<ProjectReference Include="..\..\..\Libraries\Lombiq.HelpfulLibraries\Lombiq.HelpfulLibraries.OrchardCore\Lombiq.HelpfulLibraries.OrchardCore.csproj" />
</ItemGroup>

<ItemGroup Condition="'$(NuGetBuild)' == 'true'">
<PackageReference Include="Lombiq.HelpfulLibraries.OrchardCore" Version="5.1.1" />
</ItemGroup>

</Project>
24 changes: 24 additions & 0 deletions Lombiq.Hosting.Tenants.MediaStorageManagement/Manifest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using OrchardCore.Modules.Manifest;
using static Lombiq.Hosting.Tenants.MediaStorageManagement.Constants.FeatureNames;

[assembly: Module(
Name = "Lombiq Hosting - Tenants Media Storage Management",
Author = "Lombiq Technologies",
Website = "https://github.com/Lombiq/Hosting-Tenants",
Version = "0.0.1",
Description = "Ability to configure storage quota for tenants."
)]

[assembly: Feature(
Id = MediaStorageManagement,
Name = "Lombiq Hosting - Tenants Media Storage Management - Quota Management",
Description = "Ability to configure storage quota for tenants.",
Category = "Hosting",
IsAlwaysEnabled = true,
Dependencies = new[]
{
"OrchardCore.Media",
"OrchardCore.DisplayManagement",
"OrchardCore.ResourceManagement",
}
)]
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
55 changes: 55 additions & 0 deletions Lombiq.Hosting.Tenants.MediaStorageManagement/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Lombiq Hosting - Tenants Media Storage Management for Orchard Core

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

## About

With the help of this module, you can set restrictions regarding maximum media space per tenant.

Do you want to quickly try out this project and see it in action? Check it out in our [Open-Source Orchard Core Extensions](https://github.com/Lombiq/Open-Source-Orchard-Core-Extensions) full Orchard Core solution and also see our other useful Orchard Core-related open-source projects!

## Documentation

This module currently contains one feature:

- `Lombiq.Hosting.Tenants.MediaStorageManagement`

### `Lombiq.Hosting.Tenants.MediaStorageManagement`

With this module, you can specify how much space would you like to limit each tenant's storage space. The default is 1GB. If you want to set it to 2GB e.g. you can do it in bytes as an environment variable or in `appsettings.json` as follows:

```json
"OrchardCore": {
"Lombiq_Hosting_Tenants_MediaStorageManagement": {
"Media_Storage_Management_Options": {
"MaximumSpace": 2147483648
}
}
}
```

Tenant based configuration can be defined as the following, for more details read the [Orchard Core documentation](https://docs.orchardcore.net/en/main/docs/reference/core/Configuration/#tenant-postconfiguration).

```json
"OrchardCore": {
"TenantName": {
"Lombiq_Hosting_Tenants_MediaStorageManagement": {
"Media_Storage_Management_Options": {
"MaximumSpace": 2147483648
}
}
}
}
```

## Dependencies

This module has the following dependencies:

- [Lombiq Helpful Libraries for Orchard Core](https://github.com/Lombiq/Helpful-Libraries)

## Contributing and support

Bug reports, feature requests, comments, questions, code contributions and love letters are warmly welcome. You can send them to us via GitHub issues and pull requests. Please adhere to our [open-source guidelines](https://lombiq.com/open-source-guidelines) while doing so.

This project is developed by [Lombiq Technologies](https://lombiq.com/). Commercial-grade support is available through Lombiq.
Loading

0 comments on commit 9dd7732

Please sign in to comment.