mirror of
https://github.com/bitwarden/server.git
synced 2025-07-02 00:22:50 -05:00
Families for Enterprise (#1714)
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Create common test infrastructure project
* Add helpers to further type PlanTypes
* Enable testing of ASP.net MVC controllers
Controller properties have all kinds of validations in the background.
In general, we don't user properties on our Controllers, so the easiest
way to allow for Autofixture-based testing of our Controllers is to just
omit setting all properties on them.
* Workaround for broken MemberAutoDataAttribute
https://github.com/AutoFixture/AutoFixture/pull/1164 shows that only
the first test case is pulled for this attribute.
This is a workaround that populates the provided parameters, left to
right, using AutoFixture to populate any remaining.
* WIP: Organization sponsorship flow
* Add Attribute to use the Bit Autodata dependency chain
BitAutoDataAttribute is used to mark a Theory as autopopulating
parameters.
Extract common attribute methods to to a helper class. Cannot
inherit a common base, since both require inheriting from different
Xunit base classes to work.
* WIP: scaffolding for families for enterprise sponsorship flow
* Fix broken tests
* Create sponsorship offer (#1688)
* Initial db work (#1687)
* Add organization sponsorship databases to all providers
* Generalize create and update for database, specialize in code
* Add PlanSponsorshipType to db model
* Write valid json for test entries
* Initial scaffolding of emails (#1686)
* Initial scaffolding of emails
* Work on adding models for FamilyForEnterprise emails
* Switch verbage
* Put preliminary copy in emails
* Skip test
* Families for enterprise/stripe integrations (#1699)
* Add PlanSponsorshipType to static store
* Add sponsorship type to token and creates sponsorship
* PascalCase properties
* Require sponsorship for remove
* Create subscription sponsorship helper class
* Handle Sponsored subscription changes
* Add sponsorship id to subscription metadata
* Make sponsoring references nullable
This state indicates that a sponsorship has lapsed, but was not able to
be reverted for billing reasons
* WIP: Validate and remove subscriptions
* Update sponsorships on organization and org user delete
* Add friendly name to organization sponsorship
* Add sponsorship available boolean to orgDetails
* Add sponsorship service to DI
* Use userId to find org users
* Send f4e offer email
* Simplify names of f4e mail messages
* Fix Stripe org default tax rates
* Universal sponsorship redeem api
* Populate user in current context
* Add product type to organization details
* Use upgrade path to change sponsorship
Sponsorships need to be annual to match the GB add-on charge rate
* Use organization and auth to find organization sponsorship
* Add resend sponsorship offer api endpoint
* Fix double email send
* Fix sponsorship upgrade options
* Add is sponsored item to subscription response
* Add sponsorship validation to upcoming invoice webhook
* Add sponsorship validation to upcoming invoice webhook
* Fix organization delete sponsorship hooks
* Test org sponsorship service
* Fix sproc
* Fix build error
* Update emails
* Fix tests
* Skip local test
* Add newline
* Fix stripe subscription update
* Finish emails
* Skip test
* Fix unit tests
* Remove unused variable
* Fix unit tests
* Switch to handlebars ifs
* Remove ending email
* Remove reconfirmation template
* Switch naming convention
* Switch naming convention
* Fix migration
* Update copy and links
* Switch to using Guid in the method
* Remove unneeded css styles
* Add sql files to Sql.sqlproj
* Removed old comments
* Made name more verbose
* Fix SQL error
* Move unit tests to service
* Fix sp
* Revert "Move unit tests to service"
This reverts commit 1185bf3ec8
.
* Do repository validation in service layer
* Fix tests
* Fix merge conflicts and remove TODO
* Remove unneeded models
* Fix spacing and formatting
* Switch Org -> Organization
* Remove single use variables
* Switch method name
* Fix Controller
* Switch to obfuscating email
* Fix unit tests
Co-authored-by: Justin Baur <admin@justinbaur.com>
This commit is contained in:
@ -0,0 +1,310 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Bit.Core.Enums;
|
||||
using Bit.Core.Exceptions;
|
||||
using Bit.Core.Models.Table;
|
||||
using Bit.Core.Repositories;
|
||||
using Bit.Core.Utilities;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
|
||||
namespace Bit.Core.Services
|
||||
{
|
||||
public class OrganizationSponsorshipService : IOrganizationSponsorshipService
|
||||
{
|
||||
private const string FamiliesForEnterpriseTokenName = "FamiliesForEnterpriseToken";
|
||||
private const string TokenClearTextPrefix = "BWOrganizationSponsorship_";
|
||||
|
||||
private readonly IOrganizationSponsorshipRepository _organizationSponsorshipRepository;
|
||||
private readonly IOrganizationRepository _organizationRepository;
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IPaymentService _paymentService;
|
||||
private readonly IMailService _mailService;
|
||||
|
||||
private readonly IDataProtector _dataProtector;
|
||||
|
||||
public OrganizationSponsorshipService(IOrganizationSponsorshipRepository organizationSponsorshipRepository,
|
||||
IOrganizationRepository organizationRepository,
|
||||
IUserRepository userRepository,
|
||||
IPaymentService paymentService,
|
||||
IMailService mailService,
|
||||
IDataProtectionProvider dataProtectionProvider)
|
||||
{
|
||||
_organizationSponsorshipRepository = organizationSponsorshipRepository;
|
||||
_organizationRepository = organizationRepository;
|
||||
_userRepository = userRepository;
|
||||
_paymentService = paymentService;
|
||||
_mailService = mailService;
|
||||
_dataProtector = dataProtectionProvider.CreateProtector("OrganizationSponsorshipServiceDataProtector");
|
||||
}
|
||||
|
||||
public async Task<bool> ValidateRedemptionTokenAsync(string encryptedToken)
|
||||
{
|
||||
if (!encryptedToken.StartsWith(TokenClearTextPrefix))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var decryptedToken = _dataProtector.Unprotect(encryptedToken[TokenClearTextPrefix.Length..]);
|
||||
var dataParts = decryptedToken.Split(' ');
|
||||
|
||||
if (dataParts.Length != 3)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (dataParts[0].Equals(FamiliesForEnterpriseTokenName))
|
||||
{
|
||||
if (!Guid.TryParse(dataParts[1], out Guid sponsorshipId) ||
|
||||
!Enum.TryParse<PlanSponsorshipType>(dataParts[2], true, out var sponsorshipType))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var sponsorship = await _organizationSponsorshipRepository.GetByIdAsync(sponsorshipId);
|
||||
if (sponsorship == null || sponsorship.PlanSponsorshipType != sponsorshipType)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private string RedemptionToken(Guid sponsorshipId, PlanSponsorshipType sponsorshipType) =>
|
||||
string.Concat(
|
||||
TokenClearTextPrefix,
|
||||
_dataProtector.Protect($"{FamiliesForEnterpriseTokenName} {sponsorshipId} {sponsorshipType}")
|
||||
);
|
||||
|
||||
public async Task OfferSponsorshipAsync(Organization sponsoringOrg, OrganizationUser sponsoringOrgUser,
|
||||
PlanSponsorshipType sponsorshipType, string sponsoredEmail, string friendlyName, string sponsoringUserEmail)
|
||||
{
|
||||
var requiredSponsoringProductType = StaticStore.GetSponsoredPlan(sponsorshipType)?.SponsoringProductType;
|
||||
if (requiredSponsoringProductType == null ||
|
||||
sponsoringOrg == null ||
|
||||
StaticStore.GetPlan(sponsoringOrg.PlanType).Product != requiredSponsoringProductType.Value)
|
||||
{
|
||||
throw new BadRequestException("Specified Organization cannot sponsor other organizations.");
|
||||
}
|
||||
|
||||
if (sponsoringOrgUser == null || sponsoringOrgUser.Status != OrganizationUserStatusType.Confirmed)
|
||||
{
|
||||
throw new BadRequestException("Only confirmed users can sponsor other organizations.");
|
||||
}
|
||||
|
||||
var existingOrgSponsorship = await _organizationSponsorshipRepository
|
||||
.GetBySponsoringOrganizationUserIdAsync(sponsoringOrgUser.Id);
|
||||
if (existingOrgSponsorship != null)
|
||||
{
|
||||
throw new BadRequestException("Can only sponsor one organization per Organization User.");
|
||||
}
|
||||
|
||||
var sponsorship = new OrganizationSponsorship
|
||||
{
|
||||
SponsoringOrganizationId = sponsoringOrg.Id,
|
||||
SponsoringOrganizationUserId = sponsoringOrgUser.Id,
|
||||
FriendlyName = friendlyName,
|
||||
OfferedToEmail = sponsoredEmail,
|
||||
PlanSponsorshipType = sponsorshipType,
|
||||
CloudSponsor = true,
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
sponsorship = await _organizationSponsorshipRepository.CreateAsync(sponsorship);
|
||||
|
||||
await SendSponsorshipOfferAsync(sponsorship, sponsoringUserEmail);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (sponsorship.Id != default)
|
||||
{
|
||||
await _organizationSponsorshipRepository.DeleteAsync(sponsorship);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ResendSponsorshipOfferAsync(Organization sponsoringOrg, OrganizationUser sponsoringOrgUser,
|
||||
OrganizationSponsorship sponsorship, string sponsoringUserEmail)
|
||||
{
|
||||
if (sponsoringOrg == null)
|
||||
{
|
||||
throw new BadRequestException("Cannot find the requested sponsoring organization.");
|
||||
}
|
||||
|
||||
if (sponsoringOrgUser == null || sponsoringOrgUser.Status != OrganizationUserStatusType.Confirmed)
|
||||
{
|
||||
throw new BadRequestException("Only confirmed users can sponsor other organizations.");
|
||||
}
|
||||
|
||||
if (sponsorship == null || sponsorship.OfferedToEmail == null)
|
||||
{
|
||||
throw new BadRequestException("Cannot find an outstanding sponsorship offer for this organization.");
|
||||
}
|
||||
|
||||
await SendSponsorshipOfferAsync(sponsorship, sponsoringUserEmail);
|
||||
}
|
||||
|
||||
public async Task SendSponsorshipOfferAsync(OrganizationSponsorship sponsorship, string sponsoringEmail)
|
||||
{
|
||||
var user = await _userRepository.GetByEmailAsync(sponsorship.OfferedToEmail);
|
||||
var isExistingAccount = user != null;
|
||||
|
||||
await _mailService.SendFamiliesForEnterpriseOfferEmailAsync(sponsorship.OfferedToEmail, sponsoringEmail,
|
||||
isExistingAccount, RedemptionToken(sponsorship.Id, sponsorship.PlanSponsorshipType.Value));
|
||||
}
|
||||
|
||||
public async Task SetUpSponsorshipAsync(OrganizationSponsorship sponsorship,
|
||||
Organization sponsoredOrganization)
|
||||
{
|
||||
if (sponsorship == null)
|
||||
{
|
||||
throw new BadRequestException("No unredeemed sponsorship offer exists for you.");
|
||||
}
|
||||
|
||||
var existingOrgSponsorship = await _organizationSponsorshipRepository
|
||||
.GetBySponsoredOrganizationIdAsync(sponsoredOrganization.Id);
|
||||
if (existingOrgSponsorship != null)
|
||||
{
|
||||
throw new BadRequestException("Cannot redeem a sponsorship offer for an organization that is already sponsored. Revoke existing sponsorship first.");
|
||||
}
|
||||
|
||||
if (sponsorship.PlanSponsorshipType == null)
|
||||
{
|
||||
throw new BadRequestException("Cannot set up sponsorship without a known sponsorship type.");
|
||||
}
|
||||
|
||||
// Check org to sponsor's product type
|
||||
var requiredSponsoredProductType = StaticStore.GetSponsoredPlan(sponsorship.PlanSponsorshipType.Value)?.SponsoredProductType;
|
||||
if (requiredSponsoredProductType == null ||
|
||||
sponsoredOrganization == null ||
|
||||
StaticStore.GetPlan(sponsoredOrganization.PlanType).Product != requiredSponsoredProductType.Value)
|
||||
{
|
||||
throw new BadRequestException("Can only redeem sponsorship offer on families organizations.");
|
||||
}
|
||||
|
||||
await _paymentService.SponsorOrganizationAsync(sponsoredOrganization, sponsorship);
|
||||
await _organizationRepository.UpsertAsync(sponsoredOrganization);
|
||||
|
||||
sponsorship.SponsoredOrganizationId = sponsoredOrganization.Id;
|
||||
sponsorship.OfferedToEmail = null;
|
||||
await _organizationSponsorshipRepository.UpsertAsync(sponsorship);
|
||||
}
|
||||
|
||||
public async Task<bool> ValidateSponsorshipAsync(Guid sponsoredOrganizationId)
|
||||
{
|
||||
var sponsoredOrganization = await _organizationRepository.GetByIdAsync(sponsoredOrganizationId);
|
||||
if (sponsoredOrganization == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var existingSponsorship = await _organizationSponsorshipRepository
|
||||
.GetBySponsoredOrganizationIdAsync(sponsoredOrganizationId);
|
||||
|
||||
if (existingSponsorship == null)
|
||||
{
|
||||
await DoRemoveSponsorshipAsync(sponsoredOrganization, null);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (existingSponsorship.SponsoringOrganizationId == null || existingSponsorship.SponsoringOrganizationUserId == null || existingSponsorship.PlanSponsorshipType == null)
|
||||
{
|
||||
await DoRemoveSponsorshipAsync(sponsoredOrganization, existingSponsorship);
|
||||
return false;
|
||||
}
|
||||
var sponsoredPlan = Utilities.StaticStore.GetSponsoredPlan(existingSponsorship.PlanSponsorshipType.Value);
|
||||
|
||||
var sponsoringOrganization = await _organizationRepository
|
||||
.GetByIdAsync(existingSponsorship.SponsoringOrganizationId.Value);
|
||||
if (sponsoringOrganization == null)
|
||||
{
|
||||
await DoRemoveSponsorshipAsync(sponsoredOrganization, existingSponsorship);
|
||||
return false;
|
||||
}
|
||||
|
||||
var sponsoringOrgPlan = Utilities.StaticStore.GetPlan(sponsoringOrganization.PlanType);
|
||||
if (!sponsoringOrganization.Enabled || sponsoredPlan.SponsoringProductType != sponsoringOrgPlan.Product)
|
||||
{
|
||||
await DoRemoveSponsorshipAsync(sponsoredOrganization, existingSponsorship);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task RevokeSponsorshipAsync(Organization sponsoredOrg, OrganizationSponsorship sponsorship)
|
||||
{
|
||||
if (sponsorship == null)
|
||||
{
|
||||
throw new BadRequestException("You are not currently sponsoring an organization.");
|
||||
}
|
||||
|
||||
if (sponsorship.SponsoredOrganizationId == null)
|
||||
{
|
||||
await DoRemoveSponsorshipAsync(null, sponsorship);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sponsoredOrg == null)
|
||||
{
|
||||
throw new BadRequestException("Unable to find the sponsored Organization.");
|
||||
}
|
||||
|
||||
await DoRemoveSponsorshipAsync(sponsoredOrg, sponsorship);
|
||||
}
|
||||
|
||||
public async Task RemoveSponsorshipAsync(Organization sponsoredOrg, OrganizationSponsorship sponsorship)
|
||||
{
|
||||
if (sponsorship == null || sponsorship.SponsoredOrganizationId == null)
|
||||
{
|
||||
throw new BadRequestException("The requested organization is not currently being sponsored.");
|
||||
}
|
||||
|
||||
if (sponsoredOrg == null)
|
||||
{
|
||||
throw new BadRequestException("Unable to find the sponsored Organization.");
|
||||
}
|
||||
|
||||
await DoRemoveSponsorshipAsync(sponsoredOrg, sponsorship);
|
||||
}
|
||||
|
||||
internal async Task DoRemoveSponsorshipAsync(Organization sponsoredOrganization, OrganizationSponsorship sponsorship = null)
|
||||
{
|
||||
if (sponsoredOrganization != null)
|
||||
{
|
||||
await _paymentService.RemoveOrganizationSponsorshipAsync(sponsoredOrganization, sponsorship);
|
||||
await _organizationRepository.UpsertAsync(sponsoredOrganization);
|
||||
|
||||
await _mailService.SendFamiliesForEnterpriseSponsorshipRevertingEmailAsync(
|
||||
sponsoredOrganization.BillingEmailAddress(),
|
||||
sponsoredOrganization.Name);
|
||||
}
|
||||
|
||||
if (sponsorship == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialize the record as available
|
||||
sponsorship.SponsoredOrganizationId = null;
|
||||
sponsorship.FriendlyName = null;
|
||||
sponsorship.OfferedToEmail = null;
|
||||
sponsorship.PlanSponsorshipType = null;
|
||||
sponsorship.TimesRenewedWithoutValidation = 0;
|
||||
sponsorship.SponsorshipLapsedDate = null;
|
||||
|
||||
if (sponsorship.CloudSponsor || sponsorship.SponsorshipLapsedDate.HasValue)
|
||||
{
|
||||
await _organizationSponsorshipRepository.DeleteAsync(sponsorship);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _organizationSponsorshipRepository.UpsertAsync(sponsorship);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user