Skip to content

Commit c54c39b

Browse files
MGibson1justindbaurCarlos Muentesjlf0devManolachi
authored
Feature/self hosted families for enterprise (bitwarden#1991)
* Families for enterprise/split up organization sponsorship service (bitwarden#1829) * Split OrganizationSponsorshipService into commands * Use tokenable for token validation * Use interfaces to set up for DI * Use commands over services * Move service tests to command tests * Value types can't be null * Run dotnet format * Update src/Core/OrganizationFeatures/OrganizationSponsorships/FamiliesForEnterprise/CancelSponsorshipCommand.cs Co-authored-by: Justin Baur <admin@justinbaur.com> * Fix controller tests Co-authored-by: Justin Baur <admin@justinbaur.com> * Families for enterprise/split up organization sponsorship service (bitwarden#1875) * Split OrganizationSponsorshipService into commands * Use tokenable for token validation * Use interfaces to set up for DI * Use commands over services * Move service tests to command tests * Value types can't be null * Run dotnet format * Update src/Core/OrganizationFeatures/OrganizationSponsorships/FamiliesForEnterprise/CancelSponsorshipCommand.cs Co-authored-by: Justin Baur <admin@justinbaur.com> * Fix controller tests * Split create and send sponsorships * Split up create sponsorship * Add self hosted commands to dependency injection * Add field to store cloud billing sync key on self host instances * Fix typo * Fix data protector purpose of sponsorship offers * Split cloud and selfhosted sponsorship offer tokenable * Generate offer from self hosted with all necessary auth data * Add Required properties to constructor * Split up cancel sponsorship command * Split revoke sponsorship command between cloud and self hosted * Fix/f4e multiple sponsorships (bitwarden#1838) * Use sponosorship from validate to redeem * Update tests * Format * Remove sponsorship service * Run dotnet format * Fix self hosted only controller attribute * Clean up file structure and fixes * Remove unneeded tokenables * Remove obsolete commands * Do not require file/class prefix if unnecessary * Update Organizaiton sprocs * Remove unnecessary models * Fix tests * Generalize LicenseService path calculation Use async file read and deserialization * Use interfaces for testability * Remove unused usings * Correct test direction * Test license reading * remove unused usings * Format Co-authored-by: Justin Baur <admin@justinbaur.com> * Improve DataProtectorTokenFactory test coverage (bitwarden#1884) * Add encstring to server * Test factory Co-authored-by: Carlos Muentes <cmuentes@bitwarden.com> * Format * Remove SymmetricKeyProtectedString Not needed * Set ForcInvalid Co-authored-by: Carlos Muentes <cmuentes@bitwarden.com> * Feature/self f4e/api keys (bitwarden#1896) * Add in ApiKey * Work on API Key table * Work on apikey table * Fix response model * Work on information for UI * Work on last sync date * Work on sync status * Work on auth * Work on tokenable * Work on merge * Add custom requirement * Add policy * Run formatting * Work on EF Migrations * Work on OrganizationConnection * Work on database * Work on additional database table * Run formatting * Small fixes * More cleanup * Cleanup * Add RevisionDate * Add GO * Finish Sql project * Add newlines * Fix stored proc file * Fix sqlproj * Add newlines * Fix table * Add navigation property * Delete Connections when organization is deleted * Add connection validation * Start adding ID column * Work on ID column * Work on SQL migration * Work on migrations * Run formatting * Fix test build * Fix sprocs * Work on migrations * Fix Create table * Fix sproc * Add prints to migration * Add default value * Update EF migrations * Formatting * Add to integration tests * Minor fixes * Formatting * Cleanup * Address PR feedback * Address more PR feedback * Fix formatting * Fix formatting * Fix * Address PR feedback * Remove accidential change * Fix SQL build * Run formatting * Address PR feedback * Add sync data to OrganizationUserOrgDetails * Add comments * Remove OrganizationConnectionService interface * Remove unused using * Address PR feedback * Formatting * Minor fix * Feature/self f4e/update db (bitwarden#1930) * Fix migration * Fix TimesRenewed * Add comments * Make two properties non-nullable * Remove need for SponsoredOrg on SH (bitwarden#1934) * Remove need for SponsoredOrg on SH * Add Family prefix * Add check for enterprise org on BillingSync key (bitwarden#1936) * [PS-10] Feature/sponsorships removed at end of term (bitwarden#1938) * Rename commands to min unique names * Inject revoke command based on self hosting * WIP: Remove/Revoke marks to delete * Complete WIP * Improve remove/revoke tests * PR review * Fail validation if sponsorship has failed to sync for 6 months * Feature/do not accept old self host sponsorships (bitwarden#1939) * Do not accept >6mo old self-hosted sponsorships * Give disabled grace period of 3 months * Fix issues of Sql.proj differing from migration outcome (bitwarden#1942) * Fix issues of Sql.proj differing from migration outcome * Yoink int tests * Add missing assert helpers * Feature/org sponsorship sync (bitwarden#1922) * Self-hosted side sync first pass TODO: * flush out org sponsorship model * implement cloud side * process cloud-side response and update self-hosted records * sync scaffolding second pass * remove list of Org User ids from sync and begin work on SelfHostedRevokeSponsorship * allow authenticated http calls from server to return a result * update models * add logic for sync and change offer email template * add billing sync key and hide CreateSponsorship without user * fix tests * add job scheduling * add authorize attributes to endpoints * separate models into data/model and request/response * batch sync more, add EnableCloudCommunication for testing * send emails in bulk * make userId and sponsorshipType non nullable * batch more on self hosted side of sync * remove TODOs and formatting * changed logic of cloud sync * let BaseIdentityClientService handle all logging * call sync from scheduled job on self host * create bulk db operations for OrganizationSponsorships * remove SponsoredOrgId from sync, return default from server http call * validate BillingSyncKey during sync revert changes to CreateSponsorshipCommand * revert changes to ICreateSponsorshipCommand * add some tests * add DeleteExpiredSponsorshipsJob * add cloud sync test * remove extra method * formatting * prevent new sponsorships from disabled orgs * update packages * - pulled out send sponsorship command dependency from sync on cloud - don't throw error when sponsorships are empty - formatting * formatting models * more formatting * remove licensingService dependency from selfhosted sync * use installation urls and formatting * create constructor for RequestModel and formatting * add date parameter to OrganizationSponsorship_DeleteExpired * add new migration * formatting * rename OrganizationCreateSponsorshipRequestModel to OrganizationSponsorshipCreateRequestModel * prevent whole sync from failing if one sponsorship type is unsupported * deserialize config and billingsynckey from org connection * alter log message when sync disabled * Add grace period to disabled orgs * return early on self hosted if there are no sponsorships in database * rename BillingSyncConfig * send sponsorship offers from controller * allow config to be a null object * better exception handling in sync scheduler * add ef migrations * formatting * fix tests * fix validate test Co-authored-by: Matt Gibson <mgibson@bitwarden.com> * Fix OrganizationApiKey issues (bitwarden#1941) Co-authored-by: Justin Baur <admin@justinbaur.com> * Feature/org sponsorship self hosted tests (bitwarden#1947) * Self-hosted side sync first pass TODO: * flush out org sponsorship model * implement cloud side * process cloud-side response and update self-hosted records * sync scaffolding second pass * remove list of Org User ids from sync and begin work on SelfHostedRevokeSponsorship * allow authenticated http calls from server to return a result * update models * add logic for sync and change offer email template * add billing sync key and hide CreateSponsorship without user * fix tests * add job scheduling * add authorize attributes to endpoints * separate models into data/model and request/response * batch sync more, add EnableCloudCommunication for testing * send emails in bulk * make userId and sponsorshipType non nullable * batch more on self hosted side of sync * remove TODOs and formatting * changed logic of cloud sync * let BaseIdentityClientService handle all logging * call sync from scheduled job on self host * create bulk db operations for OrganizationSponsorships * remove SponsoredOrgId from sync, return default from server http call * validate BillingSyncKey during sync revert changes to CreateSponsorshipCommand * revert changes to ICreateSponsorshipCommand * add some tests * add DeleteExpiredSponsorshipsJob * add cloud sync test * remove extra method * formatting * prevent new sponsorships from disabled orgs * update packages * - pulled out send sponsorship command dependency from sync on cloud - don't throw error when sponsorships are empty - formatting * formatting models * more formatting * remove licensingService dependency from selfhosted sync * use installation urls and formatting * create constructor for RequestModel and formatting * add date parameter to OrganizationSponsorship_DeleteExpired * add new migration * formatting * rename OrganizationCreateSponsorshipRequestModel to OrganizationSponsorshipCreateRequestModel * prevent whole sync from failing if one sponsorship type is unsupported * deserialize config and billingsynckey from org connection * add mockHttp nuget package and use httpclientfactory * fix current tests * WIP of creating tests * WIP of new self hosted tests * WIP self hosted tests * finish self hosted tests * formatting * format of interface * remove extra config file * added newlines Co-authored-by: Matt Gibson <mgibson@bitwarden.com> * Fix Organization_DeleteById (bitwarden#1950) * Fix Organization_Delete * Fix L * [PS-4] block enterprise user from sponsoring itself (bitwarden#1943) * [PS-248] Feature/add connections enabled endpoint (bitwarden#1953) * Move Organization models to sub namespaces * Add Organization Connection api endpoints * Get all connections rather than just enabled ones * Add missing services to DI * pluralize private api endpoints * Add type protection to org connection request/response * Fix route * Use nullable Id to signify no connection * Test Get Connections enabled * Fix data discoverer * Also drop this sproc for rerunning * Id is the OUTPUT of create sprocs * Fix connection config parsing * Linter fixes * update sqlproj file name * Use param xdocs on methods * Simplify controller path attribute * Use JsonDocument to avoid escaped json in our response/request strings * Fix JsonDoc tests * Linter fixes * Fix ApiKey Command and add tests (bitwarden#1949) * Fix ApiKey command * Formatting * Fix test failures introduced in bitwarden#1943 (bitwarden#1957) * Remove "Did you know?" copy from emails. (bitwarden#1962) * Remove "Did you know" * Remove jsonIf helper * Feature/fix send single sponsorship offer email (bitwarden#1956) * Fix sponsorship offer email * Do not sanitize org name * PR feedback * Feature/f4e sync event [PS-75] (bitwarden#1963) * Create sponsorship sync event type * Add InstallationId to Event model * Add combinatorics-based test case generators * Log sponsorships sync event on sync * Linter and test fixes * Fix failing test * Migrate sprocs and view * Remove unused `using`s * [PS-190] Add manual sync trigger in self hosted (bitwarden#1955) * WIP add button to admin project for billing sync * add connection table to view page * minor fixes for self hosted side of sync * fixes number of bugs for cloud side of sync * deserialize before returning for some reason * add json attributes to return models * list of sponsorships parameter is immutable, add secondary list * change sproc name * add error handling * Fix tests * modify call to connection * Update src/Admin/Controllers/OrganizationsController.cs Co-authored-by: Matt Gibson <mgibson@bitwarden.com> * undo change to sproc name * simplify logic * Update src/Core/OrganizationFeatures/OrganizationSponsorships/FamiliesForEnterprise/Cloud/CloudSyncSponsorshipsCommand.cs Co-authored-by: Matt Gibson <mgibson@bitwarden.com> * register services despite if self hosted or cloud * remove json properties * revert merge conflict Co-authored-by: Matt Gibson <mgibson@bitwarden.com> * Update OrganizationSponsorship valid until when updating org expirati… (bitwarden#1966) * Update OrganizationSponsorship valid until when updating org expiration date * Linter fixes * [PS-7] change revert email copy and add ValidUntil to sponsorship (bitwarden#1965) * change revert email copy and add ValidUntil to sponsorship * add 15 days if no ValidUntil * Chore/merge/self hosted families for enterprise (bitwarden#1972) * Log swallowed HttpRequestExceptions (bitwarden#1866) Co-authored-by: Hinton <oscar@oscarhinton.com> * Allow for utilization of readonly db connection (bitwarden#1937) * Bump the pin of the download-artifacts action to bypass the broken GitHub api (bitwarden#1952) * Bumped version to 1.48.0 (bitwarden#1958) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * [EC-160] Give Provider Users access to all org ciphers and collections (bitwarden#1959) * Bumped version to 1.48.1 (bitwarden#1961) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Avoid sending "user need confirmation" emails when there are no org admins (bitwarden#1960) * Remove noncompliant users for new policies (bitwarden#1951) * [PS-284] Allow installation clients to not need a user. (bitwarden#1968) * Allow installation clients to not need a user. * Run formatting Co-authored-by: Andrei <30410186+Manolachi@users.noreply.github.com> Co-authored-by: Hinton <oscar@oscarhinton.com> Co-authored-by: sneakernuts <671942+sneakernuts@users.noreply.github.com> Co-authored-by: Joseph Flinn <58369717+joseph-flinn@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com> Co-authored-by: Justin Baur <136baur@gmail.com> * Fix/license file not found (bitwarden#1974) * Handle null license * Throw hint message if license is not found by the admin project. * Use CloudOrganizationId from Connection config * Change test to support change * Fix test Co-authored-by: Matt Gibson <mgibson@bitwarden.com> * Feature/f4e selfhosted rename migration to .sql (bitwarden#1971) * rename migration to .sql * format * Add unit tests to self host F4E (bitwarden#1975) * Work on tests * Added more tests * Run linting * Address PR feedback * Fix AssertRecent * Linting * Fixed empty tests * Fix/misc self hosted f4e (bitwarden#1973) * Allow setting of ApiUri * Return updates sponsorshipsData objects * Bind arguments by name * Greedy load sponsorships to email. When upsert was called, it creates Ids on _all_ records, which meant that the lazy-evaluation from this call always returned an empty list. * add scope for sync command DI in job. simplify error logic * update the sync job to get CloudOrgId from the BillingSyncKey Co-authored-by: Jacob Fink <jfink@bitwarden.com> * Chore/merge/self hosted families for enterprise (bitwarden#1987) * Log swallowed HttpRequestExceptions (bitwarden#1866) Co-authored-by: Hinton <oscar@oscarhinton.com> * Allow for utilization of readonly db connection (bitwarden#1937) * Bump the pin of the download-artifacts action to bypass the broken GitHub api (bitwarden#1952) * Bumped version to 1.48.0 (bitwarden#1958) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * [EC-160] Give Provider Users access to all org ciphers and collections (bitwarden#1959) * Bumped version to 1.48.1 (bitwarden#1961) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Avoid sending "user need confirmation" emails when there are no org admins (bitwarden#1960) * Remove noncompliant users for new policies (bitwarden#1951) * [PS-284] Allow installation clients to not need a user. (bitwarden#1968) * Allow installation clients to not need a user. * Run formatting * Use accept flow for sponsorship offers (bitwarden#1964) * PS-82 check send 2FA email for new devices on TwoFactorController send-email-login (bitwarden#1977) * [Bug] Skip WebAuthn 2fa event logs during login flow (bitwarden#1978) * [Bug] Supress WebAuthn 2fa event logs during login process * Formatting * Simplified method call with new paramter input * Update RealIps Description (bitwarden#1980) Describe the syntax of the real_ips configuration key with an example, to prevent type errors in the `setup` container when parsing `config.yml` * add proper URI validation to duo host (bitwarden#1984) * captcha scores (bitwarden#1967) * captcha scores * some api fixes * check bot on captcha attribute * Update src/Core/Services/Implementations/HCaptchaValidationService.cs Co-authored-by: e271828- <e271828-@users.noreply.github.com> Co-authored-by: Chad Scharf <3904944+cscharf@users.noreply.github.com> Co-authored-by: e271828- <e271828-@users.noreply.github.com> * ensure no path specific in duo host (bitwarden#1985) Co-authored-by: Andrei <30410186+Manolachi@users.noreply.github.com> Co-authored-by: Hinton <oscar@oscarhinton.com> Co-authored-by: sneakernuts <671942+sneakernuts@users.noreply.github.com> Co-authored-by: Joseph Flinn <58369717+joseph-flinn@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com> Co-authored-by: Justin Baur <136baur@gmail.com> Co-authored-by: Federico Maccaroni <fedemkr@gmail.com> Co-authored-by: Vincent Salucci <26154748+vincentsalucci@users.noreply.github.com> Co-authored-by: Jordan Cooks <notnamed@users.noreply.github.com> Co-authored-by: Kyle Spearrin <kspearrin@users.noreply.github.com> Co-authored-by: Chad Scharf <3904944+cscharf@users.noreply.github.com> Co-authored-by: e271828- <e271828-@users.noreply.github.com> * Address feedback (bitwarden#1990) Co-authored-by: Justin Baur <admin@justinbaur.com> Co-authored-by: Carlos Muentes <cmuentes@bitwarden.com> Co-authored-by: Jake Fink <jfink@bitwarden.com> Co-authored-by: Justin Baur <136baur@gmail.com> Co-authored-by: Andrei <30410186+Manolachi@users.noreply.github.com> Co-authored-by: Hinton <oscar@oscarhinton.com> Co-authored-by: sneakernuts <671942+sneakernuts@users.noreply.github.com> Co-authored-by: Joseph Flinn <58369717+joseph-flinn@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com> Co-authored-by: Federico Maccaroni <fedemkr@gmail.com> Co-authored-by: Vincent Salucci <26154748+vincentsalucci@users.noreply.github.com> Co-authored-by: Jordan Cooks <notnamed@users.noreply.github.com> Co-authored-by: Kyle Spearrin <kspearrin@users.noreply.github.com> Co-authored-by: Chad Scharf <3904944+cscharf@users.noreply.github.com> Co-authored-by: e271828- <e271828-@users.noreply.github.com>
1 parent e5a9d3d commit c54c39b

File tree

304 files changed

+18511
-1557
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

304 files changed

+18511
-1557
lines changed

.config/dotnet-tools.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,4 @@
2727
]
2828
}
2929
}
30-
}
30+
}

