1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-23 03:33:54 +00:00

[PM-24146] Remove stateProvider.activeUserId from ProviderService (#16258)

* Refactor provider service calls to include userId parameter

- Updated multiple components and services to pass userId when fetching provider data.
- Adjusted the ProviderService interface to require userId for get, get$, and getAll methods.
- Ensured consistent handling of userId across various components, enhancing data retrieval based on active user context.

* Remove deprecated type safety comments and use the getById utility for fetching providers.

* Update ProviderService methods to return undefined for non-existent providers

- Modified the return types of get$ and get methods in ProviderService to allow for undefined values, enhancing type safety.
- Adjusted the providers$ method to return only defined Provider arrays, ensuring consistent handling of provider data.

* Enhance provider permissions guard tests to include userId parameter

- Updated test cases in provider-permissions.guard.spec.ts to pass userId when calling ProviderService methods.
- Mocked AccountService to provide active account details for improved test coverage.
- Ensured consistent handling of userId across all relevant test scenarios.

* remove promise based api's from provider service, continue refactor

* cleanup observable logic

* cleanup

---------

Co-authored-by: Brandon <btreston@bitwarden.com>
This commit is contained in:
Rui Tomé
2025-09-22 16:06:28 +01:00
committed by GitHub
parent dbec02cf8d
commit b455cb5986
24 changed files with 342 additions and 281 deletions

View File

@@ -11,7 +11,14 @@
{{ o.name }}
</td>
<td bitCell>
<button type="button" bitButton [bitAction]="add(o)" class="tw-float-right">Add</button>
<button
type="button"
bitButton
[bitAction]="add(o, provider$ | async)"
class="tw-float-right"
>
Add
</button>
</td>
</tr>
</ng-template>

View File

@@ -1,10 +1,13 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { Component, Inject, OnInit } from "@angular/core";
import { Observable, switchMap } from "rxjs";
import { ProviderService } from "@bitwarden/common/admin-console/abstractions/provider.service";
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
import { Provider } from "@bitwarden/common/admin-console/models/domain/provider";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getUserId } from "@bitwarden/common/auth/services/account.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service";
@@ -22,7 +25,7 @@ interface AddOrganizationDialogData {
standalone: false,
})
export class AddOrganizationComponent implements OnInit {
protected provider: Provider;
protected provider$: Observable<Provider>;
protected loading = true;
constructor(
@@ -35,6 +38,7 @@ export class AddOrganizationComponent implements OnInit {
private validationService: ValidationService,
private dialogService: DialogService,
private toastService: ToastService,
private accountService: AccountService,
) {}
async ngOnInit() {
@@ -46,18 +50,21 @@ export class AddOrganizationComponent implements OnInit {
return;
}
this.provider = await this.providerService.get(this.data.providerId);
this.provider$ = this.accountService.activeAccount$.pipe(
getUserId,
switchMap((userId) => this.providerService.get$(this.data.providerId, userId)),
);
this.loading = false;
}
add(organization: Organization) {
add(organization: Organization, provider: Provider) {
return async () => {
const confirmed = await this.dialogService.openSimpleDialog({
title: organization.name,
content: {
key: "addOrganizationConfirmation",
placeholders: [organization.name, this.provider.name],
placeholders: [organization.name, provider.name],
},
type: "warning",
});

View File

@@ -3,7 +3,7 @@ import { Component } from "@angular/core";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
import { FormControl } from "@angular/forms";
import { ActivatedRoute, Router, RouterModule } from "@angular/router";
import { firstValueFrom, from, map, Observable, switchMap } from "rxjs";
import { combineLatest, firstValueFrom, from, map, Observable, switchMap } from "rxjs";
import { debounceTime, first } from "rxjs/operators";
import { JslibModule } from "@bitwarden/angular/jslib.module";
@@ -65,9 +65,10 @@ export class ClientsComponent {
this.activatedRoute.parent?.params.pipe(map((params) => params.providerId as string)) ??
new Observable();
protected provider$ = this.providerId$.pipe(
switchMap((providerId) => this.providerService.get$(providerId)),
);
protected provider$ = combineLatest([
this.providerId$,
this.accountService.activeAccount$.pipe(getUserId),
]).pipe(switchMap(([providerId, userId]) => this.providerService.get$(providerId, userId)));
protected isAdminOrServiceUser$ = this.provider$.pipe(
map(

View File

@@ -3,12 +3,16 @@
import { TestBed } from "@angular/core/testing";
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from "@angular/router";
import { mock, MockProxy } from "jest-mock-extended";
import { of } from "rxjs";
import { ProviderService } from "@bitwarden/common/admin-console/abstractions/provider.service";
import { ProviderUserType } from "@bitwarden/common/admin-console/enums";
import { Provider } from "@bitwarden/common/admin-console/models/domain/provider";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { UserId } from "@bitwarden/common/types/guid";
import { ToastService } from "@bitwarden/components";
import { newGuid } from "@bitwarden/guid";
import { providerPermissionsGuard } from "./provider-permissions.guard";
@@ -25,11 +29,23 @@ const providerFactory = (props: Partial<Provider> = {}) =>
describe("Provider Permissions Guard", () => {
let providerService: MockProxy<ProviderService>;
let accountService: MockProxy<AccountService>;
let route: MockProxy<ActivatedRouteSnapshot>;
let state: MockProxy<RouterStateSnapshot>;
const mockUserId = newGuid() as UserId;
beforeEach(() => {
providerService = mock<ProviderService>();
accountService = mock<AccountService>();
accountService.activeAccount$ = of({
id: mockUserId,
email: "test@example.com",
emailVerified: true,
name: "Test User",
});
route = mock<ActivatedRouteSnapshot>({
params: {
providerId: providerFactory().id,
@@ -44,12 +60,15 @@ describe("Provider Permissions Guard", () => {
{ provide: ToastService, useValue: mock<ToastService>() },
{ provide: I18nService, useValue: mock<I18nService>() },
{ provide: Router, useValue: mock<Router>() },
{ provide: AccountService, useValue: accountService },
],
});
});
it("blocks navigation if provider does not exist", async () => {
providerService.get.mockResolvedValue(null);
providerService.get$
.calledWith(providerFactory().id, mockUserId)
.mockReturnValue(of(undefined));
const actual = await TestBed.runInInjectionContext(
async () => await providerPermissionsGuard()(route, state),
@@ -60,7 +79,7 @@ describe("Provider Permissions Guard", () => {
it("permits navigation if no permissions are specified", async () => {
const provider = providerFactory();
providerService.get.calledWith(provider.id).mockResolvedValue(provider);
providerService.get$.calledWith(provider.id, mockUserId).mockReturnValue(of(provider));
const actual = await TestBed.runInInjectionContext(
async () => await providerPermissionsGuard()(route, state),
@@ -74,7 +93,7 @@ describe("Provider Permissions Guard", () => {
permissionsCallback.mockImplementation((_provider) => true);
const provider = providerFactory();
providerService.get.calledWith(provider.id).mockResolvedValue(provider);
providerService.get$.calledWith(provider.id, mockUserId).mockReturnValue(of(provider));
const actual = await TestBed.runInInjectionContext(
async () => await providerPermissionsGuard(permissionsCallback)(route, state),
@@ -88,7 +107,7 @@ describe("Provider Permissions Guard", () => {
const permissionsCallback = jest.fn();
permissionsCallback.mockImplementation((_org) => false);
const provider = providerFactory();
providerService.get.calledWith(provider.id).mockResolvedValue(provider);
providerService.get$.calledWith(provider.id, mockUserId).mockReturnValue(of(provider));
const actual = await TestBed.runInInjectionContext(
async () => await providerPermissionsGuard(permissionsCallback)(route, state),
@@ -104,7 +123,7 @@ describe("Provider Permissions Guard", () => {
type: ProviderUserType.ServiceUser,
enabled: false,
});
providerService.get.calledWith(org.id).mockResolvedValue(org);
providerService.get$.calledWith(org.id, mockUserId).mockReturnValue(of(org));
const actual = await TestBed.runInInjectionContext(
async () => await providerPermissionsGuard()(route, state),
@@ -118,7 +137,7 @@ describe("Provider Permissions Guard", () => {
type: ProviderUserType.ProviderAdmin,
enabled: false,
});
providerService.get.calledWith(org.id).mockResolvedValue(org);
providerService.get$.calledWith(org.id, mockUserId).mockReturnValue(of(org));
const actual = await TestBed.runInInjectionContext(
async () => await providerPermissionsGuard()(route, state),

View File

@@ -7,9 +7,12 @@ import {
Router,
RouterStateSnapshot,
} from "@angular/router";
import { firstValueFrom, switchMap } from "rxjs";
import { ProviderService } from "@bitwarden/common/admin-console/abstractions/provider.service";
import { Provider } from "@bitwarden/common/admin-console/models/domain/provider";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getUserId } from "@bitwarden/common/auth/services/account.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { ToastService } from "@bitwarden/components";
@@ -40,8 +43,14 @@ export function providerPermissionsGuard(
const router = inject(Router);
const i18nService = inject(I18nService);
const toastService = inject(ToastService);
const accountService = inject(AccountService);
const provider = await providerService.get(route.params.providerId);
const provider = await firstValueFrom(
accountService.activeAccount$.pipe(
getUserId,
switchMap((userId) => providerService.get$(route.params.providerId, userId)),
),
);
if (provider == null) {
return router.createUrlTree(["/"]);
}

View File

@@ -2,12 +2,14 @@
// @ts-strict-ignore
import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { firstValueFrom, switchMap } from "rxjs";
import { UserNamePipe } from "@bitwarden/angular/pipes/user-name.pipe";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
import { ProviderService } from "@bitwarden/common/admin-console/abstractions/provider.service";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getUserId } from "@bitwarden/common/auth/services/account.service";
import { EventResponse } from "@bitwarden/common/models/response/event.response";
import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
@@ -64,7 +66,13 @@ export class EventsComponent extends BaseEventsComponent implements OnInit {
// eslint-disable-next-line rxjs-angular/prefer-takeuntil, rxjs/no-async-subscribe
this.route.parent.parent.params.subscribe(async (params) => {
this.providerId = params.providerId;
const provider = await this.providerService.get(this.providerId);
const provider = await firstValueFrom(
this.accountService.activeAccount$.pipe(
getUserId,
switchMap((userId) => this.providerService.get$(this.providerId, userId)),
),
);
if (provider == null || !provider.useEvents) {
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises

View File

@@ -3,7 +3,7 @@
import { Component } from "@angular/core";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
import { ActivatedRoute, Router } from "@angular/router";
import { combineLatest, lastValueFrom, switchMap } from "rxjs";
import { combineLatest, firstValueFrom, lastValueFrom, switchMap } from "rxjs";
import { first } from "rxjs/operators";
import { UserNamePipe } from "@bitwarden/angular/pipes/user-name.pipe";
@@ -14,6 +14,8 @@ import { ProviderUserStatusType, ProviderUserType } from "@bitwarden/common/admi
import { ProviderUserBulkRequest } from "@bitwarden/common/admin-console/models/request/provider/provider-user-bulk.request";
import { ProviderUserConfirmRequest } from "@bitwarden/common/admin-console/models/request/provider/provider-user-confirm.request";
import { ProviderUserUserDetailsResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user.response";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getUserId } from "@bitwarden/common/auth/services/account.service";
import { EncryptService } from "@bitwarden/common/key-management/crypto/abstractions/encrypt.service";
import { ListResponse } from "@bitwarden/common/models/response/list.response";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
@@ -73,6 +75,7 @@ export class MembersComponent extends BaseMembersComponent<ProviderUser> {
private activatedRoute: ActivatedRoute,
private providerService: ProviderService,
private router: Router,
private accountService: AccountService,
) {
super(
apiService,
@@ -96,7 +99,13 @@ export class MembersComponent extends BaseMembersComponent<ProviderUser> {
this.dataSource.filter = peopleFilter(queryParams.search, null);
this.providerId = urlParams.providerId;
const provider = await this.providerService.get(this.providerId);
const provider = await firstValueFrom(
this.accountService.activeAccount$.pipe(
getUserId,
switchMap((userId) => this.providerService.get$(this.providerId, userId)),
),
);
if (!provider || !provider.canManageUsers) {
return await this.router.navigate(["../"], { relativeTo: this.activatedRoute });
}

View File

@@ -11,6 +11,8 @@ import { BusinessUnitPortalLogo, Icon, ProviderPortalLogo } from "@bitwarden/ass
import { ProviderService } from "@bitwarden/common/admin-console/abstractions/provider.service";
import { ProviderStatusType, ProviderType } from "@bitwarden/common/admin-console/enums";
import { Provider } from "@bitwarden/common/admin-console/models/domain/provider";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getUserId } from "@bitwarden/common/auth/services/account.service";
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { IconModule } from "@bitwarden/components";
@@ -56,6 +58,7 @@ export class ProvidersLayoutComponent implements OnInit, OnDestroy {
private providerService: ProviderService,
private configService: ConfigService,
private providerWarningsService: ProviderWarningsService,
private accountService: AccountService,
) {}
ngOnInit() {
@@ -65,8 +68,11 @@ export class ProvidersLayoutComponent implements OnInit, OnDestroy {
map((params) => params.providerId),
);
this.provider$ = providerId$.pipe(
switchMap((providerId) => this.providerService.get$(providerId)),
this.provider$ = combineLatest([
providerId$,
this.accountService.activeAccount$.pipe(getUserId),
]).pipe(
switchMap(([providerId, userId]) => this.providerService.get$(providerId, userId)),
takeUntil(this.destroy$),
);

View File

@@ -1,3 +1,4 @@
@let providers = providers$ | async;
<app-header></app-header>
<bit-container>

View File

@@ -1,9 +1,12 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { Component, OnInit } from "@angular/core";
import { map, Observable, switchMap, tap } from "rxjs";
import { ProviderService } from "@bitwarden/common/admin-console/abstractions/provider.service";
import { Provider } from "@bitwarden/common/admin-console/models/domain/provider";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getUserId } from "@bitwarden/common/auth/services/account.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { Utils } from "@bitwarden/common/platform/misc/utils";
@@ -13,24 +16,27 @@ import { Utils } from "@bitwarden/common/platform/misc/utils";
standalone: false,
})
export class ProvidersComponent implements OnInit {
providers: Provider[];
providers$: Observable<Provider[]>;
loaded = false;
actionPromise: Promise<any>;
constructor(
private providerService: ProviderService,
private i18nService: I18nService,
private accountService: AccountService,
) {}
async ngOnInit() {
ngOnInit() {
document.body.classList.remove("layout_frontend");
await this.load();
this.load();
}
async load() {
const providers = await this.providerService.getAll();
providers.sort(Utils.getSortFunction(this.i18nService, "name"));
this.providers = providers;
this.loaded = true;
load() {
this.providers$ = this.accountService.activeAccount$.pipe(
getUserId,
switchMap((userId) => this.providerService.providers$(userId)),
map((p) => p.sort(Utils.getSortFunction(this.i18nService, "name"))),
tap(() => (this.loaded = true)),
);
}
}

View File

@@ -21,6 +21,8 @@ import {
} from "@bitwarden/common/admin-console/enums";
import { Provider } from "@bitwarden/common/admin-console/models/domain/provider";
import { ProviderOrganizationOrganizationDetailsResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-organization.response";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getUserId } from "@bitwarden/common/auth/services/account.service";
import { BillingApiServiceAbstraction } from "@bitwarden/common/billing/abstractions";
import { PlanResponse } from "@bitwarden/common/billing/models/response/plan.response";
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
@@ -87,9 +89,10 @@ export class ManageClientsComponent {
this.activatedRoute.parent?.params.pipe(map((params) => params.providerId as string)) ??
new Observable();
protected provider$ = this.providerId$.pipe(
switchMap((providerId) => this.providerService.get$(providerId)),
);
protected provider$ = combineLatest([
this.providerId$,
this.accountService.activeAccount$.pipe(getUserId),
]).pipe(switchMap(([providerId, userId]) => this.providerService.get$(providerId, userId)));
protected isAdminOrServiceUser$ = this.provider$.pipe(
map(
@@ -126,6 +129,7 @@ export class ManageClientsComponent {
private webProviderService: WebProviderService,
private billingNotificationService: BillingNotificationService,
private configService: ConfigService,
private accountService: AccountService,
) {
this.activatedRoute.queryParams.pipe(first(), takeUntilDestroyed()).subscribe((queryParams) => {
this.searchControl.setValue(queryParams.search);
@@ -133,7 +137,7 @@ export class ManageClientsComponent {
this.provider$
.pipe(
map((provider: Provider) => {
map((provider: Provider | undefined) => {
if (provider?.providerStatus !== ProviderStatusType.Billable) {
return from(
this.router.navigate(["../clients"], {
@@ -158,7 +162,8 @@ export class ManageClientsComponent {
async load() {
try {
const providerId = await firstValueFrom(this.providerId$);
const provider = await firstValueFrom(this.providerService.get$(providerId));
const userId = await firstValueFrom(getUserId(this.accountService.activeAccount$));
const provider = await firstValueFrom(this.providerService.get$(providerId, userId));
if (provider?.providerType === ProviderType.BusinessUnit) {
this.pageTitle = this.i18nService.t("businessUnits");
this.clientColumnHeader = this.i18nService.t("businessUnit");

View File

@@ -4,11 +4,15 @@ import { firstValueFrom } from "rxjs";
import { ProviderService } from "@bitwarden/common/admin-console/abstractions/provider.service";
import { ProviderStatusType } from "@bitwarden/common/admin-console/enums";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getUserId } from "@bitwarden/common/auth/services/account.service";
export const hasConsolidatedBilling: CanActivateFn = async (route: ActivatedRouteSnapshot) => {
const providerService = inject(ProviderService);
const accountService = inject(AccountService);
const provider = await firstValueFrom(providerService.get$(route.params.providerId));
const userId = await firstValueFrom(getUserId(accountService.activeAccount$));
const provider = await firstValueFrom(providerService.get$(route.params.providerId, userId));
if (!provider || provider.providerStatus !== ProviderStatusType.Billable) {
return createUrlTreeFromSnapshot(route, ["/providers", route.params.providerId]);

View File

@@ -83,8 +83,12 @@ const BANK_ACCOUNT_VERIFIED_COMMAND = new CommandDefinition<{
export class ProviderPaymentDetailsComponent implements OnInit, OnDestroy {
private viewState$ = new BehaviorSubject<View | null>(null);
private provider$ = this.activatedRoute.params.pipe(
switchMap(({ providerId }) => this.providerService.get$(providerId)),
private provider$ = combineLatest([
this.activatedRoute.params,
this.accountService.activeAccount$.pipe(getUserId),
]).pipe(
switchMap(([{ providerId }, userId]) => this.providerService.get$(providerId, userId)),
filter((provider) => provider != null),
);
private load$: Observable<View> = this.provider$.pipe(