1
0
mirror of https://github.com/bitwarden/server.git synced 2025-07-06 18:42:49 -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:
Matt Gibson
2021-11-19 16:25:06 -06:00
committed by GitHub
parent be164967b3
commit 33edc8eba0
140 changed files with 7482 additions and 285 deletions

View File

@ -26,6 +26,7 @@ namespace Bit.Core.Repositories.EntityFramework
public DbSet<GroupUser> GroupUsers { get; set; }
public DbSet<Installation> Installations { get; set; }
public DbSet<Organization> Organizations { get; set; }
public DbSet<OrganizationSponsorship> OrganizationSponsorships { get; set; }
public DbSet<OrganizationUser> OrganizationUsers { get; set; }
public DbSet<Policy> Policies { get; set; }
public DbSet<Provider> Providers { get; set; }
@ -55,6 +56,7 @@ namespace Bit.Core.Repositories.EntityFramework
var eGroupUser = builder.Entity<GroupUser>();
var eInstallation = builder.Entity<Installation>();
var eOrganization = builder.Entity<Organization>();
var eOrganizationSponsorship = builder.Entity<OrganizationSponsorship>();
var eOrganizationUser = builder.Entity<OrganizationUser>();
var ePolicy = builder.Entity<Policy>();
var eProvider = builder.Entity<Provider>();
@ -76,6 +78,7 @@ namespace Bit.Core.Repositories.EntityFramework
eGroup.Property(c => c.Id).ValueGeneratedNever();
eInstallation.Property(c => c.Id).ValueGeneratedNever();
eOrganization.Property(c => c.Id).ValueGeneratedNever();
eOrganizationSponsorship.Property(c => c.Id).ValueGeneratedNever();
eOrganizationUser.Property(c => c.Id).ValueGeneratedNever();
ePolicy.Property(c => c.Id).ValueGeneratedNever();
eProvider.Property(c => c.Id).ValueGeneratedNever();
@ -115,6 +118,7 @@ namespace Bit.Core.Repositories.EntityFramework
eGroupUser.ToTable(nameof(GroupUser));
eInstallation.ToTable(nameof(Installation));
eOrganization.ToTable(nameof(Organization));
eOrganizationSponsorship.ToTable(nameof(OrganizationSponsorship));
eOrganizationUser.ToTable(nameof(OrganizationUser));
ePolicy.ToTable(nameof(Policy));
eProvider.ToTable(nameof(Provider));

View File

@ -96,5 +96,29 @@ namespace Bit.Core.Repositories.EntityFramework
{
await OrganizationUpdateStorage(id);
}
public override async Task DeleteAsync(Organization organization)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var orgEntity = await dbContext.FindAsync<EFModel.Organization>(organization.Id);
var sponsorships = dbContext.OrganizationSponsorships
.Where(os =>
os.SponsoringOrganizationId == organization.Id ||
os.SponsoredOrganizationId == organization.Id);
dbContext.RemoveRange(sponsorships.Where(os => os.CloudSponsor));
Guid? UpdatedOrgId(Guid? orgId) => orgId == organization.Id ? null : organization.Id;
foreach (var sponsorship in sponsorships.Where(os => !os.CloudSponsor))
{
sponsorship.SponsoredOrganizationId = UpdatedOrgId(sponsorship.SponsoredOrganizationId);
sponsorship.SponsoringOrganizationId = UpdatedOrgId(sponsorship.SponsoringOrganizationId);
}
dbContext.Remove(orgEntity);
await dbContext.SaveChangesAsync();
}
}
}
}

View File

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using EFModel = Bit.Core.Models.EntityFramework;
using TableModel = Bit.Core.Models.Table;
namespace Bit.Core.Repositories.EntityFramework
{
public class OrganizationSponsorshipRepository : Repository<TableModel.OrganizationSponsorship, EFModel.OrganizationSponsorship, Guid>, IOrganizationSponsorshipRepository
{
public OrganizationSponsorshipRepository(IServiceScopeFactory serviceScopeFactory, IMapper mapper)
: base(serviceScopeFactory, mapper, (DatabaseContext context) => context.OrganizationSponsorships)
{ }
public async Task<TableModel.OrganizationSponsorship> GetByOfferedToEmailAsync(string email)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var orgSponsorship = await GetDbSet(dbContext).Where(e => e.OfferedToEmail == email)
.FirstOrDefaultAsync();
return orgSponsorship;
}
}
public async Task<TableModel.OrganizationSponsorship> GetBySponsoredOrganizationIdAsync(Guid sponsoredOrganizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var orgSponsorship = await GetDbSet(dbContext).Where(e => e.SponsoredOrganizationId == sponsoredOrganizationId)
.FirstOrDefaultAsync();
return orgSponsorship;
}
}
public async Task<TableModel.OrganizationSponsorship> GetBySponsoringOrganizationUserIdAsync(Guid sponsoringOrganizationUserId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var orgSponsorship = await GetDbSet(dbContext).Where(e => e.SponsoringOrganizationUserId == sponsoringOrganizationUserId)
.FirstOrDefaultAsync();
return orgSponsorship;
}
}
}
}

View File