.vscode/launch.json

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
"Identity",
4141
"Sso",
4242
"Icons",
43+
"Billing"
4344
],
4445
"presentation": {
4546
"hidden": false,
@@ -125,6 +126,28 @@
125126
"/Views": "${workspaceFolder}/Views"
126127
}
127128
},
129+
{
130+
"name": "Billing",
131+
"presentation": {
132+
"hidden": false,
133+
"group": "cloud",
134+
"order": 10
135+
},
136+
"requireExactSource": true,
137+
"type": "coreclr",
138+
"request": "launch",
139+
"preLaunchTask": "buildBilling",
140+
"program": "${workspaceFolder}/src/Billing/bin/Debug/net5.0/Billing.dll",
141+
"args": [],
142+
"cwd": "${workspaceFolder}/src/Billing",
143+
"stopAtEntry": false,
144+
"env": {
145+
"ASPNETCORE_ENVIRONMENT": "Development"
146+
},
147+
"sourceFileMap": {
148+
"/Views": "${workspaceFolder}/Views"
149+
}
150+
},
128151
{
129152
"name": "Admin",
130153
"presentation": {

.vscode/tasks.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,22 @@
8989
"isDefault": true
9090
}
9191
},
92+
{
93+
"label": "buildBilling",
94+
"command": "dotnet",
95+
"type": "process",
96+
"args": [
97+
"build",
98+
"${workspaceFolder}/src/Billing/Billing.csproj",
99+
"/property:GenerateFullPaths=true",
100+
"/consoleloggerparameters:NoSummary"
101+
],
102+
"problemMatcher": "$msCompile",
103+
"group": {
104+
"kind": "build",
105+
"isDefault": true
106+
}
107+
},
92108
{
93109
"label": "clean",
94110
"type": "shell",

bitwarden_license/src/Sso/Startup.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ public void ConfigureServices(IServiceCollection services)
7878
services.AddCustomIdentityServices(globalSettings);
7979

8080
// Services
81-
services.AddBaseServices();
81+
services.AddBaseServices(globalSettings);
8282
services.AddDefaultServices(globalSettings);
8383
services.AddCoreLocalizationServices();
8484
}

