mirror of
https://github.com/bitwarden/server.git
synced 2025-07-01 16:12:49 -05:00
Organization autoscaling (#1585)
* Add autoscale fields to Organization * Add autoscale setting changes * Autoscale organizations updates InviteUsersAsync to support all invite sources. sends an email to org owners when organization autoscaled * All organizations autoscale Disabling autoscaling can be done by setting max seats to current seats. We only warn about autoscaling on the first autoscaling event. * Fix tests * Bug fixes * Simplify subscription update logic * Void invoices that fail to delete Stripe no longer allows deletion of draft invoices that were created as part of subscription updates. It's necessary to void out these invoices without sending tem to the client. * Notify org owners when their subscription runs out of seats * Use datetime for notifications Allows for later re-sending email if we want to periodically remind owners * Do not update subscription if it already matches new quatity * Include all migrations * Remove unnecessary inline styling * SubscriptionUpdate handles update decisions * Remove unnecessary html setter * PR review * Use minimum access for class methods
This commit is contained in:
@ -20,6 +20,8 @@ namespace Bit.Core.Services
|
||||
Task SendMasterPasswordHintEmailAsync(string email, string hint);
|
||||
Task SendOrganizationInviteEmailAsync(string organizationName, OrganizationUser orgUser, ExpiringToken token);
|
||||
Task BulkSendOrganizationInviteEmailAsync(string organizationName, IEnumerable<(OrganizationUser orgUser, ExpiringToken token)> invites);
|
||||
Task SendOrganizationMaxSeatLimitReachedEmailAsync(Organization organization, int maxSeatCount, IEnumerable<string> ownerEmails);
|
||||
Task SendOrganizationAutoscaledEmailAsync(Organization organization, int initialSeatCount, IEnumerable<string> ownerEmails);
|
||||
Task SendOrganizationAcceptedEmailAsync(Organization organization, string userIdentifier, IEnumerable<string> adminEmails);
|
||||
Task SendOrganizationConfirmedEmailAsync(string organizationName, string email);
|
||||
Task SendOrganizationUserRemovedForPolicyTwoStepEmailAsync(string organizationName, string email);
|
||||
|
@ -17,7 +17,8 @@ namespace Bit.Core.Services
|
||||
Task ReinstateSubscriptionAsync(Guid organizationId);
|
||||
Task<Tuple<bool, string>> UpgradePlanAsync(Guid organizationId, OrganizationUpgrade upgrade);
|
||||
Task<string> AdjustStorageAsync(Guid organizationId, short storageAdjustmentGb);
|
||||
Task<string> AdjustSeatsAsync(Guid organizationId, int seatAdjustment);
|
||||
Task UpdateSubscription(Guid organizationId, int seatAdjustment, int? maxAutoscaleSeats);
|
||||
Task<string> AdjustSeatsAsync(Guid organizationId, int seatAdjustment, DateTime? prorationDate = null);
|
||||
Task VerifyBankAsync(Guid organizationId, int amount1, int amount2);
|
||||
Task<Tuple<Organization, OrganizationUser>> SignUpAsync(OrganizationSignup organizationSignup, bool provider = false);
|
||||
Task<Tuple<Organization, OrganizationUser>> SignUpAsync(OrganizationLicense license, User owner,
|
||||
@ -31,9 +32,10 @@ namespace Bit.Core.Services
|
||||
Task UpdateAsync(Organization organization, bool updateBilling = false);
|
||||
Task UpdateTwoFactorProviderAsync(Organization organization, TwoFactorProviderType type);
|
||||
Task DisableTwoFactorProviderAsync(Organization organization, TwoFactorProviderType type);
|
||||
Task<List<OrganizationUser>> InviteUsersAsync(Guid organizationId, Guid? invitingUserId,
|
||||
IEnumerable<(OrganizationUserInvite invite, string externalId)> invites);
|
||||
Task<OrganizationUser> InviteUserAsync(Guid organizationId, Guid? invitingUserId, string email,
|
||||
OrganizationUserType type, bool accessAll, string externalId, IEnumerable<SelectionReadOnly> collections);
|
||||
Task<List<OrganizationUser>> InviteUserAsync(Guid organizationId, Guid? invitingUserId, string externalId, OrganizationUserInvite orgUserInvite);
|
||||
Task<IEnumerable<Tuple<OrganizationUser, string>>> ResendInvitesAsync(Guid organizationId, Guid? invitingUserId, IEnumerable<Guid> organizationUsersId);
|
||||
Task ResendInviteAsync(Guid organizationId, Guid? invitingUserId, Guid organizationUserId);
|
||||
Task<OrganizationUser> AcceptUserAsync(Guid organizationUserId, User user, string token,
|
||||
|
@ -144,6 +144,35 @@ namespace Bit.Core.Services
|
||||
await _mailDeliveryService.SendEmailAsync(message);
|
||||
}
|
||||
|
||||
public async Task SendOrganizationAutoscaledEmailAsync(Organization organization, int initialSeatCount, IEnumerable<string> ownerEmails)
|
||||
{
|
||||
var message = CreateDefaultMessage($"{organization.Name} Seat Count Has Increased", ownerEmails);
|
||||
var model = new OrganizationSeatsAutoscaledViewModel
|
||||
{
|
||||
OrganizationId = organization.Id,
|
||||
InitialSeatCount = initialSeatCount,
|
||||
CurrentSeatCount = organization.Seats.Value,
|
||||
};
|
||||
|
||||
await AddMessageContentAsync(message, "OrganizationSeatsAutoscaled", model);
|
||||
message.Category = "OrganizationSeatsAutoscaled";
|
||||
await _mailDeliveryService.SendEmailAsync(message);
|
||||
}
|
||||
|
||||
public async Task SendOrganizationMaxSeatLimitReachedEmailAsync(Organization organization, int maxSeatCount, IEnumerable<string> ownerEmails)
|
||||
{
|
||||
var message = CreateDefaultMessage($"{organization.Name} Seat Limit Reached", ownerEmails);
|
||||
var model = new OrganizationSeatsMaxReachedViewModel
|
||||
{
|
||||
OrganizationId = organization.Id,
|
||||
MaxSeatCount = maxSeatCount,
|
||||
};
|
||||
|
||||
await AddMessageContentAsync(message, "OrganizationSeatsMaxReached", model);
|
||||
message.Category = "OrganizationSeatsMaxReached";
|
||||
await _mailDeliveryService.SendEmailAsync(message);
|
||||
}
|
||||
|
||||
public async Task SendOrganizationAcceptedEmailAsync(Organization organization, string userIdentifier,
|
||||
IEnumerable<string> adminEmails)
|
||||
{
|
||||
|
@ -16,6 +16,7 @@ using System.IO;
|
||||
using Newtonsoft.Json;
|
||||
using System.Text.Json;
|
||||
using Bit.Core.Context;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Bit.Core.Services
|
||||
{
|
||||
@ -40,9 +41,11 @@ namespace Bit.Core.Services
|
||||
private readonly ISsoConfigRepository _ssoConfigRepository;
|
||||
private readonly ISsoUserRepository _ssoUserRepository;
|
||||
private readonly IReferenceEventService _referenceEventService;
|
||||
private readonly GlobalSettings _globalSettings;
|
||||
private readonly IGlobalSettings _globalSettings;
|
||||
private readonly ITaxRateRepository _taxRateRepository;
|
||||
private readonly ICurrentContext _currentContext;
|
||||
private readonly ILogger<OrganizationService> _logger;
|
||||
|
||||
|
||||
public OrganizationService(
|
||||
IOrganizationRepository organizationRepository,
|
||||
@ -64,9 +67,10 @@ namespace Bit.Core.Services
|
||||
ISsoConfigRepository ssoConfigRepository,
|
||||
ISsoUserRepository ssoUserRepository,
|
||||
IReferenceEventService referenceEventService,
|
||||
GlobalSettings globalSettings,
|
||||
IGlobalSettings globalSettings,
|
||||
ITaxRateRepository taxRateRepository,
|
||||
ICurrentContext currentContext)
|
||||
ICurrentContext currentContext,
|
||||
ILogger<OrganizationService> logger)
|
||||
{
|
||||
_organizationRepository = organizationRepository;
|
||||
_organizationUserRepository = organizationUserRepository;
|
||||
@ -90,6 +94,7 @@ namespace Bit.Core.Services
|
||||
_globalSettings = globalSettings;
|
||||
_taxRateRepository = taxRateRepository;
|
||||
_currentContext = currentContext;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task ReplacePaymentMethodAsync(Guid organizationId, string paymentToken,
|
||||
@ -241,14 +246,14 @@ namespace Bit.Core.Services
|
||||
$"Disable your SSO configuration.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!newPlan.HasResetPassword && organization.UseResetPassword)
|
||||
{
|
||||
var resetPasswordPolicy =
|
||||
await _policyRepository.GetByOrganizationIdTypeAsync(organization.Id, PolicyType.ResetPassword);
|
||||
if (resetPasswordPolicy != null && resetPasswordPolicy.Enabled)
|
||||
{
|
||||
throw new BadRequestException("Your new plan does not allow the Password Reset feature. " +
|
||||
throw new BadRequestException("Your new plan does not allow the Password Reset feature. " +
|
||||
"Disable your Password Reset policy.");
|
||||
}
|
||||
}
|
||||
@ -347,7 +352,7 @@ namespace Bit.Core.Services
|
||||
return secret;
|
||||
}
|
||||
|
||||
public async Task<string> AdjustSeatsAsync(Guid organizationId, int seatAdjustment)
|
||||
public async Task UpdateSubscription(Guid organizationId, int seatAdjustment, int? maxAutoscaleSeats)
|
||||
{
|
||||
var organization = await GetOrgById(organizationId);
|
||||
if (organization == null)
|
||||
@ -355,6 +360,69 @@ namespace Bit.Core.Services
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
var newSeatCount = organization.Seats + seatAdjustment;
|
||||
if (maxAutoscaleSeats.HasValue && newSeatCount > maxAutoscaleSeats.Value)
|
||||
{
|
||||
throw new BadRequestException("Cannot set max seat autoscaling below seat count.");
|
||||
}
|
||||
|
||||
if (seatAdjustment != 0)
|
||||
{
|
||||
await AdjustSeatsAsync(organization, seatAdjustment);
|
||||
}
|
||||
if (maxAutoscaleSeats != organization.MaxAutoscaleSeats)
|
||||
{
|
||||
await UpdateAutoscalingAsync(organization, maxAutoscaleSeats);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UpdateAutoscalingAsync(Organization organization, int? maxAutoscaleSeats)
|
||||
{
|
||||
|
||||
if (maxAutoscaleSeats.HasValue &&
|
||||
organization.Seats.HasValue &&
|
||||
maxAutoscaleSeats.Value < organization.Seats.Value)
|
||||
{
|
||||
throw new BadRequestException($"Cannot set max seat autoscaling below current seat count.");
|
||||
}
|
||||
|
||||
var plan = StaticStore.Plans.FirstOrDefault(p => p.Type == organization.PlanType);
|
||||
if (plan == null)
|
||||
{
|
||||
throw new BadRequestException("Existing plan not found.");
|
||||
}
|
||||
|
||||
if (!plan.AllowSeatAutoscale)
|
||||
{
|
||||
throw new BadRequestException("Your plan does not allow seat autoscaling.");
|
||||
}
|
||||
|
||||
if (plan.MaxUsers.HasValue && maxAutoscaleSeats.HasValue &&
|
||||
maxAutoscaleSeats > plan.MaxUsers)
|
||||
{
|
||||
throw new BadRequestException(string.Concat($"Your plan has a seat limit of {plan.MaxUsers}, ",
|
||||
$"but you have specified a max autoscale count of {maxAutoscaleSeats}.",
|
||||
"Reduce your max autoscale seat count."));
|
||||
}
|
||||
|
||||
organization.MaxAutoscaleSeats = maxAutoscaleSeats;
|
||||
|
||||
await ReplaceAndUpdateCache(organization);
|
||||
}
|
||||
|
||||
public async Task<string> AdjustSeatsAsync(Guid organizationId, int seatAdjustment, DateTime? prorationDate = null)
|
||||
{
|
||||
var organization = await GetOrgById(organizationId);
|
||||
if (organization == null)
|
||||
{
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
return await AdjustSeatsAsync(organization, seatAdjustment, prorationDate);
|
||||
}
|
||||
|
||||
private async Task<string> AdjustSeatsAsync(Organization organization, int seatAdjustment, DateTime? prorationDate = null, IEnumerable<string> ownerEmails = null)
|
||||
{
|
||||
if (organization.Seats == null)
|
||||
{
|
||||
throw new BadRequestException("Organization has no seat limit, no need to adjust seats");
|
||||
@ -420,6 +488,24 @@ namespace Bit.Core.Services
|
||||
});
|
||||
organization.Seats = (short?)newSeatTotal;
|
||||
await ReplaceAndUpdateCache(organization);
|
||||
|
||||
if (organization.Seats.HasValue && organization.MaxAutoscaleSeats.HasValue && organization.Seats == organization.MaxAutoscaleSeats)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (ownerEmails == null)
|
||||
{
|
||||
ownerEmails = (await _organizationUserRepository.GetManyByMinimumRoleAsync(organization.Id,
|
||||
OrganizationUserType.Owner)).Select(u => u.Email).Distinct();
|
||||
}
|
||||
await _mailService.SendOrganizationMaxSeatLimitReachedEmailAsync(organization, organization.MaxAutoscaleSeats.Value, ownerEmails);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError(e, "Error encountered notifying organization owners of seat limit reached.");
|
||||
}
|
||||
}
|
||||
|
||||
return paymentIntentClientSecret;
|
||||
}
|
||||
|
||||
@ -470,7 +556,7 @@ namespace Bit.Core.Services
|
||||
bool provider = false)
|
||||
{
|
||||
var plan = StaticStore.Plans.FirstOrDefault(p => p.Type == signup.Plan);
|
||||
if (!(plan is {LegacyYear: null}))
|
||||
if (!(plan is { LegacyYear: null }))
|
||||
{
|
||||
throw new BadRequestException("Invalid plan selected.");
|
||||
}
|
||||
@ -558,7 +644,7 @@ namespace Bit.Core.Services
|
||||
|
||||
var orgsWithSingleOrgPolicy = policies.Where(p => p.Enabled && p.Type == PolicyType.SingleOrg)
|
||||
.Select(p => p.OrganizationId);
|
||||
var blockedBySingleOrgPolicy = orgUsers.Any(ou => ou is {Type: OrganizationUserType.Owner} &&
|
||||
var blockedBySingleOrgPolicy = orgUsers.Any(ou => ou is { Type: OrganizationUserType.Owner } &&
|
||||
ou.Type != OrganizationUserType.Admin &&
|
||||
ou.Status != OrganizationUserStatusType.Invited &&
|
||||
orgsWithSingleOrgPolicy.Contains(ou.OrganizationId));
|
||||
@ -786,14 +872,14 @@ namespace Bit.Core.Services
|
||||
$"Your new license does not allow for the use of SSO. Disable your SSO configuration.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!license.UseResetPassword && organization.UseResetPassword)
|
||||
{
|
||||
var resetPasswordPolicy =
|
||||
await _policyRepository.GetByOrganizationIdTypeAsync(organization.Id, PolicyType.ResetPassword);
|
||||
if (resetPasswordPolicy != null && resetPasswordPolicy.Enabled)
|
||||
{
|
||||
throw new BadRequestException("Your new license does not allow the Password Reset feature. "
|
||||
throw new BadRequestException("Your new license does not allow the Password Reset feature. "
|
||||
+ "Disable your Password Reset policy.");
|
||||
}
|
||||
}
|
||||
@ -964,11 +1050,12 @@ namespace Bit.Core.Services
|
||||
await UpdateAsync(organization);
|
||||
}
|
||||
|
||||
private async Task<List<OrganizationUser>> InviteUsersAsync(Guid organizationId, Guid? invitingUserId,
|
||||
public async Task<List<OrganizationUser>> InviteUsersAsync(Guid organizationId, Guid? invitingUserId,
|
||||
IEnumerable<(OrganizationUserInvite invite, string externalId)> invites)
|
||||
{
|
||||
var organization = await GetOrgById(organizationId);
|
||||
if (organization == null || invites.Any(i => i.invite.Emails == null || i.externalId == null))
|
||||
var initialSeatCount = organization.Seats;
|
||||
if (organization == null || invites.Any(i => i.invite.Emails == null))
|
||||
{
|
||||
throw new NotFoundException();
|
||||
}
|
||||
@ -983,23 +1070,34 @@ namespace Bit.Core.Services
|
||||
}
|
||||
}
|
||||
|
||||
var newSeatsRequired = 0;
|
||||
var existingEmails = new HashSet<string>(await _organizationUserRepository.SelectKnownEmailsAsync(
|
||||
organizationId, invites.SelectMany(i => i.invite.Emails), false), StringComparer.InvariantCultureIgnoreCase);
|
||||
if (organization.Seats.HasValue)
|
||||
{
|
||||
var userCount = await _organizationUserRepository.GetCountByOrganizationIdAsync(organizationId);
|
||||
var availableSeats = organization.Seats.Value - userCount;
|
||||
if (availableSeats < invites.Select(i => i.invite.Emails.Count()).Sum())
|
||||
{
|
||||
throw new BadRequestException("You have reached the maximum number of users " +
|
||||
$"({organization.Seats.Value}) for this organization.");
|
||||
}
|
||||
newSeatsRequired = invites.Sum(i => i.invite.Emails.Count()) - existingEmails.Count() - availableSeats;
|
||||
}
|
||||
|
||||
var (canScale, failureReason) = await CanScaleAsync(organization, newSeatsRequired);
|
||||
if (!canScale)
|
||||
{
|
||||
throw new BadRequestException(failureReason);
|
||||
}
|
||||
|
||||
var invitedAreAllOwners = invites.All(i => i.invite.Type == OrganizationUserType.Owner);
|
||||
if (!invitedAreAllOwners && !await HasConfirmedOwnersExceptAsync(organizationId, new Guid[] { }))
|
||||
{
|
||||
throw new BadRequestException("Organization must have at least one confirmed owner.");
|
||||
}
|
||||
|
||||
|
||||
var orgUsers = new List<OrganizationUser>();
|
||||
var limitedCollectionOrgUsers = new List<(OrganizationUser, IEnumerable<SelectionReadOnly>)>();
|
||||
var orgUserInvitedCount = 0;
|
||||
var exceptions = new List<Exception>();
|
||||
var events = new List<(OrganizationUser, EventType, DateTime?)>();
|
||||
var existingEmails = new HashSet<string>(await _organizationUserRepository.SelectKnownEmailsAsync(
|
||||
organizationId, invites.SelectMany(i => i.invite.Emails), false), StringComparer.InvariantCultureIgnoreCase);
|
||||
foreach (var (invite, externalId) in invites)
|
||||
{
|
||||
foreach (var email in invite.Emails)
|
||||
@ -1036,11 +1134,14 @@ namespace Bit.Core.Services
|
||||
|
||||
if (!orgUser.AccessAll && invite.Collections.Any())
|
||||
{
|
||||
throw new Exception("Bulk invite does not support limited collection invites");
|
||||
limitedCollectionOrgUsers.Add((orgUser, invite.Collections));
|
||||
}
|
||||
else
|
||||
{
|
||||
orgUsers.Add(orgUser);
|
||||
}
|
||||
|
||||
events.Add((orgUser, EventType.OrganizationUser_Invited, DateTime.UtcNow));
|
||||
orgUsers.Add(orgUser);
|
||||
orgUserInvitedCount++;
|
||||
}
|
||||
catch (Exception e)
|
||||
@ -1050,9 +1151,21 @@ namespace Bit.Core.Services
|
||||
}
|
||||
}
|
||||
|
||||
if (exceptions.Any())
|
||||
{
|
||||
throw new AggregateException("One or more errors occurred while inviting users.", exceptions);
|
||||
}
|
||||
|
||||
var prorationDate = DateTime.UtcNow;
|
||||
try
|
||||
{
|
||||
await _organizationUserRepository.CreateManyAsync(orgUsers);
|
||||
foreach (var (orgUser, collections) in limitedCollectionOrgUsers)
|
||||
{
|
||||
await _organizationUserRepository.CreateAsync(orgUser, collections);
|
||||
}
|
||||
|
||||
await AutoAddSeatsAsync(organization, newSeatsRequired, prorationDate);
|
||||
await SendInvitesAsync(orgUsers, organization);
|
||||
await _eventService.LogOrganizationUserEventsAsync(events);
|
||||
|
||||
@ -1064,6 +1177,16 @@ namespace Bit.Core.Services
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// Revert any added users.
|
||||
var invitedOrgUserIds = orgUsers.Select(u => u.Id).Concat(limitedCollectionOrgUsers.Select(u => u.Item1.Id));
|
||||
await _organizationUserRepository.DeleteManyAsync(invitedOrgUserIds);
|
||||
var currentSeatCount = (await _organizationRepository.GetByIdAsync(organization.Id)).Seats;
|
||||
|
||||
if (initialSeatCount.HasValue && currentSeatCount.HasValue && currentSeatCount.Value != initialSeatCount.Value)
|
||||
{
|
||||
await AdjustSeatsAsync(organization, initialSeatCount.Value - currentSeatCount.Value, prorationDate);
|
||||
}
|
||||
|
||||
exceptions.Add(e);
|
||||
}
|
||||
|
||||
@ -1075,94 +1198,6 @@ namespace Bit.Core.Services
|
||||
return orgUsers;
|
||||
}
|
||||
|
||||
public async Task<List<OrganizationUser>> InviteUserAsync(Guid organizationId, Guid? invitingUserId,
|
||||
string externalId, OrganizationUserInvite invite)
|
||||
{
|
||||
var organization = await GetOrgById(organizationId);
|
||||
if (organization == null || invite?.Emails == null)
|
||||
{
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
if (invitingUserId.HasValue && invite.Type.HasValue)
|
||||
{
|
||||
await ValidateOrganizationUserUpdatePermissions(organizationId, invite.Type.Value, null);
|
||||
}
|
||||
|
||||
if (organization.Seats.HasValue)
|
||||
{
|
||||
var userCount = await _organizationUserRepository.GetCountByOrganizationIdAsync(organizationId);
|
||||
var availableSeats = organization.Seats.Value - userCount;
|
||||
if (availableSeats < invite.Emails.Count())
|
||||
{
|
||||
throw new BadRequestException("You have reached the maximum number of users " +
|
||||
$"({organization.Seats.Value}) for this organization.");
|
||||
}
|
||||
}
|
||||
|
||||
var invitedIsOwner = invite.Type is OrganizationUserType.Owner;
|
||||
if (!invitedIsOwner && !await HasConfirmedOwnersExceptAsync(organizationId, new Guid[] {}))
|
||||
{
|
||||
throw new BadRequestException("Organization must have at least one confirmed owner.");
|
||||
}
|
||||
|
||||
var orgUsers = new List<OrganizationUser>();
|
||||
var orgUserInvitedCount = 0;
|
||||
foreach (var email in invite.Emails)
|
||||
{
|
||||
// Make sure user is not already invited
|
||||
var existingOrgUserCount = await _organizationUserRepository.GetCountByOrganizationAsync(
|
||||
organizationId, email, false);
|
||||
if (existingOrgUserCount > 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var orgUser = new OrganizationUser
|
||||
{
|
||||
OrganizationId = organizationId,
|
||||
UserId = null,
|
||||
Email = email.ToLowerInvariant(),
|
||||
Key = null,
|
||||
Type = invite.Type.Value,
|
||||
Status = OrganizationUserStatusType.Invited,
|
||||
AccessAll = invite.AccessAll,
|
||||
ExternalId = externalId,
|
||||
CreationDate = DateTime.UtcNow,
|
||||
RevisionDate = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
if (invite.Permissions != null)
|
||||
{
|
||||
orgUser.Permissions = System.Text.Json.JsonSerializer.Serialize(invite.Permissions, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
});
|
||||
}
|
||||
|
||||
if (!orgUser.AccessAll && invite.Collections.Any())
|
||||
{
|
||||
await _organizationUserRepository.CreateAsync(orgUser, invite.Collections);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _organizationUserRepository.CreateAsync(orgUser);
|
||||
}
|
||||
|
||||
await SendInviteAsync(orgUser, organization);
|
||||
await _eventService.LogOrganizationUserEventAsync(orgUser, EventType.OrganizationUser_Invited);
|
||||
orgUsers.Add(orgUser);
|
||||
orgUserInvitedCount++;
|
||||
}
|
||||
await _referenceEventService.RaiseEventAsync(
|
||||
new ReferenceEvent(ReferenceEventType.InvitedUsers, organization)
|
||||
{
|
||||
Users = orgUserInvitedCount
|
||||
});
|
||||
|
||||
return orgUsers;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Tuple<OrganizationUser, string>>> ResendInvitesAsync(Guid organizationId, Guid? invitingUserId,
|
||||
IEnumerable<Guid> organizationUsersId)
|
||||
{
|
||||
@ -1349,7 +1384,7 @@ namespace Bit.Core.Services
|
||||
public async Task<OrganizationUser> ConfirmUserAsync(Guid organizationId, Guid organizationUserId, string key,
|
||||
Guid confirmingUserId, IUserService userService)
|
||||
{
|
||||
var result = await ConfirmUsersAsync(organizationId, new Dictionary<Guid, string>() {{organizationUserId, key}},
|
||||
var result = await ConfirmUsersAsync(organizationId, new Dictionary<Guid, string>() { { organizationUserId, key } },
|
||||
confirmingUserId, userService);
|
||||
|
||||
if (!result.Any())
|
||||
@ -1364,7 +1399,7 @@ namespace Bit.Core.Services
|
||||
}
|
||||
return orgUser;
|
||||
}
|
||||
|
||||
|
||||
public async Task<List<Tuple<OrganizationUser, string>>> ConfirmUsersAsync(Guid organizationId, Dictionary<Guid, string> keys,
|
||||
Guid confirmingUserId, IUserService userService)
|
||||
{
|
||||
@ -1379,7 +1414,7 @@ namespace Bit.Core.Services
|
||||
}
|
||||
|
||||
var validOrganizationUserIds = validOrganizationUsers.Select(u => u.UserId.Value).ToList();
|
||||
|
||||
|
||||
var organization = await GetOrgById(organizationId);
|
||||
var policies = await _policyRepository.GetManyByOrganizationIdAsync(organizationId);
|
||||
var usersOrgs = await _organizationUserRepository.GetManyByManyUsersAsync(validOrganizationUserIds);
|
||||
@ -1417,7 +1452,7 @@ namespace Bit.Core.Services
|
||||
orgUser.Status = OrganizationUserStatusType.Confirmed;
|
||||
orgUser.Key = keys[orgUser.Id];
|
||||
orgUser.Email = null;
|
||||
|
||||
|
||||
await _eventService.LogOrganizationUserEventAsync(orgUser, EventType.OrganizationUser_Confirmed);
|
||||
await _mailService.SendOrganizationConfirmedEmailAsync(organization.Name, user.Email);
|
||||
await DeleteAndPushUserRegistrationAsync(organizationId, user.Id);
|
||||
@ -1435,6 +1470,68 @@ namespace Bit.Core.Services
|
||||
return result;
|
||||
}
|
||||
|
||||
internal async Task<(bool canScale, string failureReason)> CanScaleAsync(Organization organization, int seatsToAdd)
|
||||
{
|
||||
var failureReason = "";
|
||||
if (_globalSettings.SelfHosted)
|
||||
{
|
||||
failureReason = "Cannot autoscale on self-hosted instance.";
|
||||
return (false, failureReason);
|
||||
}
|
||||
|
||||
if (!await _currentContext.ManageUsers(organization.Id))
|
||||
{
|
||||
failureReason = "Cannot manage organization users.";
|
||||
return (false, failureReason);
|
||||
}
|
||||
// if (!await _currentContext.OrganizationOwner(organization.Id))
|
||||
// {
|
||||
// failureReason = "Only organization owners can autoscale seats.";
|
||||
// return (false, failureReason);
|
||||
// }
|
||||
|
||||
if (seatsToAdd < 1)
|
||||
{
|
||||
return (true, failureReason);
|
||||
}
|
||||
|
||||
if (organization.Seats.HasValue &&
|
||||
organization.MaxAutoscaleSeats.HasValue &&
|
||||
organization.MaxAutoscaleSeats.Value < organization.Seats.Value + seatsToAdd)
|
||||
{
|
||||
return (false, $"Cannot invite new users. Seat limit has been reached.");
|
||||
}
|
||||
|
||||
return (true, failureReason);
|
||||
}
|
||||
|
||||
private async Task AutoAddSeatsAsync(Organization organization, int seatsToAdd, DateTime? prorationDate = null)
|
||||
{
|
||||
if (seatsToAdd < 1 || !organization.Seats.HasValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var (canScale, failureMessage) = await CanScaleAsync(organization, seatsToAdd);
|
||||
if (!canScale)
|
||||
{
|
||||
throw new BadRequestException(failureMessage);
|
||||
}
|
||||
|
||||
var ownerEmails = (await _organizationUserRepository.GetManyByMinimumRoleAsync(organization.Id,
|
||||
OrganizationUserType.Owner)).Select(u => u.Email).Distinct();
|
||||
|
||||
await AdjustSeatsAsync(organization, seatsToAdd, prorationDate, ownerEmails);
|
||||
|
||||
if (!organization.OwnersNotifiedOfAutoscaling.HasValue)
|
||||
{
|
||||
await _mailService.SendOrganizationAutoscaledEmailAsync(organization, organization.Seats.Value + seatsToAdd,
|
||||
ownerEmails);
|
||||
organization.OwnersNotifiedOfAutoscaling = DateTime.UtcNow;
|
||||
await _organizationRepository.UpsertAsync(organization);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CheckPolicies(ICollection<Policy> policies, Guid organizationId, User user,
|
||||
ICollection<OrganizationUser> userOrgs, IUserService userService)
|
||||
{
|
||||
@ -1474,7 +1571,7 @@ namespace Bit.Core.Services
|
||||
}
|
||||
|
||||
if (user.Type != OrganizationUserType.Owner &&
|
||||
!await HasConfirmedOwnersExceptAsync(user.OrganizationId, new[] {user.Id}))
|
||||
!await HasConfirmedOwnersExceptAsync(user.OrganizationId, new[] { user.Id }))
|
||||
{
|
||||
throw new BadRequestException("Organization must have at least one confirmed owner.");
|
||||
}
|
||||
@ -1507,7 +1604,7 @@ namespace Bit.Core.Services
|
||||
throw new BadRequestException("Only owners can delete other owners.");
|
||||
}
|
||||
|
||||
if (!await HasConfirmedOwnersExceptAsync(organizationId, new[] {organizationUserId}))
|
||||
if (!await HasConfirmedOwnersExceptAsync(organizationId, new[] { organizationUserId }))
|
||||
{
|
||||
throw new BadRequestException("Organization must have at least one confirmed owner.");
|
||||
}
|
||||
@ -1529,7 +1626,7 @@ namespace Bit.Core.Services
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
if (!await HasConfirmedOwnersExceptAsync(organizationId, new[] {orgUser.Id}))
|
||||
if (!await HasConfirmedOwnersExceptAsync(organizationId, new[] { orgUser.Id }))
|
||||
{
|
||||
throw new BadRequestException("Organization must have at least one confirmed owner.");
|
||||
}
|
||||
@ -1630,12 +1727,12 @@ namespace Bit.Core.Services
|
||||
{
|
||||
// Org User must be the same as the calling user and the organization ID associated with the user must match passed org ID
|
||||
var orgUser = await _organizationUserRepository.GetByOrganizationAsync(organizationId, organizationUserId);
|
||||
if (!callingUserId.HasValue || orgUser == null || orgUser.UserId != callingUserId.Value ||
|
||||
if (!callingUserId.HasValue || orgUser == null || orgUser.UserId != callingUserId.Value ||
|
||||
orgUser.OrganizationId != organizationId)
|
||||
{
|
||||
throw new BadRequestException("User not valid.");
|
||||
}
|
||||
|
||||
|
||||
// Make sure the organization has the ability to use password reset
|
||||
var org = await _organizationRepository.GetByIdAsync(organizationId);
|
||||
if (org == null || !org.UseResetPassword)
|
||||
@ -1650,7 +1747,7 @@ namespace Bit.Core.Services
|
||||
{
|
||||
throw new BadRequestException("Organization does not have the password reset policy enabled.");
|
||||
}
|
||||
|
||||
|
||||
// Block the user from withdrawal if auto enrollment is enabled
|
||||
if (resetPasswordKey == null && resetPasswordPolicy.Data != null)
|
||||
{
|
||||
@ -1661,7 +1758,7 @@ namespace Bit.Core.Services
|
||||
throw new BadRequestException("Due to an Enterprise Policy, you are not allowed to withdraw from Password Reset.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
orgUser.ResetPasswordKey = resetPasswordKey;
|
||||
await _organizationUserRepository.ReplaceAsync(orgUser);
|
||||
await _eventService.LogOrganizationUserEventAsync(orgUser, resetPasswordKey != null ?
|
||||
@ -1702,7 +1799,8 @@ namespace Bit.Core.Services
|
||||
AccessAll = accessAll,
|
||||
Collections = collections,
|
||||
};
|
||||
var results = await InviteUserAsync(organizationId, invitingUserId, externalId, invite);
|
||||
var results = await InviteUsersAsync(organizationId, invitingUserId,
|
||||
new (OrganizationUserInvite, string)[] { (invite, externalId) });
|
||||
var result = results.FirstOrDefault();
|
||||
if (result == null)
|
||||
{
|
||||
@ -1797,11 +1895,6 @@ namespace Bit.Core.Services
|
||||
enoughSeatsAvailable = seatsAvailable >= usersToAdd.Count;
|
||||
}
|
||||
|
||||
if (!enoughSeatsAvailable)
|
||||
{
|
||||
throw new BadRequestException($"Organization does not have enough seats available. Need {usersToAdd.Count} but {seatsAvailable} available.");
|
||||
}
|
||||
|
||||
var userInvites = new List<(OrganizationUserInvite, string)>();
|
||||
foreach (var user in newUsers)
|
||||
{
|
||||
@ -1891,7 +1984,7 @@ namespace Bit.Core.Services
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
await _referenceEventService.RaiseEventAsync(
|
||||
new ReferenceEvent(ReferenceEventType.DirectorySynced, organization));
|
||||
}
|
||||
@ -1934,7 +2027,7 @@ namespace Bit.Core.Services
|
||||
org.PublicKey = publicKey;
|
||||
org.PrivateKey = privateKey;
|
||||
await UpdateAsync(org);
|
||||
|
||||
|
||||
return org;
|
||||
}
|
||||
|
||||
|
@ -718,6 +718,12 @@ namespace Bit.Core.Services
|
||||
ProrationDate = prorationDate,
|
||||
};
|
||||
|
||||
if (!subscriptionUpdate.UpdateNeeded(sub))
|
||||
{
|
||||
// No need to update subscription, quantity matches
|
||||
return null;
|
||||
}
|
||||
|
||||
var customer = await new CustomerService().GetAsync(sub.CustomerId);
|
||||
if (!string.IsNullOrWhiteSpace(customer?.Address?.Country)
|
||||
&& !string.IsNullOrWhiteSpace(customer?.Address?.PostalCode))
|
||||
|
@ -35,6 +35,16 @@ namespace Bit.Core.Services
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public Task SendOrganizationMaxSeatLimitReachedEmailAsync(Organization organization, int maxSeatCount, IEnumerable<string> ownerEmails)
|
||||
{
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public Task SendOrganizationAutoscaledEmailAsync(Organization organization, int initialSeatCount, IEnumerable<string> ownerEmails)
|
||||
{
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
|
||||
public Task SendOrganizationAcceptedEmailAsync(Organization organization, string userIdentifier, IEnumerable<string> adminEmails)
|
||||
{
|
||||
return Task.FromResult(0);
|
||||
|
Reference in New Issue
Block a user