@ -67,12 +67,32 @@ namespace Bit.Core.Repositories.EntityFramework
return organizationUsers.Select(u => u.Id).ToList();
}
public override async Task DeleteAsync(OrganizationUser organizationUser) => await DeleteAsync(organizationUser.Id);
public async Task DeleteAsync(Guid organizationUserId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var orgUser = await dbContext.FindAsync<EfModel.OrganizationUser>(organizationUserId);
var sponsorships = dbContext.OrganizationSponsorships
.Where(os => os.SponsoringOrganizationUserId != default &&
os.SponsoringOrganizationUserId.Value == organizationUserId);
dbContext.RemoveRange(sponsorships);
dbContext.Remove(orgUser);
await dbContext.SaveChangesAsync();
}
}
public async Task DeleteManyAsync(IEnumerable<Guid> organizationUserIds)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var entities = dbContext.FindAsync<EfModel.OrganizationUser>(organizationUserIds);
var sponsorships = dbContext.OrganizationSponsorships
.Where(os => os.SponsoringOrganizationUserId != default &&
organizationUserIds.Contains(os.SponsoringOrganizationUserId ?? default));
dbContext.RemoveRange(sponsorships);
dbContext.RemoveRange(entities);
await dbContext.SaveChangesAsync();
}

View File

@ -17,16 +17,20 @@ namespace Bit.Core.Repositories.EntityFramework.Queries
from po in po_g.DefaultIfEmpty()
join p in dbContext.Providers on po.ProviderId equals p.Id into p_g
from p in p_g.DefaultIfEmpty()
join os in dbContext.OrganizationSponsorships on ou.Id equals os.SponsoringOrganizationUserId into os_g
from os in os_g.DefaultIfEmpty()
join ss in dbContext.SsoConfigs on ou.OrganizationId equals ss.OrganizationId into ss_g
from ss in ss_g.DefaultIfEmpty()
where ((su == null || !su.OrganizationId.HasValue) || su.OrganizationId == ou.OrganizationId)
select new { ou, o, su, p, ss };
select new { ou, o, su, p, ss, os };
return query.Select(x => new OrganizationUserOrganizationDetails
{
OrganizationId = x.ou.OrganizationId,
UserId = x.ou.UserId,
Name = x.o.Name,
Enabled = x.o.Enabled,
PlanType = x.o.PlanType,
UsePolicies = x.o.UsePolicies,
UseSso = x.o.UseSso,
UseKeyConnector = x.o.UseKeyConnector,
@ -52,6 +56,7 @@ namespace Bit.Core.Repositories.EntityFramework.Queries
PrivateKey = x.o.PrivateKey,
ProviderId = x.p.Id,
ProviderName = x.p.Name,
FamilySponsorshipFriendlyName = x.os.FriendlyName,
SsoConfig = x.ss.Data,
});
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Bit.Core.Models.Table;
namespace Bit.Core.Repositories
{
public interface IOrganizationSponsorshipRepository : IRepository<OrganizationSponsorship, Guid>
{
Task<OrganizationSponsorship> GetBySponsoringOrganizationUserIdAsync(Guid sponsoringOrganizationUserId);
Task<OrganizationSponsorship> GetBySponsoredOrganizationIdAsync(Guid sponsoredOrganizationId);
Task<OrganizationSponsorship> GetByOfferedToEmailAsync(string email);
}
}

View File

@ -0,0 +1,67 @@
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using Bit.Core.Models.Table;
using Bit.Core.Settings;
using Dapper;
namespace Bit.Core.Repositories.SqlServer
{
public class OrganizationSponsorshipRepository : Repository<OrganizationSponsorship, Guid>, IOrganizationSponsorshipRepository
{
public OrganizationSponsorshipRepository(GlobalSettings globalSettings)
: this(globalSettings.SqlServer.ConnectionString, globalSettings.SqlServer.ReadOnlyConnectionString)
{ }
public OrganizationSponsorshipRepository(string connectionString, string readOnlyConnectionString)
: base(connectionString, readOnlyConnectionString)
{ }
public async Task<OrganizationSponsorship> GetBySponsoringOrganizationUserIdAsync(Guid sponsoringOrganizationUserId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<OrganizationSponsorship>(
"[dbo].[OrganizationSponsorship_ReadBySponsoringOrganizationUserId]",
new
{
SponsoringOrganizationUserId = sponsoringOrganizationUserId
},
commandType: CommandType.StoredProcedure);
return results.SingleOrDefault();
}
}
public async Task<OrganizationSponsorship> GetBySponsoredOrganizationIdAsync(Guid sponsoredOrganizationId)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<OrganizationSponsorship>(
"[dbo].[OrganizationSponsorship_ReadBySponsoredOrganizationId]",
new { SponsoredOrganizationId = sponsoredOrganizationId },
commandType: CommandType.StoredProcedure);
return results.SingleOrDefault();
}
}
public async Task<OrganizationSponsorship> GetByOfferedToEmailAsync(string offeredToEmail)
{
using (var connection = new SqlConnection(ConnectionString))
{
var results = await connection.QueryAsync<OrganizationSponsorship>(
"[dbo].[OrganizationSponsorship_ReadByOfferedToEmail]",
new
{
OfferedToEmail = offeredToEmail
},
commandType: CommandType.StoredProcedure);
return results.SingleOrDefault();
}
}
}
}