1
0
mirror of https://github.com/bitwarden/server.git synced 2025-07-04 01:22:50 -05:00

[EC-635] Extract organizationService.UpdateLicenseAsync to a command (#2408)

* move UpdateLicenseAsync from service to command
* create new SelfHostedOrganizationDetails view model and move license validation logic there
* move occupied seat count logic to database level
This commit is contained in:
Thomas Rittson
2023-02-24 07:54:19 +10:00
committed by GitHub
parent 7d0bba3a29
commit 4643f5960e
30 changed files with 967 additions and 239 deletions

View File

@ -0,0 +1,66 @@
#nullable enable
using System.Text.Json;
using Bit.Core.Entities;
using Bit.Core.Exceptions;
using Bit.Core.Models.Business;
using Bit.Core.Models.Data.Organizations;
using Bit.Core.OrganizationFeatures.OrganizationLicenses.Interfaces;
using Bit.Core.Services;
using Bit.Core.Settings;
using Bit.Core.Utilities;
namespace Bit.Core.OrganizationFeatures.OrganizationLicenses;
public class UpdateOrganizationLicenseCommand : IUpdateOrganizationLicenseCommand
{
private readonly ILicensingService _licensingService;
private readonly IGlobalSettings _globalSettings;
private readonly IOrganizationService _organizationService;
public UpdateOrganizationLicenseCommand(
ILicensingService licensingService,
IGlobalSettings globalSettings,
IOrganizationService organizationService)
{
_licensingService = licensingService;
_globalSettings = globalSettings;
_organizationService = organizationService;
}
public async Task UpdateLicenseAsync(SelfHostedOrganizationDetails selfHostedOrganization,
OrganizationLicense license, Organization? currentOrganizationUsingLicenseKey)
{
if (currentOrganizationUsingLicenseKey != null && currentOrganizationUsingLicenseKey.Id != selfHostedOrganization.Id)
{
throw new BadRequestException("License is already in use by another organization.");
}
var canUse = license.CanUse(_globalSettings, _licensingService, out var exception) &&
selfHostedOrganization.CanUseLicense(license, out exception);
if (!canUse)
{
throw new BadRequestException(exception);
}
await WriteLicenseFileAsync(selfHostedOrganization, license);
await UpdateOrganizationAsync(selfHostedOrganization, license);
}
private async Task WriteLicenseFileAsync(Organization organization, OrganizationLicense license)
{
var dir = $"{_globalSettings.LicenseDirectory}/organization";
Directory.CreateDirectory(dir);
await using var fs = new FileStream(Path.Combine(dir, $"{organization.Id}.json"), FileMode.Create);
await JsonSerializer.SerializeAsync(fs, license, JsonHelpers.Indented);
}
private async Task UpdateOrganizationAsync(SelfHostedOrganizationDetails selfHostedOrganizationDetails, OrganizationLicense license)
{
var organization = selfHostedOrganizationDetails.ToOrganization();
organization.UpdateFromLicense(license);
await _organizationService.ReplaceAndUpdateCacheAsync(organization);
}
}