bitwarden_license/test/CmmCore.Test/packages.lock.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,15 @@
298298
"IdentityModel": "4.3.0"
299299
}
300300
},
301+
"Kralizek.AutoFixture.Extensions.MockHttp": {
302+
"type": "Transitive",
303+
"resolved": "1.2.0",
304+
"contentHash": "6zmks7/5mVczazv910N7V2EdiU6B+rY61lwdgVO0o2iZuTI6KI3T+Hgkrjv0eGOKYucq2OMC+gnAc5Ej2ajoTQ==",
305+
"dependencies": {
306+
"AutoFixture": "4.11.0",
307+
"RichardSzalay.MockHttp": "6.0.0"
308+
}
309+
},
301310
"libsodium": {
302311
"type": "Transitive",
303312
"resolved": "1.0.18",
@@ -1598,6 +1607,11 @@
15981607
"System.Diagnostics.DiagnosticSource": "4.7.1"
15991608
}
16001609
},
1610+
"RichardSzalay.MockHttp": {
1611+
"type": "Transitive",
1612+
"resolved": "6.0.0",
1613+
"contentHash": "bStGNqIX/MGYtML7K3EzdsE/k5HGVAcg7XgN23TQXGXqxNC9fvYFR94fA0sGM5hAT36R+BBGet6ZDQxXL/IPxg=="
1614+
},
16011615
"runtime.debian.8-x64.runtime.native.System.Security.Cryptography.OpenSsl": {
16021616
"type": "Transitive",
16031617
"resolved": "4.3.2",
@@ -3547,6 +3561,7 @@
35473561
"AutoFixture.AutoNSubstitute": "4.14.0",
35483562
"AutoFixture.Xunit2": "4.14.0",
35493563
"Core": "1.47.1",
3564+
"Kralizek.AutoFixture.Extensions.MockHttp": "1.2.0",
35503565
"Microsoft.NET.Test.Sdk": "16.6.1",
35513566
"NSubstitute": "4.2.2",
35523567
"xunit": "2.4.1"
@@ -3599,6 +3614,7 @@
35993614
"AutoFixture.Xunit2": "4.14.0",
36003615
"Common": "1.47.1",
36013616
"Core": "1.47.1",
3617+
"Kralizek.AutoFixture.Extensions.MockHttp": "1.2.0",
36023618
"Microsoft.NET.Test.Sdk": "16.6.1",
36033619
"Moq": "4.16.1",
36043620
"NSubstitute": "4.2.2",

src/Admin/Controllers/OrganizationsController.cs

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Linq;
34
using System.Threading.Tasks;
45
using Bit.Admin.Models;
56
using Bit.Core.Entities;
67
using Bit.Core.Enums;
78
using Bit.Core.Models.Business;
9+
using Bit.Core.Models.OrganizationConnectionConfigs;
10+
using Bit.Core.OrganizationFeatures.OrganizationSponsorships.FamiliesForEnterprise.Interfaces;
811
using Bit.Core.Repositories;
912
using Bit.Core.Services;
1013
using Bit.Core.Settings;
@@ -19,11 +22,14 @@ public class OrganizationsController : Controller
1922
{
2023
private readonly IOrganizationRepository _organizationRepository;
2124
private readonly IOrganizationUserRepository _organizationUserRepository;
25+
private readonly IOrganizationConnectionRepository _organizationConnectionRepository;
26+
private readonly ISelfHostedSyncSponsorshipsCommand _syncSponsorshipsCommand;
2227
private readonly ICipherRepository _cipherRepository;
2328
private readonly ICollectionRepository _collectionRepository;
2429
private readonly IGroupRepository _groupRepository;
2530
private readonly IPolicyRepository _policyRepository;
2631
private readonly IPaymentService _paymentService;
32+
private readonly ILicensingService _licensingService;
2733
private readonly IApplicationCacheService _applicationCacheService;
2834
private readonly GlobalSettings _globalSettings;
2935
private readonly IReferenceEventService _referenceEventService;
@@ -32,23 +38,29 @@ public class OrganizationsController : Controller
3238
public OrganizationsController(
3339
IOrganizationRepository organizationRepository,
3440
IOrganizationUserRepository organizationUserRepository,
41+
IOrganizationConnectionRepository organizationConnectionRepository,
42+
ISelfHostedSyncSponsorshipsCommand syncSponsorshipsCommand,
3543
ICipherRepository cipherRepository,
3644
ICollectionRepository collectionRepository,
3745
IGroupRepository groupRepository,
3846
IPolicyRepository policyRepository,
3947
IPaymentService paymentService,
48+
ILicensingService licensingService,
4049
IApplicationCacheService applicationCacheService,
4150
GlobalSettings globalSettings,
4251
IReferenceEventService referenceEventService,
4352
IUserService userService)
4453
{
4554
_organizationRepository = organizationRepository;
4655
_organizationUserRepository = organizationUserRepository;
56+
_organizationConnectionRepository = organizationConnectionRepository;
57+
_syncSponsorshipsCommand = syncSponsorshipsCommand;
4758
_cipherRepository = cipherRepository;
4859
_collectionRepository = collectionRepository;
4960
_groupRepository = groupRepository;
5061
_policyRepository = policyRepository;
5162
_paymentService = paymentService;
63+
_licensingService = licensingService;
5264
_applicationCacheService = applicationCacheService;
5365
_globalSettings = globalSettings;
5466
_referenceEventService = referenceEventService;
@@ -104,7 +116,8 @@ public async Task<IActionResult> View(Guid id)
104116
policies = await _policyRepository.GetManyByOrganizationIdAsync(id);
105117
}
106118
var users = await _organizationUserRepository.GetManyDetailsByOrganizationAsync(id);
107-
return View(new OrganizationViewModel(organization, users, ciphers, collections, groups, policies));
119+
var billingSyncConnection = _globalSettings.EnableCloudCommunication ? await _organizationConnectionRepository.GetByOrganizationIdTypeAsync(id, OrganizationConnectionType.CloudBillingSync) : null;
120+
return View(new OrganizationViewModel(organization, billingSyncConnection, users, ciphers, collections, groups, policies));
108121
}
109122

110123
[SelfHosted(NotSelfHostedOnly = true)]
@@ -130,8 +143,9 @@ public async Task<IActionResult> Edit(Guid id)
130143
}
131144
var users = await _organizationUserRepository.GetManyDetailsByOrganizationAsync(id);
132145
var billingInfo = await _paymentService.GetBillingAsync(organization);
146+
var billingSyncConnection = _globalSettings.EnableCloudCommunication ? await _organizationConnectionRepository.GetByOrganizationIdTypeAsync(id, OrganizationConnectionType.CloudBillingSync) : null;
133147
return View(new OrganizationEditModel(organization, users, ciphers, collections, groups, policies,
134-
billingInfo, _globalSettings));
148+
billingInfo, billingSyncConnection, _globalSettings));
135149
}
136150

137151
[HttpPost]
@@ -164,5 +178,40 @@ public async Task<IActionResult> Delete(Guid id)
164178

165179
return RedirectToAction("Index");
166180
}
181+
182+
public async Task<IActionResult> TriggerBillingSync(Guid id)
183+
{
184+
var organization = await _organizationRepository.GetByIdAsync(id);
185+
if (organization == null)
186+
{
187+
return RedirectToAction("Index");
188+
}
189+
var connection = (await _organizationConnectionRepository.GetEnabledByOrganizationIdTypeAsync(id, OrganizationConnectionType.CloudBillingSync)).FirstOrDefault();
190+
if (connection != null)
191+
{
192+
try
193+
{
194+
var config = connection.GetConfig<BillingSyncConfig>();
195+
await _syncSponsorshipsCommand.SyncOrganization(id, config.CloudOrganizationId, connection);
196+
TempData["ConnectionActivated"] = id;
197+
TempData["ConnectionError"] = null;
198+
}
199+
catch (Exception ex)
200+
{
201+
TempData["ConnectionError"] = ex.Message;
202+
}
203+
204+
if (_globalSettings.SelfHosted)
205+
{
206+
return RedirectToAction("View", new { id });
207+
}
208+
else
209+
{
210+
return RedirectToAction("Edit", new { id });
211+
}
212+
}
213+
return RedirectToAction("Index");
214+
}
215+
167216
}
168217
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using System;
2+
using System.Threading.Tasks;
3+
using Bit.Core;
4+
using Bit.Core.Jobs;
5+
using Bit.Core.Repositories;
6+
using Bit.Core.Settings;
7+
using Microsoft.Extensions.Logging;
8+
using Quartz;
9+
10+
namespace Bit.Admin.Jobs
11+
{
12+
public class DatabaseExpiredSponsorshipsJob : BaseJob
13+
{
14+
private GlobalSettings _globalSettings;
15+
private readonly IMaintenanceRepository _maintenanceRepository;
16+
17+
public DatabaseExpiredSponsorshipsJob(
18+
IMaintenanceRepository maintenanceRepository,
19+
ILogger<DatabaseExpiredSponsorshipsJob> logger,
20+
GlobalSettings globalSettings)
21+
: base(logger)
22+
{
23+
_maintenanceRepository = maintenanceRepository;
24+
_globalSettings = globalSettings;
25+
}
26+
27+
protected override async Task ExecuteJobAsync(IJobExecutionContext context)
28+
{
29+
if (_globalSettings.SelfHosted && !_globalSettings.EnableCloudCommunication)
30+
{
31+
return;
32+
}
33+
_logger.LogInformation(Constants.BypassFiltersEventId, "Execute job task: DeleteExpiredSponsorshipsAsync");
34+
35+
// allow a 90 day grace period before deleting
36+
var deleteDate = DateTime.UtcNow.AddDays(-90);
37+
38+
await _maintenanceRepository.DeleteExpiredSponsorshipsAsync(deleteDate);
39+
_logger.LogInformation(Constants.BypassFiltersEventId, "Finished job task: DeleteExpiredSponsorshipsAsync");
40+
}
41+
}
42+
}

src/Admin/Jobs/JobsHostedService.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,11 @@ public override async Task StartAsync(CancellationToken cancellationToken)
5555
.StartNow()
5656
.WithCronSchedule("0 0 0 ? * SUN", x => x.InTimeZone(timeZone))
5757
.Build();
58+
var everyMondayAtMidnightTrigger = TriggerBuilder.Create()
59+
.WithIdentity("EveryMondayAtMidnightTrigger")
60+
.StartNow()
61+
.WithCronSchedule("0 0 0 ? * MON", x => x.InTimeZone(timeZone))
62+
.Build();
5863
var everyDayAtMidnightUtc = TriggerBuilder.Create()
5964
.WithIdentity("EveryDayAtMidnightUtc")
6065
.StartNow()
@@ -67,7 +72,8 @@ public override async Task StartAsync(CancellationToken cancellationToken)
6772
new Tuple<Type, ITrigger>(typeof(DatabaseExpiredGrantsJob), everyFridayAt10pmTrigger),
6873
new Tuple<Type, ITrigger>(typeof(DatabaseUpdateStatisticsJob), everySaturdayAtMidnightTrigger),
6974
new Tuple<Type, ITrigger>(typeof(DatabaseRebuildlIndexesJob), everySundayAtMidnightTrigger),
70-
new Tuple<Type, ITrigger>(typeof(DeleteCiphersJob), everyDayAtMidnightUtc)
75+
new Tuple<Type, ITrigger>(typeof(DeleteCiphersJob), everyDayAtMidnightUtc),
76+
new Tuple<Type, ITrigger>(typeof(DatabaseExpiredSponsorshipsJob), everyMondayAtMidnightTrigger)
7177
};
7278

7379
if (!_globalSettings.SelfHosted)
@@ -88,6 +94,7 @@ public static void AddJobsServices(IServiceCollection services, bool selfHosted)
8894
services.AddTransient<DatabaseUpdateStatisticsJob>();
8995
services.AddTransient<DatabaseRebuildlIndexesJob>();
9096
services.AddTransient<DatabaseExpiredGrantsJob>();
97+
services.AddTransient<DatabaseExpiredSponsorshipsJob>();
9198
services.AddTransient<DeleteSendsJob>();
9299
services.AddTransient<DeleteCiphersJob>();
93100
}

src/Admin/Models/OrganizationEditModel.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
using Bit.Core.Entities;
55
using Bit.Core.Enums;
66
using Bit.Core.Models.Business;
7-
using Bit.Core.Models.Data;
7+
using Bit.Core.Models.Data.Organizations.OrganizationUsers;
88
using Bit.Core.Settings;
99
using Bit.Core.Utilities;
1010

@@ -16,8 +16,9 @@ public OrganizationEditModel() { }
1616

1717
public OrganizationEditModel(Organization org, IEnumerable<OrganizationUserUserDetails> orgUsers,
1818
IEnumerable<Cipher> ciphers, IEnumerable<Collection> collections, IEnumerable<Group> groups,
19-
IEnumerable<Policy> policies, BillingInfo billingInfo, GlobalSettings globalSettings)
20-
: base(org, orgUsers, ciphers, collections, groups, policies)
19+
IEnumerable<Policy> policies, BillingInfo billingInfo, IEnumerable<OrganizationConnection> connections,
20+
GlobalSettings globalSettings)
21+
: base(org, connections, orgUsers, ciphers, collections, groups, policies)
2122
{
2223
BillingInfo = billingInfo;
2324
BraintreeMerchantId = globalSettings.Braintree.MerchantId;

src/Admin/Models/OrganizationViewModel.cs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
1-
using System;
2-
using System.Collections.Generic;
1+
using System.Collections.Generic;
32
using System.Linq;
43
using Bit.Core.Entities;
54
using Bit.Core.Enums;
6-
using Bit.Core.Models.Data;
5+
using Bit.Core.Models.Data.Organizations.OrganizationUsers;
76

87
namespace Bit.Admin.Models
98
{
109
public class OrganizationViewModel
1110
{
1211
public OrganizationViewModel() { }
1312

14-
public OrganizationViewModel(Organization org, IEnumerable<OrganizationUserUserDetails> orgUsers,
15-
IEnumerable<Cipher> ciphers, IEnumerable<Collection> collections, IEnumerable<Group> groups,
16-
IEnumerable<Policy> policies)
13+
public OrganizationViewModel(Organization org, IEnumerable<OrganizationConnection> connections,
14+
IEnumerable<OrganizationUserUserDetails> orgUsers, IEnumerable<Cipher> ciphers, IEnumerable<Collection> collections,
15+
IEnumerable<Group> groups, IEnumerable<Policy> policies)
1716
{
1817
Organization = org;
18+
Connections = connections ?? Enumerable.Empty<OrganizationConnection>();
1919
HasPublicPrivateKeys = org.PublicKey != null && org.PrivateKey != null;
2020
UserInvitedCount = orgUsers.Count(u => u.Status == OrganizationUserStatusType.Invited);
2121
UserAcceptedCount = orgUsers.Count(u => u.Status == OrganizationUserStatusType.Accepted);
@@ -36,6 +36,7 @@ public OrganizationViewModel(Organization org, IEnumerable<OrganizationUserUserD
3636
}
3737

3838
public Organization Organization { get; set; }
39+
public IEnumerable<OrganizationConnection> Connections { get; set; }
3940
public string Owners { get; set; }
4041
public string Admins { get; set; }
4142
public int UserInvitedCount { get; set; }

0 commit comments

Comments
 (0)