mirror of
https://github.com/bitwarden/browser
synced 2026-02-22 12:24:01 +00:00
Merge branch 'main' into vault/pm-27632/sdk-cipher-ops
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@bitwarden/web-vault",
|
||||
"version": "2025.12.2",
|
||||
"version": "2026.1.0",
|
||||
"scripts": {
|
||||
"build:oss": "webpack",
|
||||
"build:bit": "webpack -c ../../bitwarden_license/bit-web/webpack.config.js",
|
||||
|
||||
@@ -2,18 +2,24 @@
|
||||
// @ts-strict-ignore
|
||||
import { computed, Signal } from "@angular/core";
|
||||
import { toSignal } from "@angular/core/rxjs-interop";
|
||||
import { map } from "rxjs";
|
||||
import { Observable, Subject, map } from "rxjs";
|
||||
|
||||
import {
|
||||
OrganizationUserStatusType,
|
||||
ProviderUserStatusType,
|
||||
} from "@bitwarden/common/admin-console/enums";
|
||||
import { ProviderUserUserDetailsResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user.response";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { TableDataSource } from "@bitwarden/components";
|
||||
|
||||
import { StatusType, UserViewTypes } from "./base-members.component";
|
||||
import { OrganizationUserView } from "../organizations/core/views/organization-user.view";
|
||||
|
||||
export type StatusType = OrganizationUserStatusType | ProviderUserStatusType;
|
||||
|
||||
export type UserViewTypes = ProviderUser | OrganizationUserView;
|
||||
export type ProviderUser = ProviderUserUserDetailsResponse;
|
||||
|
||||
/**
|
||||
* Default maximum for most bulk operations (confirm, remove, delete, etc.)
|
||||
@@ -100,6 +106,8 @@ export abstract class PeopleTableDataSource<T extends UserViewTypes> extends Tab
|
||||
this.data?.filter((u) => u.status === this.statusType.Confirmed).length ?? 0;
|
||||
this.revokedUserCount =
|
||||
this.data?.filter((u) => u.status === this.statusType.Revoked).length ?? 0;
|
||||
|
||||
this.checkedUsersUpdated$.next();
|
||||
}
|
||||
|
||||
override get data() {
|
||||
@@ -112,6 +120,15 @@ export abstract class PeopleTableDataSource<T extends UserViewTypes> extends Tab
|
||||
* @param select check the user (true), uncheck the user (false), or toggle the current state (null)
|
||||
*/
|
||||
checkUser(user: T, select?: boolean) {
|
||||
this.setUserChecked(user, select);
|
||||
this.checkedUsersUpdated$.next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal method to set checked state without triggering emissions.
|
||||
* Use this in bulk operations to avoid excessive emissions.
|
||||
*/
|
||||
private setUserChecked(user: T, select?: boolean) {
|
||||
(user as any).checked = select == null ? !(user as any).checked : select;
|
||||
}
|
||||
|
||||
@@ -119,6 +136,12 @@ export abstract class PeopleTableDataSource<T extends UserViewTypes> extends Tab
|
||||
return this.data.filter((u) => (u as any).checked);
|
||||
}
|
||||
|
||||
private checkedUsersUpdated$ = new Subject<void>();
|
||||
|
||||
usersUpdated(): Observable<T[]> {
|
||||
return this.checkedUsersUpdated$.asObservable().pipe(map(() => this.getCheckedUsers()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets checked users in the order they appear in the filtered/sorted table view.
|
||||
* Use this when enforcing limits to ensure visual consistency (top N visible rows stay checked).
|
||||
@@ -147,8 +170,10 @@ export abstract class PeopleTableDataSource<T extends UserViewTypes> extends Tab
|
||||
: Math.min(filteredUsers.length, MaxCheckedCount);
|
||||
|
||||
for (let i = 0; i < selectCount; i++) {
|
||||
this.checkUser(filteredUsers[i], select);
|
||||
this.setUserChecked(filteredUsers[i], select);
|
||||
}
|
||||
|
||||
this.checkedUsersUpdated$.next();
|
||||
}
|
||||
|
||||
uncheckAllUsers() {
|
||||
@@ -190,7 +215,10 @@ export abstract class PeopleTableDataSource<T extends UserViewTypes> extends Tab
|
||||
}
|
||||
|
||||
// Uncheck users beyond the limit
|
||||
users.slice(limit).forEach((user) => this.checkUser(user, false));
|
||||
users.slice(limit).forEach((user) => this.setUserChecked(user, false));
|
||||
|
||||
// Emit once after all unchecking is done
|
||||
this.checkedUsersUpdated$.next();
|
||||
|
||||
return users.slice(0, limit);
|
||||
}
|
||||
@@ -213,3 +241,26 @@ export abstract class PeopleTableDataSource<T extends UserViewTypes> extends Tab
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class ProvidersTableDataSource extends PeopleTableDataSource<ProviderUser> {
|
||||
protected statusType = ProviderUserStatusType;
|
||||
}
|
||||
|
||||
export class MembersTableDataSource extends PeopleTableDataSource<OrganizationUserView> {
|
||||
protected statusType = OrganizationUserStatusType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to determine if the confirm users banner should be shown
|
||||
* @params dataSource Either a ProvidersTableDataSource or a MembersTableDataSource
|
||||
*/
|
||||
export function showConfirmBanner(
|
||||
dataSource: ProvidersTableDataSource | MembersTableDataSource,
|
||||
): boolean {
|
||||
return (
|
||||
dataSource.activeUserCount > 1 &&
|
||||
dataSource.confirmedUserCount > 0 &&
|
||||
dataSource.confirmedUserCount < 3 &&
|
||||
dataSource.acceptedUserCount > 0
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,12 +7,12 @@ import { combineLatest, of, Subject, switchMap, takeUntil } from "rxjs";
|
||||
import {
|
||||
CollectionAdminService,
|
||||
OrganizationUserApiService,
|
||||
CollectionView,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import {
|
||||
getOrganizationById,
|
||||
OrganizationService,
|
||||
} from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { CollectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// @ts-strict-ignore
|
||||
import { Component, Input } from "@angular/core";
|
||||
|
||||
import { CollectionView } from "@bitwarden/admin-console/common";
|
||||
import { CollectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { uuidAsString } from "@bitwarden/common/platform/abstractions/sdk/sdk.service";
|
||||
import { CollectionId } from "@bitwarden/sdk-internal";
|
||||
|
||||
|
||||
@@ -1,2 +1 @@
|
||||
export * from "./utils";
|
||||
export * from "./collection-badge";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Pipe, PipeTransform } from "@angular/core";
|
||||
|
||||
import { CollectionView } from "@bitwarden/admin-console/common";
|
||||
import { CollectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
|
||||
@Pipe({
|
||||
name: "collectionNameFromId",
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
import { CollectionView } from "@bitwarden/admin-console/common";
|
||||
import { CollectionId, OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { TreeNode } from "@bitwarden/common/vault/models/domain/tree-node";
|
||||
import { newGuid } from "@bitwarden/guid";
|
||||
|
||||
import { getNestedCollectionTree, getFlatCollectionTree } from "./collection-utils";
|
||||
|
||||
describe("CollectionUtils Service", () => {
|
||||
describe("getNestedCollectionTree", () => {
|
||||
it("should return collections properly sorted if provided out of order", () => {
|
||||
// Arrange
|
||||
const collections: CollectionView[] = [];
|
||||
|
||||
const parentCollection = new CollectionView({
|
||||
name: "Parent",
|
||||
organizationId: "orgId" as OrganizationId,
|
||||
id: newGuid() as CollectionId,
|
||||
});
|
||||
|
||||
const childCollection = new CollectionView({
|
||||
name: "Parent/Child",
|
||||
organizationId: "orgId" as OrganizationId,
|
||||
id: newGuid() as CollectionId,
|
||||
});
|
||||
|
||||
collections.push(childCollection);
|
||||
collections.push(parentCollection);
|
||||
|
||||
// Act
|
||||
const result = getNestedCollectionTree(collections);
|
||||
|
||||
// Assert
|
||||
expect(result[0].node.name).toBe("Parent");
|
||||
expect(result[0].children[0].node.name).toBe("Child");
|
||||
});
|
||||
|
||||
it("should return an empty array if no collections are provided", () => {
|
||||
// Arrange
|
||||
const collections: CollectionView[] = [];
|
||||
|
||||
// Act
|
||||
const result = getNestedCollectionTree(collections);
|
||||
|
||||
// Assert
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFlatCollectionTree", () => {
|
||||
it("should flatten a tree node with no children", () => {
|
||||
// Arrange
|
||||
const collection = new CollectionView({
|
||||
name: "Test Collection",
|
||||
id: "test-id" as CollectionId,
|
||||
organizationId: "orgId" as OrganizationId,
|
||||
});
|
||||
|
||||
const treeNodes: TreeNode<CollectionView>[] = [
|
||||
new TreeNode<CollectionView>(collection, {} as TreeNode<CollectionView>),
|
||||
];
|
||||
|
||||
// Act
|
||||
const result = getFlatCollectionTree(treeNodes);
|
||||
|
||||
// Assert
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0]).toBe(collection);
|
||||
});
|
||||
|
||||
it("should flatten a tree node with children", () => {
|
||||
// Arrange
|
||||
const parentCollection = new CollectionView({
|
||||
name: "Parent",
|
||||
id: "parent-id" as CollectionId,
|
||||
organizationId: "orgId" as OrganizationId,
|
||||
});
|
||||
|
||||
const child1Collection = new CollectionView({
|
||||
name: "Child 1",
|
||||
id: "child1-id" as CollectionId,
|
||||
organizationId: "orgId" as OrganizationId,
|
||||
});
|
||||
|
||||
const child2Collection = new CollectionView({
|
||||
name: "Child 2",
|
||||
id: "child2-id" as CollectionId,
|
||||
organizationId: "orgId" as OrganizationId,
|
||||
});
|
||||
|
||||
const grandchildCollection = new CollectionView({
|
||||
name: "Grandchild",
|
||||
id: "grandchild-id" as CollectionId,
|
||||
organizationId: "orgId" as OrganizationId,
|
||||
});
|
||||
|
||||
const parentNode = new TreeNode<CollectionView>(
|
||||
parentCollection,
|
||||
{} as TreeNode<CollectionView>,
|
||||
);
|
||||
const child1Node = new TreeNode<CollectionView>(child1Collection, parentNode);
|
||||
const child2Node = new TreeNode<CollectionView>(child2Collection, parentNode);
|
||||
const grandchildNode = new TreeNode<CollectionView>(grandchildCollection, child1Node);
|
||||
|
||||
parentNode.children = [child1Node, child2Node];
|
||||
child1Node.children = [grandchildNode];
|
||||
|
||||
const treeNodes: TreeNode<CollectionView>[] = [parentNode];
|
||||
|
||||
// Act
|
||||
const result = getFlatCollectionTree(treeNodes);
|
||||
|
||||
// Assert
|
||||
expect(result.length).toBe(4);
|
||||
expect(result[0]).toBe(parentCollection);
|
||||
expect(result).toContain(child1Collection);
|
||||
expect(result).toContain(child2Collection);
|
||||
expect(result).toContain(grandchildCollection);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,87 +0,0 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
import {
|
||||
CollectionAdminView,
|
||||
CollectionView,
|
||||
NestingDelimiter,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { TreeNode } from "@bitwarden/common/vault/models/domain/tree-node";
|
||||
import { ServiceUtils } from "@bitwarden/common/vault/service-utils";
|
||||
|
||||
export function getNestedCollectionTree(
|
||||
collections: CollectionAdminView[],
|
||||
): TreeNode<CollectionAdminView>[];
|
||||
export function getNestedCollectionTree(collections: CollectionView[]): TreeNode<CollectionView>[];
|
||||
export function getNestedCollectionTree(
|
||||
collections: (CollectionView | CollectionAdminView)[],
|
||||
): TreeNode<CollectionView | CollectionAdminView>[] {
|
||||
if (!collections) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Collections need to be cloned because ServiceUtils.nestedTraverse actively
|
||||
// modifies the names of collections.
|
||||
// These changes risk affecting collections store in StateService.
|
||||
const clonedCollections: CollectionView[] | CollectionAdminView[] = collections
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
.map(cloneCollection);
|
||||
|
||||
const all: TreeNode<CollectionView | CollectionAdminView>[] = [];
|
||||
const groupedByOrg = new Map<OrganizationId, (CollectionView | CollectionAdminView)[]>();
|
||||
clonedCollections.map((c) => {
|
||||
const key = c.organizationId;
|
||||
(groupedByOrg.get(key) ?? groupedByOrg.set(key, []).get(key)!).push(c);
|
||||
});
|
||||
for (const group of groupedByOrg.values()) {
|
||||
const nodes: TreeNode<CollectionView | CollectionAdminView>[] = [];
|
||||
for (const c of group) {
|
||||
const parts = c.name ? c.name.replace(/^\/+|\/+$/g, "").split(NestingDelimiter) : [];
|
||||
ServiceUtils.nestedTraverse(nodes, 0, parts, c, undefined, NestingDelimiter);
|
||||
}
|
||||
all.push(...nodes);
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
export function cloneCollection(collection: CollectionView): CollectionView;
|
||||
export function cloneCollection(collection: CollectionAdminView): CollectionAdminView;
|
||||
export function cloneCollection(
|
||||
collection: CollectionView | CollectionAdminView,
|
||||
): CollectionView | CollectionAdminView {
|
||||
let cloned;
|
||||
|
||||
if (collection instanceof CollectionAdminView) {
|
||||
cloned = Object.assign(
|
||||
new CollectionAdminView({ ...collection, name: collection.name }),
|
||||
collection,
|
||||
);
|
||||
} else {
|
||||
cloned = Object.assign(
|
||||
new CollectionView({ ...collection, name: collection.name }),
|
||||
collection,
|
||||
);
|
||||
}
|
||||
return cloned;
|
||||
}
|
||||
|
||||
export function getFlatCollectionTree(
|
||||
nodes: TreeNode<CollectionAdminView>[],
|
||||
): CollectionAdminView[];
|
||||
export function getFlatCollectionTree(nodes: TreeNode<CollectionView>[]): CollectionView[];
|
||||
export function getFlatCollectionTree(
|
||||
nodes: TreeNode<CollectionView | CollectionAdminView>[],
|
||||
): (CollectionView | CollectionAdminView)[] {
|
||||
if (!nodes || nodes.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return nodes.flatMap((node) => {
|
||||
if (!node.children || node.children.length === 0) {
|
||||
return [node.node];
|
||||
}
|
||||
|
||||
const children = getFlatCollectionTree(node.children);
|
||||
return [node.node, ...children];
|
||||
});
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./collection-utils";
|
||||
@@ -15,15 +15,15 @@ import { PremiumUpgradePromptService } from "@bitwarden/common/vault/abstraction
|
||||
import { TreeNode } from "@bitwarden/common/vault/models/domain/tree-node";
|
||||
import { RestrictedItemTypesService } from "@bitwarden/common/vault/services/restricted-item-types.service";
|
||||
import { DialogService, ToastService } from "@bitwarden/components";
|
||||
|
||||
import { VaultFilterComponent as BaseVaultFilterComponent } from "../../../../vault/individual-vault/vault-filter/components/vault-filter.component";
|
||||
import { VaultFilterService } from "../../../../vault/individual-vault/vault-filter/services/abstractions/vault-filter.service";
|
||||
import {
|
||||
VaultFilterServiceAbstraction,
|
||||
VaultFilterList,
|
||||
VaultFilterSection,
|
||||
VaultFilterType,
|
||||
} from "../../../../vault/individual-vault/vault-filter/shared/models/vault-filter-section.type";
|
||||
import { CollectionFilter } from "../../../../vault/individual-vault/vault-filter/shared/models/vault-filter.type";
|
||||
CollectionFilter,
|
||||
} from "@bitwarden/vault";
|
||||
|
||||
import { VaultFilterComponent as BaseVaultFilterComponent } from "../../../../vault/individual-vault/vault-filter/components/vault-filter.component";
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
|
||||
@@ -49,7 +49,7 @@ export class VaultFilterComponent
|
||||
protected destroy$: Subject<void>;
|
||||
|
||||
constructor(
|
||||
protected vaultFilterService: VaultFilterService,
|
||||
protected vaultFilterService: VaultFilterServiceAbstraction,
|
||||
protected policyService: PolicyService,
|
||||
protected i18nService: I18nService,
|
||||
protected platformUtilsService: PlatformUtilsService,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { NgModule } from "@angular/core";
|
||||
|
||||
import { SearchModule } from "@bitwarden/components";
|
||||
import { VaultFilterServiceAbstraction } from "@bitwarden/vault";
|
||||
|
||||
import { VaultFilterService as VaultFilterServiceAbstraction } from "../../../../vault/individual-vault/vault-filter/services/abstractions/vault-filter.service";
|
||||
import { VaultFilterSharedModule } from "../../../../vault/individual-vault/vault-filter/shared/vault-filter-shared.module";
|
||||
|
||||
import { VaultFilterComponent } from "./vault-filter.component";
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
import { Injectable, OnDestroy } from "@angular/core";
|
||||
import { map, Observable, ReplaySubject, Subject } from "rxjs";
|
||||
|
||||
import { CollectionAdminView, CollectionService } from "@bitwarden/admin-console/common";
|
||||
import { CollectionService } from "@bitwarden/admin-console/common";
|
||||
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
|
||||
import { CollectionAdminView } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { StateProvider } from "@bitwarden/common/platform/state";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction";
|
||||
import { TreeNode } from "@bitwarden/common/vault/models/domain/tree-node";
|
||||
|
||||
import { VaultFilterService as BaseVaultFilterService } from "../../../../vault/individual-vault/vault-filter/services/vault-filter.service";
|
||||
import { CollectionFilter } from "../../../../vault/individual-vault/vault-filter/shared/models/vault-filter.type";
|
||||
import { VaultFilterService as BaseVaultFilterService, CollectionFilter } from "@bitwarden/vault";
|
||||
|
||||
@Injectable()
|
||||
export class VaultFilterService extends BaseVaultFilterService implements OnDestroy {
|
||||
|
||||
@@ -7,12 +7,12 @@ import { Component, EventEmitter, Input, Output } from "@angular/core";
|
||||
import { Router } from "@angular/router";
|
||||
import { firstValueFrom, switchMap } from "rxjs";
|
||||
|
||||
import { CollectionAdminService } from "@bitwarden/admin-console/common";
|
||||
import { JslibModule } from "@bitwarden/angular/jslib.module";
|
||||
import {
|
||||
CollectionAdminService,
|
||||
CollectionAdminView,
|
||||
Unassigned,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { JslibModule } from "@bitwarden/angular/jslib.module";
|
||||
} from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
@@ -27,14 +27,10 @@ import {
|
||||
SearchModule,
|
||||
SimpleDialogOptions,
|
||||
} from "@bitwarden/components";
|
||||
import { NewCipherMenuComponent } from "@bitwarden/vault";
|
||||
import { NewCipherMenuComponent, All, RoutedVaultFilterModel } from "@bitwarden/vault";
|
||||
|
||||
import { HeaderModule } from "../../../../layouts/header/header.module";
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import {
|
||||
All,
|
||||
RoutedVaultFilterModel,
|
||||
} from "../../../../vault/individual-vault/vault-filter/shared/models/routed-vault-filter.model";
|
||||
import { CollectionDialogTabType } from "../../shared/components/collection-dialog";
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
|
||||
@@ -27,19 +27,22 @@ import {
|
||||
takeUntil,
|
||||
} from "rxjs/operators";
|
||||
|
||||
import {
|
||||
CollectionAdminService,
|
||||
CollectionAdminView,
|
||||
CollectionService,
|
||||
CollectionView,
|
||||
Unassigned,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { CollectionAdminService, CollectionService } from "@bitwarden/admin-console/common";
|
||||
import { SearchPipe } from "@bitwarden/angular/pipes/search.pipe";
|
||||
import { NoResults } from "@bitwarden/assets/svg";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { EventCollectionService } from "@bitwarden/common/abstractions/event/event-collection.service";
|
||||
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import {
|
||||
CollectionView,
|
||||
CollectionAdminView,
|
||||
Unassigned,
|
||||
} from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import {
|
||||
getFlatCollectionTree,
|
||||
getNestedCollectionTree,
|
||||
} from "@bitwarden/common/admin-console/utils";
|
||||
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/billing-api.service.abstraction";
|
||||
@@ -81,6 +84,13 @@ import {
|
||||
CollectionAssignmentResult,
|
||||
DecryptionFailureDialogComponent,
|
||||
PasswordRepromptService,
|
||||
VaultFilterServiceAbstraction as VaultFilterService,
|
||||
RoutedVaultFilterBridgeService,
|
||||
RoutedVaultFilterService,
|
||||
createFilterFunction,
|
||||
All,
|
||||
RoutedVaultFilterModel,
|
||||
VaultFilter,
|
||||
} from "@bitwarden/vault";
|
||||
import {
|
||||
OrganizationFreeTrialWarningComponent,
|
||||
@@ -102,15 +112,6 @@ import {
|
||||
BulkDeleteDialogResult,
|
||||
openBulkDeleteDialog,
|
||||
} from "../../../vault/individual-vault/bulk-action-dialogs/bulk-delete-dialog/bulk-delete-dialog.component";
|
||||
import { VaultFilterService } from "../../../vault/individual-vault/vault-filter/services/abstractions/vault-filter.service";
|
||||
import { RoutedVaultFilterBridgeService } from "../../../vault/individual-vault/vault-filter/services/routed-vault-filter-bridge.service";
|
||||
import { RoutedVaultFilterService } from "../../../vault/individual-vault/vault-filter/services/routed-vault-filter.service";
|
||||
import { createFilterFunction } from "../../../vault/individual-vault/vault-filter/shared/models/filter-function";
|
||||
import {
|
||||
All,
|
||||
RoutedVaultFilterModel,
|
||||
} from "../../../vault/individual-vault/vault-filter/shared/models/routed-vault-filter.model";
|
||||
import { VaultFilter } from "../../../vault/individual-vault/vault-filter/shared/models/vault-filter.model";
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
import { GroupApiService, GroupView } from "../core";
|
||||
import { openEntityEventsDialog } from "../manage/entity-events.component";
|
||||
@@ -126,7 +127,6 @@ import {
|
||||
BulkCollectionsDialogResult,
|
||||
} from "./bulk-collections-dialog";
|
||||
import { CollectionAccessRestrictedComponent } from "./collection-access-restricted.component";
|
||||
import { getFlatCollectionTree, getNestedCollectionTree } from "./utils";
|
||||
import { VaultFilterModule } from "./vault-filter/vault-filter.module";
|
||||
import { VaultHeaderComponent } from "./vault-header/vault-header.component";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CollectionAccessSelectionView } from "@bitwarden/admin-console/common";
|
||||
import { CollectionAccessSelectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
|
||||
export interface AddEditGroupDetail {
|
||||
id: string;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
import { CollectionAccessSelectionView } from "@bitwarden/admin-console/common";
|
||||
import { CollectionAccessSelectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { View } from "@bitwarden/common/models/view/view";
|
||||
|
||||
import { GroupDetailsResponse } from "../services/group/responses/group.response";
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
import {
|
||||
CollectionAccessSelectionView,
|
||||
OrganizationUserDetailsResponse,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { OrganizationUserDetailsResponse } from "@bitwarden/admin-console/common";
|
||||
import {
|
||||
OrganizationUserStatusType,
|
||||
OrganizationUserType,
|
||||
} from "@bitwarden/common/admin-console/enums";
|
||||
import { PermissionsApi } from "@bitwarden/common/admin-console/models/api/permissions.api";
|
||||
import { CollectionAccessSelectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
|
||||
export class OrganizationUserAdminView {
|
||||
id: string;
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
import {
|
||||
OrganizationUserUserDetailsResponse,
|
||||
CollectionAccessSelectionView,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { OrganizationUserUserDetailsResponse } from "@bitwarden/admin-console/common";
|
||||
import {
|
||||
OrganizationUserStatusType,
|
||||
OrganizationUserType,
|
||||
} from "@bitwarden/common/admin-console/enums";
|
||||
import { PermissionsApi } from "@bitwarden/common/admin-console/models/api/permissions.api";
|
||||
import { CollectionAccessSelectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
|
||||
export class OrganizationUserView {
|
||||
id: string;
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
|
||||
import {
|
||||
CollectionAdminService,
|
||||
CollectionAdminView,
|
||||
OrganizationUserApiService,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
@@ -26,6 +25,7 @@ import {
|
||||
getOrganizationById,
|
||||
OrganizationService,
|
||||
} from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { CollectionAdminView } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
|
||||
@@ -17,15 +17,15 @@ import {
|
||||
} from "rxjs";
|
||||
import { debounceTime, first } from "rxjs/operators";
|
||||
|
||||
import { CollectionService } from "@bitwarden/admin-console/common";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import {
|
||||
CollectionService,
|
||||
CollectionData,
|
||||
Collection,
|
||||
CollectionView,
|
||||
CollectionDetailsResponse,
|
||||
CollectionResponse,
|
||||
CollectionView,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
Collection,
|
||||
CollectionData,
|
||||
} from "@bitwarden/common/admin-console/models/collections";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { ListResponse } from "@bitwarden/common/models/response/list.response";
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
// @ts-strict-ignore
|
||||
import { Component, Inject, OnInit } from "@angular/core";
|
||||
import { FormControl, FormGroup } from "@angular/forms";
|
||||
import { firstValueFrom } from "rxjs";
|
||||
|
||||
import { OrganizationManagementPreferencesService } from "@bitwarden/common/admin-console/abstractions/organization-management-preferences/organization-management-preferences.service";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { DIALOG_DATA, DialogConfig, DialogRef, DialogService } from "@bitwarden/components";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
@@ -14,7 +17,8 @@ export type UserConfirmDialogData = {
|
||||
name: string;
|
||||
userId: string;
|
||||
publicKey: Uint8Array;
|
||||
confirmUser: (publicKey: Uint8Array) => Promise<void>;
|
||||
// @TODO remove this when doing feature flag cleanup for members component refactor.
|
||||
confirmUser?: (publicKey: Uint8Array) => Promise<void>;
|
||||
};
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
@@ -42,6 +46,7 @@ export class UserConfirmComponent implements OnInit {
|
||||
private keyService: KeyService,
|
||||
private logService: LogService,
|
||||
private organizationManagementPreferencesService: OrganizationManagementPreferencesService,
|
||||
private configService: ConfigService,
|
||||
) {
|
||||
this.name = data.name;
|
||||
this.userId = data.userId;
|
||||
@@ -64,16 +69,21 @@ export class UserConfirmComponent implements OnInit {
|
||||
|
||||
submit = async () => {
|
||||
if (this.loading) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.formGroup.value.dontAskAgain) {
|
||||
await this.organizationManagementPreferencesService.autoConfirmFingerPrints.set(true);
|
||||
}
|
||||
|
||||
await this.data.confirmUser(this.publicKey);
|
||||
const membersComponentRefactorEnabled = await firstValueFrom(
|
||||
this.configService.getFeatureFlag$(FeatureFlag.MembersComponentRefactor),
|
||||
);
|
||||
if (!membersComponentRefactorEnabled) {
|
||||
await this.data.confirmUser(this.publicKey);
|
||||
}
|
||||
|
||||
this.dialogRef.close();
|
||||
this.dialogRef.close(true);
|
||||
};
|
||||
|
||||
static open(dialogService: DialogService, config: DialogConfig<UserConfirmDialogData>) {
|
||||
|
||||
@@ -36,6 +36,7 @@ type BulkConfirmDialogParams = {
|
||||
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
|
||||
@Component({
|
||||
templateUrl: "bulk-confirm-dialog.component.html",
|
||||
selector: "member-bulk-comfirm-dialog",
|
||||
standalone: false,
|
||||
})
|
||||
export class BulkConfirmDialogComponent extends BaseBulkConfirmComponent {
|
||||
|
||||
@@ -20,6 +20,7 @@ type BulkDeleteDialogParams = {
|
||||
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
|
||||
@Component({
|
||||
templateUrl: "bulk-delete-dialog.component.html",
|
||||
selector: "member-bulk-delete-dialog",
|
||||
standalone: false,
|
||||
})
|
||||
export class BulkDeleteDialogComponent {
|
||||
|
||||
@@ -24,6 +24,7 @@ export type BulkEnableSecretsManagerDialogData = {
|
||||
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
|
||||
@Component({
|
||||
templateUrl: `bulk-enable-sm-dialog.component.html`,
|
||||
selector: "member-bulk-enable-sm-dialog",
|
||||
standalone: false,
|
||||
})
|
||||
export class BulkEnableSecretsManagerDialogComponent implements OnInit {
|
||||
|
||||
@@ -23,6 +23,7 @@ type BulkRemoveDialogParams = {
|
||||
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
|
||||
@Component({
|
||||
templateUrl: "bulk-remove-dialog.component.html",
|
||||
selector: "member-bulk-remove-dialog",
|
||||
standalone: false,
|
||||
})
|
||||
export class BulkRemoveDialogComponent extends BaseBulkRemoveComponent {
|
||||
|
||||
@@ -18,7 +18,7 @@ type BulkRestoreDialogParams = {
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
|
||||
@Component({
|
||||
selector: "app-bulk-restore-revoke",
|
||||
selector: "member-bulk-restore-revoke",
|
||||
templateUrl: "bulk-restore-revoke.component.html",
|
||||
standalone: false,
|
||||
})
|
||||
|
||||
@@ -41,7 +41,7 @@ type BulkStatusDialogData = {
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
|
||||
@Component({
|
||||
selector: "app-bulk-status",
|
||||
selector: "member-bulk-status",
|
||||
templateUrl: "bulk-status.component.html",
|
||||
standalone: false,
|
||||
})
|
||||
|
||||
@@ -15,11 +15,8 @@ import {
|
||||
} from "rxjs";
|
||||
|
||||
import {
|
||||
CollectionAccessSelectionView,
|
||||
CollectionAdminService,
|
||||
CollectionAdminView,
|
||||
OrganizationUserApiService,
|
||||
CollectionView,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import {
|
||||
getOrganizationById,
|
||||
@@ -30,6 +27,11 @@ import {
|
||||
OrganizationUserType,
|
||||
} from "@bitwarden/common/admin-console/enums";
|
||||
import { PermissionsApi } from "@bitwarden/common/admin-console/models/api/permissions.api";
|
||||
import {
|
||||
CollectionAccessSelectionView,
|
||||
CollectionAdminView,
|
||||
CollectionView,
|
||||
} from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
|
||||
@@ -0,0 +1,495 @@
|
||||
@let organization = this.organization();
|
||||
@if (organization) {
|
||||
<app-organization-free-trial-warning
|
||||
[organization]="organization"
|
||||
(clicked)="billingConstraint.navigateToPaymentMethod(organization)"
|
||||
>
|
||||
</app-organization-free-trial-warning>
|
||||
<app-header>
|
||||
<bit-search
|
||||
class="tw-grow"
|
||||
[formControl]="searchControl"
|
||||
[placeholder]="'searchMembers' | i18n"
|
||||
></bit-search>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
bitButton
|
||||
buttonType="primary"
|
||||
(click)="invite(organization)"
|
||||
[disabled]="!firstLoaded"
|
||||
*ngIf="showUserManagementControls()"
|
||||
>
|
||||
<i class="bwi bwi-plus bwi-fw" aria-hidden="true"></i>
|
||||
{{ "inviteMember" | i18n }}
|
||||
</button>
|
||||
</app-header>
|
||||
|
||||
<div class="tw-mb-4 tw-flex tw-flex-col tw-space-y-4">
|
||||
<bit-toggle-group
|
||||
[selected]="status"
|
||||
(selectedChange)="statusToggle.next($event)"
|
||||
[attr.aria-label]="'memberStatusFilter' | i18n"
|
||||
*ngIf="showUserManagementControls()"
|
||||
>
|
||||
<bit-toggle [value]="null">
|
||||
{{ "all" | i18n }}
|
||||
<span bitBadge variant="info" *ngIf="dataSource.activeUserCount as allCount">{{
|
||||
allCount
|
||||
}}</span>
|
||||
</bit-toggle>
|
||||
|
||||
<bit-toggle [value]="userStatusType.Invited">
|
||||
{{ "invited" | i18n }}
|
||||
<span bitBadge variant="info" *ngIf="dataSource.invitedUserCount as invitedCount">{{
|
||||
invitedCount
|
||||
}}</span>
|
||||
</bit-toggle>
|
||||
|
||||
<bit-toggle [value]="userStatusType.Accepted">
|
||||
{{ "needsConfirmation" | i18n }}
|
||||
<span bitBadge variant="info" *ngIf="dataSource.acceptedUserCount as acceptedUserCount">{{
|
||||
acceptedUserCount
|
||||
}}</span>
|
||||
</bit-toggle>
|
||||
|
||||
<bit-toggle [value]="userStatusType.Revoked">
|
||||
{{ "revoked" | i18n }}
|
||||
<span bitBadge variant="info" *ngIf="dataSource.revokedUserCount as revokedCount">{{
|
||||
revokedCount
|
||||
}}</span>
|
||||
</bit-toggle>
|
||||
</bit-toggle-group>
|
||||
</div>
|
||||
<ng-container *ngIf="!firstLoaded">
|
||||
<i
|
||||
class="bwi bwi-spinner bwi-spin tw-text-muted"
|
||||
title="{{ 'loading' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "loading" | i18n }}</span>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="firstLoaded">
|
||||
<p *ngIf="!dataSource.filteredData.length">{{ "noMembersInList" | i18n }}</p>
|
||||
<ng-container *ngIf="dataSource.filteredData.length">
|
||||
<bit-callout
|
||||
type="info"
|
||||
title="{{ 'confirmUsers' | i18n }}"
|
||||
icon="bwi-check-circle"
|
||||
*ngIf="showConfirmUsers"
|
||||
>
|
||||
{{ "usersNeedConfirmed" | i18n }}
|
||||
</bit-callout>
|
||||
<!-- The padding on the bottom of the cdk-virtual-scroll-viewport element is required to prevent table row content
|
||||
from overflowing the <main> element. -->
|
||||
<cdk-virtual-scroll-viewport bitScrollLayout [itemSize]="rowHeight" class="tw-pb-8">
|
||||
<bit-table [dataSource]="dataSource">
|
||||
<ng-container header>
|
||||
<tr>
|
||||
<th bitCell class="tw-w-20" *ngIf="showUserManagementControls()">
|
||||
<input
|
||||
type="checkbox"
|
||||
bitCheckbox
|
||||
class="tw-mr-1"
|
||||
(change)="dataSource.checkAllFilteredUsers($any($event.target).checked)"
|
||||
id="selectAll"
|
||||
/>
|
||||
<label class="tw-mb-0 !tw-font-medium !tw-text-muted" for="selectAll">{{
|
||||
"all" | i18n
|
||||
}}</label>
|
||||
</th>
|
||||
<th bitCell bitSortable="email" default>{{ "name" | i18n }}</th>
|
||||
<th bitCell>{{ (organization.useGroups ? "groups" : "collections") | i18n }}</th>
|
||||
<th bitCell bitSortable="type">{{ "role" | i18n }}</th>
|
||||
<th bitCell>{{ "policies" | i18n }}</th>
|
||||
<th bitCell>
|
||||
<div class="tw-flex tw-flex-row tw-items-center tw-justify-end tw-gap-2">
|
||||
<button
|
||||
type="button"
|
||||
bitIconButton="bwi-download"
|
||||
size="small"
|
||||
[bitAction]="exportMembers"
|
||||
[disabled]="!firstLoaded"
|
||||
label="{{ 'export' | i18n }}"
|
||||
></button>
|
||||
<button
|
||||
[bitMenuTriggerFor]="headerMenu"
|
||||
type="button"
|
||||
bitIconButton="bwi-ellipsis-v"
|
||||
size="small"
|
||||
label="{{ 'options' | i18n }}"
|
||||
*ngIf="showUserManagementControls()"
|
||||
></button>
|
||||
</div>
|
||||
|
||||
<bit-menu #headerMenu>
|
||||
<ng-container *ngIf="canUseSecretsManager()">
|
||||
<button type="button" bitMenuItem (click)="bulkEnableSM(organization)">
|
||||
{{ "activateSecretsManager" | i18n }}
|
||||
</button>
|
||||
<bit-menu-divider></bit-menu-divider>
|
||||
</ng-container>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkReinvite(organization)"
|
||||
*ngIf="showBulkReinviteUsers"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-envelope" aria-hidden="true"></i>
|
||||
{{ "reinviteSelected" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkConfirm(organization)"
|
||||
*ngIf="showBulkConfirmUsers"
|
||||
>
|
||||
<span class="tw-text-success">
|
||||
<i class="bwi bwi-fw bwi-check" aria-hidden="true"></i>
|
||||
{{ "confirmSelected" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkRestore(organization)"
|
||||
*ngIf="showBulkRestoreUsers"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-plus-circle" aria-hidden="true"></i>
|
||||
{{ "restoreAccess" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkRevoke(organization)"
|
||||
*ngIf="showBulkRevokeUsers"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-minus-circle" aria-hidden="true"></i>
|
||||
{{ "revokeAccess" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkRemove(organization)"
|
||||
*ngIf="showBulkRemoveUsers"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i aria-hidden="true" class="bwi bwi-fw bwi-close"></i>
|
||||
{{ "remove" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkDelete(organization)"
|
||||
*ngIf="showBulkDeleteUsers"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i aria-hidden="true" class="bwi bwi-fw bwi-trash"></i>
|
||||
{{ "delete" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
</bit-menu>
|
||||
</th>
|
||||
</tr>
|
||||
</ng-container>
|
||||
<ng-template body let-rows$>
|
||||
<tr
|
||||
bitRow
|
||||
*cdkVirtualFor="let u of rows$"
|
||||
alignContent="middle"
|
||||
[ngClass]="rowHeightClass"
|
||||
>
|
||||
<td bitCell (click)="dataSource.checkUser(u)" *ngIf="showUserManagementControls()">
|
||||
<input type="checkbox" bitCheckbox [(ngModel)]="$any(u).checked" />
|
||||
</td>
|
||||
<ng-container *ngIf="showUserManagementControls(); else readOnlyUserInfo">
|
||||
<td bitCell (click)="edit(u, organization)" class="tw-cursor-pointer">
|
||||
<div class="tw-flex tw-items-center">
|
||||
<bit-avatar
|
||||
size="small"
|
||||
[text]="u | userName"
|
||||
[id]="u.userId"
|
||||
[color]="u.avatarColor"
|
||||
class="tw-mr-3"
|
||||
></bit-avatar>
|
||||
<div class="tw-flex tw-flex-col">
|
||||
<div class="tw-flex tw-flex-row tw-gap-2">
|
||||
<button type="button" bitLink>
|
||||
{{ u.name ?? u.email }}
|
||||
</button>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="secondary"
|
||||
*ngIf="u.status === userStatusType.Invited"
|
||||
>
|
||||
{{ "invited" | i18n }}
|
||||
</span>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="warning"
|
||||
*ngIf="u.status === userStatusType.Accepted"
|
||||
>
|
||||
{{ "needsConfirmation" | i18n }}
|
||||
</span>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="secondary"
|
||||
*ngIf="u.status === userStatusType.Revoked"
|
||||
>
|
||||
{{ "revoked" | i18n }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="tw-text-sm tw-text-muted" *ngIf="u.name">
|
||||
{{ u.email }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</ng-container>
|
||||
<ng-template #readOnlyUserInfo>
|
||||
<td bitCell>
|
||||
<div class="tw-flex tw-items-center">
|
||||
<bit-avatar
|
||||
size="small"
|
||||
[text]="u | userName"
|
||||
[id]="u.userId"
|
||||
[color]="u.avatarColor"
|
||||
class="tw-mr-3"
|
||||
></bit-avatar>
|
||||
<div class="tw-flex tw-flex-col">
|
||||
<div class="tw-flex tw-flex-row tw-gap-2">
|
||||
<span>{{ u.name ?? u.email }}</span>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="secondary"
|
||||
*ngIf="u.status === userStatusType.Invited"
|
||||
>
|
||||
{{ "invited" | i18n }}
|
||||
</span>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="warning"
|
||||
*ngIf="u.status === userStatusType.Accepted"
|
||||
>
|
||||
{{ "needsConfirmation" | i18n }}
|
||||
</span>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="secondary"
|
||||
*ngIf="u.status === userStatusType.Revoked"
|
||||
>
|
||||
{{ "revoked" | i18n }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="tw-text-sm tw-text-muted" *ngIf="u.name">
|
||||
{{ u.email }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</ng-template>
|
||||
|
||||
<ng-container *ngIf="showUserManagementControls(); else readOnlyGroupsCell">
|
||||
<td
|
||||
bitCell
|
||||
(click)="
|
||||
edit(
|
||||
u,
|
||||
organization,
|
||||
organization.useGroups ? memberTab.Groups : memberTab.Collections
|
||||
)
|
||||
"
|
||||
class="tw-cursor-pointer"
|
||||
>
|
||||
<bit-badge-list
|
||||
[items]="organization.useGroups ? u.groupNames : u.collectionNames"
|
||||
[maxItems]="3"
|
||||
variant="secondary"
|
||||
></bit-badge-list>
|
||||
</td>
|
||||
</ng-container>
|
||||
<ng-template #readOnlyGroupsCell>
|
||||
<td bitCell>
|
||||
<bit-badge-list
|
||||
[items]="organization.useGroups ? u.groupNames : u.collectionNames"
|
||||
[maxItems]="3"
|
||||
variant="secondary"
|
||||
></bit-badge-list>
|
||||
</td>
|
||||
</ng-template>
|
||||
|
||||
<ng-container *ngIf="showUserManagementControls(); else readOnlyRoleCell">
|
||||
<td
|
||||
bitCell
|
||||
(click)="edit(u, organization, memberTab.Role)"
|
||||
class="tw-cursor-pointer tw-text-sm tw-text-muted"
|
||||
>
|
||||
{{ u.type | userType }}
|
||||
</td>
|
||||
</ng-container>
|
||||
<ng-template #readOnlyRoleCell>
|
||||
<td bitCell class="tw-text-sm tw-text-muted">
|
||||
{{ u.type | userType }}
|
||||
</td>
|
||||
</ng-template>
|
||||
|
||||
<td bitCell class="tw-text-muted">
|
||||
<ng-container *ngIf="u.twoFactorEnabled">
|
||||
<i
|
||||
class="bwi bwi-lock"
|
||||
title="{{ 'userUsingTwoStep' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "userUsingTwoStep" | i18n }}</span>
|
||||
</ng-container>
|
||||
@let resetPasswordPolicyEnabled = resetPasswordPolicyEnabled$ | async;
|
||||
<ng-container
|
||||
*ngIf="showEnrolledStatus($any(u), organization, resetPasswordPolicyEnabled)"
|
||||
>
|
||||
<i
|
||||
class="bwi bwi-key"
|
||||
title="{{ 'enrolledAccountRecovery' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "enrolledAccountRecovery" | i18n }}</span>
|
||||
</ng-container>
|
||||
</td>
|
||||
<td bitCell>
|
||||
<div class="tw-flex tw-flex-row tw-items-center tw-justify-end tw-gap-2">
|
||||
<div class="tw-w-[32px]"></div>
|
||||
<button
|
||||
[bitMenuTriggerFor]="rowMenu"
|
||||
type="button"
|
||||
bitIconButton="bwi-ellipsis-v"
|
||||
size="small"
|
||||
label="{{ 'options' | i18n }}"
|
||||
></button>
|
||||
</div>
|
||||
|
||||
<bit-menu #rowMenu>
|
||||
<ng-container *ngIf="showUserManagementControls()">
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="reinvite(u, organization)"
|
||||
*ngIf="u.status === userStatusType.Invited"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-envelope"></i>
|
||||
{{ "resendInvitation" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="confirm(u, organization)"
|
||||
*ngIf="u.status === userStatusType.Accepted"
|
||||
>
|
||||
<span class="tw-text-success">
|
||||
<i aria-hidden="true" class="bwi bwi-check"></i> {{ "confirm" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
<bit-menu-divider
|
||||
*ngIf="
|
||||
u.status === userStatusType.Accepted || u.status === userStatusType.Invited
|
||||
"
|
||||
></bit-menu-divider>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="edit(u, organization, memberTab.Role)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-user"></i> {{ "memberRole" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="edit(u, organization, memberTab.Groups)"
|
||||
*ngIf="organization.useGroups"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-users"></i> {{ "groups" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="edit(u, organization, memberTab.Collections)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-collection-shared"></i>
|
||||
{{ "collections" | i18n }}
|
||||
</button>
|
||||
<bit-menu-divider></bit-menu-divider>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="openEventsDialog(u, organization)"
|
||||
*ngIf="organization.useEvents && u.status === userStatusType.Confirmed"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-file-text"></i> {{ "eventLogs" | i18n }}
|
||||
</button>
|
||||
</ng-container>
|
||||
|
||||
<!-- Account recovery is available to all users with appropriate permissions -->
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="resetPassword(u, organization)"
|
||||
*ngIf="allowResetPassword(u, organization, resetPasswordPolicyEnabled)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-key"></i> {{ "recoverAccount" | i18n }}
|
||||
</button>
|
||||
|
||||
<ng-container *ngIf="showUserManagementControls()">
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="restore(u, organization)"
|
||||
*ngIf="u.status === userStatusType.Revoked"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-plus-circle"></i>
|
||||
{{ "restoreAccess" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="revoke(u, organization)"
|
||||
*ngIf="u.status !== userStatusType.Revoked"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-minus-circle"></i>
|
||||
{{ "revokeAccess" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
*ngIf="!u.managedByOrganization"
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="remove(u, organization)"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i aria-hidden="true" class="bwi bwi-close"></i> {{ "remove" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
*ngIf="u.managedByOrganization"
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="deleteUser(u, organization)"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i class="bwi bwi-trash" aria-hidden="true"></i>
|
||||
{{ "delete" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
</ng-container>
|
||||
</bit-menu>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</bit-table>
|
||||
</cdk-virtual-scroll-viewport>
|
||||
</ng-container>
|
||||
</ng-container>
|
||||
}
|
||||
@@ -0,0 +1,616 @@
|
||||
import { Component, computed, Signal } from "@angular/core";
|
||||
import { takeUntilDestroyed, toSignal } from "@angular/core/rxjs-interop";
|
||||
import { ActivatedRoute } from "@angular/router";
|
||||
import {
|
||||
combineLatest,
|
||||
concatMap,
|
||||
filter,
|
||||
firstValueFrom,
|
||||
from,
|
||||
map,
|
||||
merge,
|
||||
Observable,
|
||||
shareReplay,
|
||||
switchMap,
|
||||
take,
|
||||
} from "rxjs";
|
||||
|
||||
import { OrganizationUserUserDetailsResponse } from "@bitwarden/admin-console/common";
|
||||
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 { OrganizationManagementPreferencesService } from "@bitwarden/common/admin-console/abstractions/organization-management-preferences/organization-management-preferences.service";
|
||||
import { PolicyApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy-api.service.abstraction";
|
||||
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
|
||||
import {
|
||||
OrganizationUserStatusType,
|
||||
OrganizationUserType,
|
||||
PolicyType,
|
||||
} from "@bitwarden/common/admin-console/enums";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { Policy } from "@bitwarden/common/admin-console/models/domain/policy";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { OrganizationMetadataServiceAbstraction } from "@bitwarden/common/billing/abstractions/organization-metadata.service.abstraction";
|
||||
import { OrganizationBillingMetadataResponse } from "@bitwarden/common/billing/models/response/organization-billing-metadata.response";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service";
|
||||
import { getById } from "@bitwarden/common/platform/misc";
|
||||
import { DialogService, ToastService } from "@bitwarden/components";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
import { UserId } from "@bitwarden/user-core";
|
||||
import { BillingConstraintService } from "@bitwarden/web-vault/app/billing/members/billing-constraint/billing-constraint.service";
|
||||
import { OrganizationWarningsService } from "@bitwarden/web-vault/app/billing/organizations/warnings/services";
|
||||
|
||||
import { BaseMembersComponent } from "../../common/base-members.component";
|
||||
import {
|
||||
CloudBulkReinviteLimit,
|
||||
MaxCheckedCount,
|
||||
PeopleTableDataSource,
|
||||
} from "../../common/people-table-data-source";
|
||||
import { OrganizationUserView } from "../core/views/organization-user.view";
|
||||
|
||||
import { AccountRecoveryDialogResultType } from "./components/account-recovery/account-recovery-dialog.component";
|
||||
import { MemberDialogResult, MemberDialogTab } from "./components/member-dialog";
|
||||
import {
|
||||
MemberDialogManagerService,
|
||||
MemberExportService,
|
||||
OrganizationMembersService,
|
||||
} from "./services";
|
||||
import { DeleteManagedMemberWarningService } from "./services/delete-managed-member/delete-managed-member-warning.service";
|
||||
import {
|
||||
MemberActionsService,
|
||||
MemberActionResult,
|
||||
} from "./services/member-actions/member-actions.service";
|
||||
|
||||
class MembersTableDataSource extends PeopleTableDataSource<OrganizationUserView> {
|
||||
protected statusType = OrganizationUserStatusType;
|
||||
}
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
|
||||
@Component({
|
||||
templateUrl: "deprecated_members.component.html",
|
||||
standalone: false,
|
||||
})
|
||||
export class MembersComponent extends BaseMembersComponent<OrganizationUserView> {
|
||||
userType = OrganizationUserType;
|
||||
userStatusType = OrganizationUserStatusType;
|
||||
memberTab = MemberDialogTab;
|
||||
protected dataSource: MembersTableDataSource;
|
||||
|
||||
readonly organization: Signal<Organization | undefined>;
|
||||
status: OrganizationUserStatusType | undefined;
|
||||
|
||||
private userId$: Observable<UserId> = this.accountService.activeAccount$.pipe(getUserId);
|
||||
|
||||
resetPasswordPolicyEnabled$: Observable<boolean>;
|
||||
|
||||
protected readonly canUseSecretsManager: Signal<boolean> = computed(
|
||||
() => this.organization()?.useSecretsManager ?? false,
|
||||
);
|
||||
protected readonly showUserManagementControls: Signal<boolean> = computed(
|
||||
() => this.organization()?.canManageUsers ?? false,
|
||||
);
|
||||
protected billingMetadata$: Observable<OrganizationBillingMetadataResponse>;
|
||||
|
||||
// Fixed sizes used for cdkVirtualScroll
|
||||
protected rowHeight = 66;
|
||||
protected rowHeightClass = `tw-h-[66px]`;
|
||||
|
||||
constructor(
|
||||
apiService: ApiService,
|
||||
i18nService: I18nService,
|
||||
organizationManagementPreferencesService: OrganizationManagementPreferencesService,
|
||||
keyService: KeyService,
|
||||
validationService: ValidationService,
|
||||
logService: LogService,
|
||||
userNamePipe: UserNamePipe,
|
||||
dialogService: DialogService,
|
||||
toastService: ToastService,
|
||||
private route: ActivatedRoute,
|
||||
protected deleteManagedMemberWarningService: DeleteManagedMemberWarningService,
|
||||
private organizationWarningsService: OrganizationWarningsService,
|
||||
private memberActionsService: MemberActionsService,
|
||||
private memberDialogManager: MemberDialogManagerService,
|
||||
protected billingConstraint: BillingConstraintService,
|
||||
protected memberService: OrganizationMembersService,
|
||||
private organizationService: OrganizationService,
|
||||
private accountService: AccountService,
|
||||
private policyService: PolicyService,
|
||||
private policyApiService: PolicyApiServiceAbstraction,
|
||||
private organizationMetadataService: OrganizationMetadataServiceAbstraction,
|
||||
private memberExportService: MemberExportService,
|
||||
private configService: ConfigService,
|
||||
private environmentService: EnvironmentService,
|
||||
) {
|
||||
super(
|
||||
apiService,
|
||||
i18nService,
|
||||
keyService,
|
||||
validationService,
|
||||
logService,
|
||||
userNamePipe,
|
||||
dialogService,
|
||||
organizationManagementPreferencesService,
|
||||
toastService,
|
||||
);
|
||||
|
||||
this.dataSource = new MembersTableDataSource(this.configService, this.environmentService);
|
||||
|
||||
const organization$ = this.route.params.pipe(
|
||||
concatMap((params) =>
|
||||
this.userId$.pipe(
|
||||
switchMap((userId) =>
|
||||
this.organizationService.organizations$(userId).pipe(getById(params.organizationId)),
|
||||
),
|
||||
filter((organization): organization is Organization => organization != null),
|
||||
shareReplay({ refCount: true, bufferSize: 1 }),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
this.organization = toSignal(organization$);
|
||||
|
||||
const policies$ = combineLatest([this.userId$, organization$]).pipe(
|
||||
switchMap(([userId, organization]) =>
|
||||
organization.isProviderUser
|
||||
? from(this.policyApiService.getPolicies(organization.id)).pipe(
|
||||
map((response) => Policy.fromListResponse(response)),
|
||||
)
|
||||
: this.policyService.policies$(userId),
|
||||
),
|
||||
);
|
||||
|
||||
this.resetPasswordPolicyEnabled$ = combineLatest([organization$, policies$]).pipe(
|
||||
map(
|
||||
([organization, policies]) =>
|
||||
policies
|
||||
.filter((policy) => policy.type === PolicyType.ResetPassword)
|
||||
.find((p) => p.organizationId === organization.id)?.enabled ?? false,
|
||||
),
|
||||
);
|
||||
|
||||
combineLatest([this.route.queryParams, organization$])
|
||||
.pipe(
|
||||
concatMap(async ([qParams, organization]) => {
|
||||
await this.load(organization!);
|
||||
|
||||
this.searchControl.setValue(qParams.search);
|
||||
|
||||
if (qParams.viewEvents != null) {
|
||||
const user = this.dataSource.data.filter((u) => u.id === qParams.viewEvents);
|
||||
if (user.length > 0 && user[0].status === OrganizationUserStatusType.Confirmed) {
|
||||
this.openEventsDialog(user[0], organization!);
|
||||
}
|
||||
}
|
||||
}),
|
||||
takeUntilDestroyed(),
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
organization$
|
||||
.pipe(
|
||||
switchMap((organization) =>
|
||||
merge(
|
||||
this.organizationWarningsService.showInactiveSubscriptionDialog$(organization),
|
||||
this.organizationWarningsService.showSubscribeBeforeFreeTrialEndsDialog$(organization),
|
||||
),
|
||||
),
|
||||
takeUntilDestroyed(),
|
||||
)
|
||||
.subscribe();
|
||||
|
||||
this.billingMetadata$ = organization$.pipe(
|
||||
switchMap((organization) =>
|
||||
this.organizationMetadataService.getOrganizationMetadata$(organization.id),
|
||||
),
|
||||
shareReplay({ bufferSize: 1, refCount: false }),
|
||||
);
|
||||
|
||||
// Stripe is slow, so kick this off in the background but without blocking page load.
|
||||
// Anyone who needs it will still await the first emission.
|
||||
this.billingMetadata$.pipe(take(1), takeUntilDestroyed()).subscribe();
|
||||
}
|
||||
|
||||
override async load(organization: Organization) {
|
||||
await super.load(organization);
|
||||
}
|
||||
|
||||
async getUsers(organization: Organization): Promise<OrganizationUserView[]> {
|
||||
return await this.memberService.loadUsers(organization);
|
||||
}
|
||||
|
||||
async removeUser(id: string, organization: Organization): Promise<MemberActionResult> {
|
||||
return await this.memberActionsService.removeUser(organization, id);
|
||||
}
|
||||
|
||||
async revokeUser(id: string, organization: Organization): Promise<MemberActionResult> {
|
||||
return await this.memberActionsService.revokeUser(organization, id);
|
||||
}
|
||||
|
||||
async restoreUser(id: string, organization: Organization): Promise<MemberActionResult> {
|
||||
return await this.memberActionsService.restoreUser(organization, id);
|
||||
}
|
||||
|
||||
async reinviteUser(id: string, organization: Organization): Promise<MemberActionResult> {
|
||||
return await this.memberActionsService.reinviteUser(organization, id);
|
||||
}
|
||||
|
||||
async confirmUser(
|
||||
user: OrganizationUserView,
|
||||
publicKey: Uint8Array,
|
||||
organization: Organization,
|
||||
): Promise<MemberActionResult> {
|
||||
return await this.memberActionsService.confirmUser(user, publicKey, organization);
|
||||
}
|
||||
|
||||
async revoke(user: OrganizationUserView, organization: Organization) {
|
||||
const confirmed = await this.revokeUserConfirmationDialog(user);
|
||||
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.actionPromise = this.revokeUser(user.id, organization);
|
||||
try {
|
||||
const result = await this.actionPromise;
|
||||
if (result.success) {
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("revokedUserId", this.userNamePipe.transform(user)),
|
||||
});
|
||||
await this.load(organization);
|
||||
} else {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
} catch (e) {
|
||||
this.validationService.showError(e);
|
||||
}
|
||||
this.actionPromise = undefined;
|
||||
}
|
||||
|
||||
async restore(user: OrganizationUserView, organization: Organization) {
|
||||
this.actionPromise = this.restoreUser(user.id, organization);
|
||||
try {
|
||||
const result = await this.actionPromise;
|
||||
if (result.success) {
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("restoredUserId", this.userNamePipe.transform(user)),
|
||||
});
|
||||
await this.load(organization);
|
||||
} else {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
} catch (e) {
|
||||
this.validationService.showError(e);
|
||||
}
|
||||
this.actionPromise = undefined;
|
||||
}
|
||||
|
||||
allowResetPassword(
|
||||
orgUser: OrganizationUserView,
|
||||
organization: Organization,
|
||||
orgResetPasswordPolicyEnabled: boolean,
|
||||
): boolean {
|
||||
return this.memberActionsService.allowResetPassword(
|
||||
orgUser,
|
||||
organization,
|
||||
orgResetPasswordPolicyEnabled,
|
||||
);
|
||||
}
|
||||
|
||||
showEnrolledStatus(
|
||||
orgUser: OrganizationUserUserDetailsResponse,
|
||||
organization: Organization,
|
||||
orgResetPasswordPolicyEnabled: boolean,
|
||||
): boolean {
|
||||
return (
|
||||
organization.useResetPassword &&
|
||||
orgUser.resetPasswordEnrolled &&
|
||||
orgResetPasswordPolicyEnabled
|
||||
);
|
||||
}
|
||||
|
||||
private async handleInviteDialog(organization: Organization) {
|
||||
const billingMetadata = await firstValueFrom(this.billingMetadata$);
|
||||
const allUserEmails = this.dataSource.data?.map((user) => user.email) ?? [];
|
||||
|
||||
const result = await this.memberDialogManager.openInviteDialog(
|
||||
organization,
|
||||
billingMetadata,
|
||||
allUserEmails,
|
||||
);
|
||||
|
||||
if (result === MemberDialogResult.Saved) {
|
||||
await this.load(organization);
|
||||
}
|
||||
}
|
||||
|
||||
async invite(organization: Organization) {
|
||||
const billingMetadata = await firstValueFrom(this.billingMetadata$);
|
||||
const seatLimitResult = this.billingConstraint.checkSeatLimit(organization, billingMetadata);
|
||||
if (!(await this.billingConstraint.seatLimitReached(seatLimitResult, organization))) {
|
||||
await this.handleInviteDialog(organization);
|
||||
this.organizationMetadataService.refreshMetadataCache();
|
||||
}
|
||||
}
|
||||
|
||||
async edit(
|
||||
user: OrganizationUserView,
|
||||
organization: Organization,
|
||||
initialTab: MemberDialogTab = MemberDialogTab.Role,
|
||||
) {
|
||||
const billingMetadata = await firstValueFrom(this.billingMetadata$);
|
||||
|
||||
const result = await this.memberDialogManager.openEditDialog(
|
||||
user,
|
||||
organization,
|
||||
billingMetadata,
|
||||
initialTab,
|
||||
);
|
||||
|
||||
switch (result) {
|
||||
case MemberDialogResult.Deleted:
|
||||
this.dataSource.removeUser(user);
|
||||
break;
|
||||
case MemberDialogResult.Saved:
|
||||
case MemberDialogResult.Revoked:
|
||||
case MemberDialogResult.Restored:
|
||||
await this.load(organization);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
async bulkRemove(organization: Organization) {
|
||||
if (this.actionPromise != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const users = this.dataSource.getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
|
||||
await this.memberDialogManager.openBulkRemoveDialog(organization, users);
|
||||
this.organizationMetadataService.refreshMetadataCache();
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
async bulkDelete(organization: Organization) {
|
||||
if (this.actionPromise != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const users = this.dataSource.getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
|
||||
await this.memberDialogManager.openBulkDeleteDialog(organization, users);
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
async bulkRevoke(organization: Organization) {
|
||||
await this.bulkRevokeOrRestore(true, organization);
|
||||
}
|
||||
|
||||
async bulkRestore(organization: Organization) {
|
||||
await this.bulkRevokeOrRestore(false, organization);
|
||||
}
|
||||
|
||||
async bulkRevokeOrRestore(isRevoking: boolean, organization: Organization) {
|
||||
if (this.actionPromise != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const users = this.dataSource.getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
|
||||
await this.memberDialogManager.openBulkRestoreRevokeDialog(organization, users, isRevoking);
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
async bulkReinvite(organization: Organization) {
|
||||
if (this.actionPromise != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
let users: OrganizationUserView[];
|
||||
if (this.dataSource.isIncreasedBulkLimitEnabled()) {
|
||||
users = this.dataSource.getCheckedUsersInVisibleOrder();
|
||||
} else {
|
||||
users = this.dataSource.getCheckedUsers();
|
||||
}
|
||||
|
||||
const allInvitedUsers = users.filter((u) => u.status === OrganizationUserStatusType.Invited);
|
||||
|
||||
// Capture the original count BEFORE enforcing the limit
|
||||
const originalInvitedCount = allInvitedUsers.length;
|
||||
|
||||
// When feature flag is enabled, limit invited users and uncheck the excess
|
||||
let filteredUsers: OrganizationUserView[];
|
||||
if (this.dataSource.isIncreasedBulkLimitEnabled()) {
|
||||
filteredUsers = this.dataSource.limitAndUncheckExcess(
|
||||
allInvitedUsers,
|
||||
CloudBulkReinviteLimit,
|
||||
);
|
||||
} else {
|
||||
filteredUsers = allInvitedUsers;
|
||||
}
|
||||
|
||||
if (filteredUsers.length <= 0) {
|
||||
this.toastService.showToast({
|
||||
variant: "error",
|
||||
title: this.i18nService.t("errorOccurred"),
|
||||
message: this.i18nService.t("noSelectedUsersApplicable"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.memberActionsService.bulkReinvite(
|
||||
organization,
|
||||
filteredUsers.map((user) => user.id as UserId),
|
||||
);
|
||||
|
||||
if (!result.successful) {
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
// When feature flag is enabled, show toast instead of dialog
|
||||
if (this.dataSource.isIncreasedBulkLimitEnabled()) {
|
||||
const selectedCount = originalInvitedCount;
|
||||
const invitedCount = filteredUsers.length;
|
||||
|
||||
if (selectedCount > CloudBulkReinviteLimit) {
|
||||
const excludedCount = selectedCount - CloudBulkReinviteLimit;
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t(
|
||||
"bulkReinviteLimitedSuccessToast",
|
||||
CloudBulkReinviteLimit.toLocaleString(),
|
||||
selectedCount.toLocaleString(),
|
||||
excludedCount.toLocaleString(),
|
||||
),
|
||||
});
|
||||
} else {
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("bulkReinviteSuccessToast", invitedCount.toString()),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Feature flag disabled - show legacy dialog
|
||||
await this.memberDialogManager.openBulkStatusDialog(
|
||||
users,
|
||||
filteredUsers,
|
||||
Promise.resolve(result.successful),
|
||||
this.i18nService.t("bulkReinviteMessage"),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
this.validationService.showError(e);
|
||||
}
|
||||
this.actionPromise = undefined;
|
||||
}
|
||||
|
||||
async bulkConfirm(organization: Organization) {
|
||||
if (this.actionPromise != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const users = this.dataSource.getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
|
||||
await this.memberDialogManager.openBulkConfirmDialog(organization, users);
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
async bulkEnableSM(organization: Organization) {
|
||||
const users = this.dataSource.getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
|
||||
await this.memberDialogManager.openBulkEnableSecretsManagerDialog(organization, users);
|
||||
|
||||
this.dataSource.uncheckAllUsers();
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
openEventsDialog(user: OrganizationUserView, organization: Organization) {
|
||||
this.memberDialogManager.openEventsDialog(user, organization);
|
||||
}
|
||||
|
||||
async resetPassword(user: OrganizationUserView, organization: Organization) {
|
||||
if (!user || !user.email || !user.id) {
|
||||
this.toastService.showToast({
|
||||
variant: "error",
|
||||
title: this.i18nService.t("errorOccurred"),
|
||||
message: this.i18nService.t("orgUserDetailsNotFound"),
|
||||
});
|
||||
this.logService.error("Org user details not found when attempting account recovery");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await this.memberDialogManager.openAccountRecoveryDialog(user, organization);
|
||||
if (result === AccountRecoveryDialogResultType.Ok) {
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
protected async removeUserConfirmationDialog(user: OrganizationUserView) {
|
||||
return await this.memberDialogManager.openRemoveUserConfirmationDialog(user);
|
||||
}
|
||||
|
||||
protected async revokeUserConfirmationDialog(user: OrganizationUserView) {
|
||||
return await this.memberDialogManager.openRevokeUserConfirmationDialog(user);
|
||||
}
|
||||
|
||||
async deleteUser(user: OrganizationUserView, organization: Organization) {
|
||||
const confirmed = await this.memberDialogManager.openDeleteUserConfirmationDialog(
|
||||
user,
|
||||
organization,
|
||||
);
|
||||
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.actionPromise = this.memberActionsService.deleteUser(organization, user.id);
|
||||
try {
|
||||
const result = await this.actionPromise;
|
||||
if (!result.success) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("organizationUserDeleted", this.userNamePipe.transform(user)),
|
||||
});
|
||||
this.dataSource.removeUser(user);
|
||||
} catch (e) {
|
||||
this.validationService.showError(e);
|
||||
}
|
||||
this.actionPromise = undefined;
|
||||
}
|
||||
|
||||
get showBulkRestoreUsers(): boolean {
|
||||
return this.dataSource
|
||||
.getCheckedUsers()
|
||||
.every((member) => member.status == this.userStatusType.Revoked);
|
||||
}
|
||||
|
||||
get showBulkRevokeUsers(): boolean {
|
||||
return this.dataSource
|
||||
.getCheckedUsers()
|
||||
.every((member) => member.status != this.userStatusType.Revoked);
|
||||
}
|
||||
|
||||
get showBulkRemoveUsers(): boolean {
|
||||
return this.dataSource.getCheckedUsers().every((member) => !member.managedByOrganization);
|
||||
}
|
||||
|
||||
get showBulkDeleteUsers(): boolean {
|
||||
const validStatuses = [
|
||||
this.userStatusType.Accepted,
|
||||
this.userStatusType.Confirmed,
|
||||
this.userStatusType.Revoked,
|
||||
];
|
||||
|
||||
return this.dataSource
|
||||
.getCheckedUsers()
|
||||
.every((member) => member.managedByOrganization && validStatuses.includes(member.status));
|
||||
}
|
||||
|
||||
exportMembers = () => {
|
||||
const result = this.memberExportService.getMemberExport(this.dataSource.data);
|
||||
if (result.success) {
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
title: undefined,
|
||||
message: this.i18nService.t("dataExportSuccess"),
|
||||
});
|
||||
}
|
||||
|
||||
if (result.error != null) {
|
||||
this.validationService.showError(result.error.message);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,23 +1,30 @@
|
||||
import { NgModule } from "@angular/core";
|
||||
import { RouterModule, Routes } from "@angular/router";
|
||||
|
||||
import { featureFlaggedRoute } from "@bitwarden/angular/platform/utils/feature-flagged-route";
|
||||
import { canAccessMembersTab } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
|
||||
import { FreeBitwardenFamiliesComponent } from "../../../billing/members/free-bitwarden-families.component";
|
||||
import { organizationPermissionsGuard } from "../guards/org-permissions.guard";
|
||||
|
||||
import { canAccessSponsoredFamilies } from "./../../../billing/guards/can-access-sponsored-families.guard";
|
||||
import { MembersComponent } from "./members.component";
|
||||
import { MembersComponent } from "./deprecated_members.component";
|
||||
import { vNextMembersComponent } from "./members.component";
|
||||
|
||||
const routes: Routes = [
|
||||
{
|
||||
path: "",
|
||||
component: MembersComponent,
|
||||
canActivate: [organizationPermissionsGuard(canAccessMembersTab)],
|
||||
data: {
|
||||
titleId: "members",
|
||||
...featureFlaggedRoute({
|
||||
defaultComponent: MembersComponent,
|
||||
flaggedComponent: vNextMembersComponent,
|
||||
featureFlag: FeatureFlag.MembersComponentRefactor,
|
||||
routeOptions: {
|
||||
path: "",
|
||||
canActivate: [organizationPermissionsGuard(canAccessMembersTab)],
|
||||
data: {
|
||||
titleId: "members",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
{
|
||||
path: "sponsored-families",
|
||||
component: FreeBitwardenFamiliesComponent,
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
@let organization = this.organization();
|
||||
@if (organization) {
|
||||
@let dataSource = this.dataSource();
|
||||
@let bulkActions = bulkMenuOptions$ | async;
|
||||
@let showConfirmBanner = showConfirmBanner$ | async;
|
||||
@let isProcessing = this.isProcessing();
|
||||
|
||||
@if (organization && dataSource) {
|
||||
<app-organization-free-trial-warning
|
||||
[organization]="organization"
|
||||
(clicked)="billingConstraint.navigateToPaymentMethod(organization)"
|
||||
@@ -12,183 +17,199 @@
|
||||
[placeholder]="'searchMembers' | i18n"
|
||||
></bit-search>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
bitButton
|
||||
buttonType="primary"
|
||||
(click)="invite(organization)"
|
||||
[disabled]="!firstLoaded"
|
||||
*ngIf="showUserManagementControls()"
|
||||
>
|
||||
<i class="bwi bwi-plus bwi-fw" aria-hidden="true"></i>
|
||||
{{ "inviteMember" | i18n }}
|
||||
</button>
|
||||
@if (showUserManagementControls()) {
|
||||
<button
|
||||
type="button"
|
||||
bitButton
|
||||
buttonType="primary"
|
||||
(click)="invite(organization)"
|
||||
[disabled]="!firstLoaded()"
|
||||
>
|
||||
<i class="bwi bwi-plus bwi-fw" aria-hidden="true"></i>
|
||||
{{ "inviteMember" | i18n }}
|
||||
</button>
|
||||
}
|
||||
</app-header>
|
||||
|
||||
<div class="tw-mb-4 tw-flex tw-flex-col tw-space-y-4">
|
||||
<bit-toggle-group
|
||||
[selected]="status"
|
||||
(selectedChange)="statusToggle.next($event)"
|
||||
[attr.aria-label]="'memberStatusFilter' | i18n"
|
||||
*ngIf="showUserManagementControls()"
|
||||
>
|
||||
<bit-toggle [value]="null">
|
||||
{{ "all" | i18n }}
|
||||
<span bitBadge variant="info" *ngIf="dataSource.activeUserCount as allCount">{{
|
||||
allCount
|
||||
}}</span>
|
||||
</bit-toggle>
|
||||
@if (showUserManagementControls()) {
|
||||
<bit-toggle-group
|
||||
[selected]="statusToggle | async"
|
||||
(selectedChange)="statusToggle.next($event)"
|
||||
[attr.aria-label]="'memberStatusFilter' | i18n"
|
||||
>
|
||||
<bit-toggle [value]="undefined">
|
||||
{{ "all" | i18n }}
|
||||
@if (dataSource.activeUserCount; as allCount) {
|
||||
<span bitBadge variant="info">{{ allCount }}</span>
|
||||
}
|
||||
</bit-toggle>
|
||||
|
||||
<bit-toggle [value]="userStatusType.Invited">
|
||||
{{ "invited" | i18n }}
|
||||
<span bitBadge variant="info" *ngIf="dataSource.invitedUserCount as invitedCount">{{
|
||||
invitedCount
|
||||
}}</span>
|
||||
</bit-toggle>
|
||||
<bit-toggle [value]="userStatusType.Invited">
|
||||
{{ "invited" | i18n }}
|
||||
@if (dataSource.invitedUserCount; as invitedCount) {
|
||||
<span bitBadge variant="info">{{ invitedCount }}</span>
|
||||
}
|
||||
</bit-toggle>
|
||||
|
||||
<bit-toggle [value]="userStatusType.Accepted">
|
||||
{{ "needsConfirmation" | i18n }}
|
||||
<span bitBadge variant="info" *ngIf="dataSource.acceptedUserCount as acceptedUserCount">{{
|
||||
acceptedUserCount
|
||||
}}</span>
|
||||
</bit-toggle>
|
||||
<bit-toggle [value]="userStatusType.Accepted">
|
||||
{{ "needsConfirmation" | i18n }}
|
||||
@if (dataSource.acceptedUserCount; as acceptedUserCount) {
|
||||
<span bitBadge variant="info">{{ acceptedUserCount }}</span>
|
||||
}
|
||||
</bit-toggle>
|
||||
|
||||
<bit-toggle [value]="userStatusType.Revoked">
|
||||
{{ "revoked" | i18n }}
|
||||
<span bitBadge variant="info" *ngIf="dataSource.revokedUserCount as revokedCount">{{
|
||||
revokedCount
|
||||
}}</span>
|
||||
</bit-toggle>
|
||||
</bit-toggle-group>
|
||||
<bit-toggle [value]="userStatusType.Revoked">
|
||||
{{ "revoked" | i18n }}
|
||||
@if (dataSource.revokedUserCount; as revokedCount) {
|
||||
<span bitBadge variant="info">{{ revokedCount }}</span>
|
||||
}
|
||||
</bit-toggle>
|
||||
</bit-toggle-group>
|
||||
}
|
||||
</div>
|
||||
<ng-container *ngIf="!firstLoaded">
|
||||
@if (!firstLoaded() || !organization || !dataSource) {
|
||||
<i
|
||||
class="bwi bwi-spinner bwi-spin tw-text-muted"
|
||||
title="{{ 'loading' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "loading" | i18n }}</span>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="firstLoaded">
|
||||
<p *ngIf="!dataSource.filteredData.length">{{ "noMembersInList" | i18n }}</p>
|
||||
<ng-container *ngIf="dataSource.filteredData.length">
|
||||
<bit-callout
|
||||
type="info"
|
||||
title="{{ 'confirmUsers' | i18n }}"
|
||||
icon="bwi-check-circle"
|
||||
*ngIf="showConfirmUsers"
|
||||
>
|
||||
{{ "usersNeedConfirmed" | i18n }}
|
||||
</bit-callout>
|
||||
} @else {
|
||||
@if (!dataSource.filteredData?.length) {
|
||||
<p>{{ "noMembersInList" | i18n }}</p>
|
||||
}
|
||||
@if (dataSource.filteredData?.length) {
|
||||
@if (showConfirmBanner) {
|
||||
<bit-callout type="info" title="{{ 'confirmUsers' | i18n }}" icon="bwi-check-circle">
|
||||
{{ "usersNeedConfirmed" | i18n }}
|
||||
</bit-callout>
|
||||
}
|
||||
|
||||
<!-- The padding on the bottom of the cdk-virtual-scroll-viewport element is required to prevent table row content
|
||||
from overflowing the <main> element. -->
|
||||
<cdk-virtual-scroll-viewport bitScrollLayout [itemSize]="rowHeight" class="tw-pb-8">
|
||||
<bit-table [dataSource]="dataSource">
|
||||
<ng-container header>
|
||||
<tr>
|
||||
<th bitCell class="tw-w-20" *ngIf="showUserManagementControls()">
|
||||
<input
|
||||
type="checkbox"
|
||||
bitCheckbox
|
||||
class="tw-mr-1"
|
||||
(change)="dataSource.checkAllFilteredUsers($any($event.target).checked)"
|
||||
id="selectAll"
|
||||
/>
|
||||
<label class="tw-mb-0 !tw-font-medium !tw-text-muted" for="selectAll">{{
|
||||
"all" | i18n
|
||||
}}</label>
|
||||
</th>
|
||||
@if (showUserManagementControls()) {
|
||||
<th bitCell class="tw-w-20">
|
||||
<input
|
||||
type="checkbox"
|
||||
bitCheckbox
|
||||
class="tw-mr-1"
|
||||
(change)="dataSource.checkAllFilteredUsers($any($event.target).checked)"
|
||||
id="selectAll"
|
||||
/>
|
||||
<label class="tw-mb-0 !tw-font-medium !tw-text-muted" for="selectAll">{{
|
||||
"all" | i18n
|
||||
}}</label>
|
||||
</th>
|
||||
}
|
||||
<th bitCell bitSortable="email" default>{{ "name" | i18n }}</th>
|
||||
<th bitCell>{{ (organization.useGroups ? "groups" : "collections") | i18n }}</th>
|
||||
<th bitCell bitSortable="type">{{ "role" | i18n }}</th>
|
||||
<th bitCell>{{ "policies" | i18n }}</th>
|
||||
<th bitCell>
|
||||
<div class="tw-flex tw-flex-row tw-items-center tw-justify-end tw-gap-2">
|
||||
<button
|
||||
type="button"
|
||||
bitIconButton="bwi-download"
|
||||
size="small"
|
||||
[bitAction]="exportMembers"
|
||||
[disabled]="!firstLoaded"
|
||||
label="{{ 'export' | i18n }}"
|
||||
></button>
|
||||
<button
|
||||
[bitMenuTriggerFor]="headerMenu"
|
||||
type="button"
|
||||
bitIconButton="bwi-ellipsis-v"
|
||||
size="small"
|
||||
label="{{ 'options' | i18n }}"
|
||||
*ngIf="showUserManagementControls()"
|
||||
></button>
|
||||
</div>
|
||||
<th bitCell class="tw-w-10">
|
||||
@if (showUserManagementControls()) {
|
||||
<th bitCell>
|
||||
<div class="tw-flex tw-flex-row tw-items-center tw-justify-end tw-gap-2">
|
||||
<button
|
||||
type="button"
|
||||
bitIconButton="bwi-download"
|
||||
size="small"
|
||||
[bitAction]="exportMembers"
|
||||
[disabled]="!firstLoaded"
|
||||
label="{{ 'export' | i18n }}"
|
||||
></button>
|
||||
<button
|
||||
[bitMenuTriggerFor]="headerMenu"
|
||||
type="button"
|
||||
bitIconButton="bwi-ellipsis-v"
|
||||
size="small"
|
||||
label="{{ 'options' | i18n }}"
|
||||
></button>
|
||||
</div>
|
||||
</th>
|
||||
}
|
||||
|
||||
<bit-menu #headerMenu>
|
||||
<ng-container *ngIf="canUseSecretsManager()">
|
||||
<button type="button" bitMenuItem (click)="bulkEnableSM(organization)">
|
||||
@if (canUseSecretsManager()) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : bulkEnableSM(organization)"
|
||||
>
|
||||
{{ "activateSecretsManager" | i18n }}
|
||||
</button>
|
||||
<bit-menu-divider></bit-menu-divider>
|
||||
</ng-container>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkReinvite(organization)"
|
||||
*ngIf="showBulkReinviteUsers"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-envelope" aria-hidden="true"></i>
|
||||
{{ "reinviteSelected" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkConfirm(organization)"
|
||||
*ngIf="showBulkConfirmUsers"
|
||||
>
|
||||
<span class="tw-text-success">
|
||||
<i class="bwi bwi-fw bwi-check" aria-hidden="true"></i>
|
||||
{{ "confirmSelected" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkRestore(organization)"
|
||||
*ngIf="showBulkRestoreUsers"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-plus-circle" aria-hidden="true"></i>
|
||||
{{ "restoreAccess" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkRevoke(organization)"
|
||||
*ngIf="showBulkRevokeUsers"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-minus-circle" aria-hidden="true"></i>
|
||||
{{ "revokeAccess" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkRemove(organization)"
|
||||
*ngIf="showBulkRemoveUsers"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i aria-hidden="true" class="bwi bwi-fw bwi-close"></i>
|
||||
{{ "remove" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="bulkDelete(organization)"
|
||||
*ngIf="showBulkDeleteUsers"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i aria-hidden="true" class="bwi bwi-fw bwi-trash"></i>
|
||||
{{ "delete" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
@if (bulkActions.showBulkReinviteUsers) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : bulkReinvite(organization)"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-envelope" aria-hidden="true"></i>
|
||||
{{ "reinviteSelected" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (bulkActions.showBulkConfirmUsers) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : bulkConfirm(organization)"
|
||||
>
|
||||
<span class="tw-text-success">
|
||||
<i class="bwi bwi-fw bwi-check" aria-hidden="true"></i>
|
||||
{{ "confirmSelected" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
@if (bulkActions.showBulkRestoreUsers) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : bulkRevokeOrRestore(false, organization)"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-plus-circle" aria-hidden="true"></i>
|
||||
{{ "restoreAccess" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (bulkActions.showBulkRevokeUsers) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : bulkRevokeOrRestore(true, organization)"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-minus-circle" aria-hidden="true"></i>
|
||||
{{ "revokeAccess" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (bulkActions.showBulkRemoveUsers) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : bulkRemove(organization)"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i aria-hidden="true" class="bwi bwi-fw bwi-close"></i>
|
||||
{{ "remove" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
@if (bulkActions.showBulkDeleteUsers) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : bulkDelete(organization)"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i aria-hidden="true" class="bwi bwi-fw bwi-trash"></i>
|
||||
{{ "delete" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
</bit-menu>
|
||||
</th>
|
||||
</tr>
|
||||
@@ -200,10 +221,10 @@
|
||||
alignContent="middle"
|
||||
[ngClass]="rowHeightClass"
|
||||
>
|
||||
<td bitCell (click)="dataSource.checkUser(u)" *ngIf="showUserManagementControls()">
|
||||
<input type="checkbox" bitCheckbox [(ngModel)]="$any(u).checked" />
|
||||
</td>
|
||||
<ng-container *ngIf="showUserManagementControls(); else readOnlyUserInfo">
|
||||
@if (showUserManagementControls()) {
|
||||
<td bitCell (click)="dataSource.checkUser(u)">
|
||||
<input type="checkbox" bitCheckbox [(ngModel)]="u.checked" />
|
||||
</td>
|
||||
<td bitCell (click)="edit(u, organization)" class="tw-cursor-pointer">
|
||||
<div class="tw-flex tw-items-center">
|
||||
<bit-avatar
|
||||
@@ -218,39 +239,31 @@
|
||||
<button type="button" bitLink>
|
||||
{{ u.name ?? u.email }}
|
||||
</button>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="secondary"
|
||||
*ngIf="u.status === userStatusType.Invited"
|
||||
>
|
||||
{{ "invited" | i18n }}
|
||||
</span>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="warning"
|
||||
*ngIf="u.status === userStatusType.Accepted"
|
||||
>
|
||||
{{ "needsConfirmation" | i18n }}
|
||||
</span>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="secondary"
|
||||
*ngIf="u.status === userStatusType.Revoked"
|
||||
>
|
||||
{{ "revoked" | i18n }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="tw-text-sm tw-text-muted" *ngIf="u.name">
|
||||
{{ u.email }}
|
||||
@if (u.status === userStatusType.Invited) {
|
||||
<span bitBadge class="tw-text-xs" variant="secondary">
|
||||
{{ "invited" | i18n }}
|
||||
</span>
|
||||
}
|
||||
@if (u.status === userStatusType.Accepted) {
|
||||
<span bitBadge class="tw-text-xs" variant="warning">
|
||||
{{ "needsConfirmation" | i18n }}
|
||||
</span>
|
||||
}
|
||||
@if (u.status === userStatusType.Revoked) {
|
||||
<span bitBadge class="tw-text-xs" variant="secondary">
|
||||
{{ "revoked" | i18n }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
@if (u.name) {
|
||||
<div class="tw-text-sm tw-text-muted">
|
||||
{{ u.email }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</ng-container>
|
||||
<ng-template #readOnlyUserInfo>
|
||||
} @else {
|
||||
<td bitCell>
|
||||
<div class="tw-flex tw-items-center">
|
||||
<bit-avatar
|
||||
@@ -263,40 +276,33 @@
|
||||
<div class="tw-flex tw-flex-col">
|
||||
<div class="tw-flex tw-flex-row tw-gap-2">
|
||||
<span>{{ u.name ?? u.email }}</span>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="secondary"
|
||||
*ngIf="u.status === userStatusType.Invited"
|
||||
>
|
||||
{{ "invited" | i18n }}
|
||||
</span>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="warning"
|
||||
*ngIf="u.status === userStatusType.Accepted"
|
||||
>
|
||||
{{ "needsConfirmation" | i18n }}
|
||||
</span>
|
||||
<span
|
||||
bitBadge
|
||||
class="tw-text-xs"
|
||||
variant="secondary"
|
||||
*ngIf="u.status === userStatusType.Revoked"
|
||||
>
|
||||
{{ "revoked" | i18n }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="tw-text-sm tw-text-muted" *ngIf="u.name">
|
||||
{{ u.email }}
|
||||
@if (u.status === userStatusType.Invited) {
|
||||
<span bitBadge class="tw-text-xs" variant="secondary">
|
||||
{{ "invited" | i18n }}
|
||||
</span>
|
||||
}
|
||||
@if (u.status === userStatusType.Accepted) {
|
||||
<span bitBadge class="tw-text-xs" variant="warning">
|
||||
{{ "needsConfirmation" | i18n }}
|
||||
</span>
|
||||
}
|
||||
@if (u.status === userStatusType.Revoked) {
|
||||
<span bitBadge class="tw-text-xs" variant="secondary">
|
||||
{{ "revoked" | i18n }}
|
||||
</span>
|
||||
}
|
||||
</div>
|
||||
@if (u.name) {
|
||||
<div class="tw-text-sm tw-text-muted">
|
||||
{{ u.email }}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</ng-template>
|
||||
}
|
||||
|
||||
<ng-container *ngIf="showUserManagementControls(); else readOnlyGroupsCell">
|
||||
@if (showUserManagementControls()) {
|
||||
<td
|
||||
bitCell
|
||||
(click)="
|
||||
@@ -314,8 +320,7 @@
|
||||
variant="secondary"
|
||||
></bit-badge-list>
|
||||
</td>
|
||||
</ng-container>
|
||||
<ng-template #readOnlyGroupsCell>
|
||||
} @else {
|
||||
<td bitCell>
|
||||
<bit-badge-list
|
||||
[items]="organization.useGroups ? u.groupNames : u.collectionNames"
|
||||
@@ -323,9 +328,9 @@
|
||||
variant="secondary"
|
||||
></bit-badge-list>
|
||||
</td>
|
||||
</ng-template>
|
||||
}
|
||||
|
||||
<ng-container *ngIf="showUserManagementControls(); else readOnlyRoleCell">
|
||||
@if (showUserManagementControls()) {
|
||||
<td
|
||||
bitCell
|
||||
(click)="edit(u, organization, memberTab.Role)"
|
||||
@@ -333,33 +338,30 @@
|
||||
>
|
||||
{{ u.type | userType }}
|
||||
</td>
|
||||
</ng-container>
|
||||
<ng-template #readOnlyRoleCell>
|
||||
} @else {
|
||||
<td bitCell class="tw-text-sm tw-text-muted">
|
||||
{{ u.type | userType }}
|
||||
</td>
|
||||
</ng-template>
|
||||
}
|
||||
|
||||
<td bitCell class="tw-text-muted">
|
||||
<ng-container *ngIf="u.twoFactorEnabled">
|
||||
@if (u.twoFactorEnabled) {
|
||||
<i
|
||||
class="bwi bwi-lock"
|
||||
title="{{ 'userUsingTwoStep' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "userUsingTwoStep" | i18n }}</span>
|
||||
</ng-container>
|
||||
}
|
||||
@let resetPasswordPolicyEnabled = resetPasswordPolicyEnabled$ | async;
|
||||
<ng-container
|
||||
*ngIf="showEnrolledStatus($any(u), organization, resetPasswordPolicyEnabled)"
|
||||
>
|
||||
@if (showEnrolledStatus(u, organization, resetPasswordPolicyEnabled)) {
|
||||
<i
|
||||
class="bwi bwi-key"
|
||||
title="{{ 'enrolledAccountRecovery' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "enrolledAccountRecovery" | i18n }}</span>
|
||||
</ng-container>
|
||||
}
|
||||
</td>
|
||||
<td bitCell>
|
||||
<div class="tw-flex tw-flex-row tw-items-center tw-justify-end tw-gap-2">
|
||||
@@ -374,122 +376,131 @@
|
||||
</div>
|
||||
|
||||
<bit-menu #rowMenu>
|
||||
<ng-container *ngIf="showUserManagementControls()">
|
||||
@if (showUserManagementControls()) {
|
||||
@if (u.status === userStatusType.Invited) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : reinvite(u, organization)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-envelope"></i>
|
||||
{{ "resendInvitation" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (u.status === userStatusType.Accepted) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : confirm(u, organization)"
|
||||
>
|
||||
<span class="tw-text-success">
|
||||
<i aria-hidden="true" class="bwi bwi-check"></i> {{ "confirm" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
@if (
|
||||
u.status === userStatusType.Accepted || u.status === userStatusType.Invited
|
||||
) {
|
||||
<bit-menu-divider></bit-menu-divider>
|
||||
}
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="reinvite(u, organization)"
|
||||
*ngIf="u.status === userStatusType.Invited"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-envelope"></i>
|
||||
{{ "resendInvitation" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="confirm(u, organization)"
|
||||
*ngIf="u.status === userStatusType.Accepted"
|
||||
>
|
||||
<span class="tw-text-success">
|
||||
<i aria-hidden="true" class="bwi bwi-check"></i> {{ "confirm" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
<bit-menu-divider
|
||||
*ngIf="
|
||||
u.status === userStatusType.Accepted || u.status === userStatusType.Invited
|
||||
"
|
||||
></bit-menu-divider>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="edit(u, organization, memberTab.Role)"
|
||||
(click)="isProcessing ? null : edit(u, organization, memberTab.Role)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-user"></i> {{ "memberRole" | i18n }}
|
||||
</button>
|
||||
@if (organization.useGroups) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : edit(u, organization, memberTab.Groups)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-users"></i> {{ "groups" | i18n }}
|
||||
</button>
|
||||
}
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="edit(u, organization, memberTab.Groups)"
|
||||
*ngIf="organization.useGroups"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-users"></i> {{ "groups" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="edit(u, organization, memberTab.Collections)"
|
||||
(click)="isProcessing ? null : edit(u, organization, memberTab.Collections)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-collection-shared"></i>
|
||||
{{ "collections" | i18n }}
|
||||
</button>
|
||||
<bit-menu-divider></bit-menu-divider>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="openEventsDialog(u, organization)"
|
||||
*ngIf="organization.useEvents && u.status === userStatusType.Confirmed"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-file-text"></i> {{ "eventLogs" | i18n }}
|
||||
</button>
|
||||
</ng-container>
|
||||
@if (organization.useEvents && u.status === userStatusType.Confirmed) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : openEventsDialog(u, organization)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-file-text"></i>
|
||||
{{ "eventLogs" | i18n }}
|
||||
</button>
|
||||
}
|
||||
}
|
||||
|
||||
<!-- Account recovery is available to all users with appropriate permissions -->
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="resetPassword(u, organization)"
|
||||
*ngIf="allowResetPassword(u, organization, resetPasswordPolicyEnabled)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-key"></i> {{ "recoverAccount" | i18n }}
|
||||
</button>
|
||||
@if (allowResetPassword(u, organization, resetPasswordPolicyEnabled)) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : resetPassword(u, organization)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-key"></i> {{ "recoverAccount" | i18n }}
|
||||
</button>
|
||||
}
|
||||
|
||||
<ng-container *ngIf="showUserManagementControls()">
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="restore(u, organization)"
|
||||
*ngIf="u.status === userStatusType.Revoked"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-plus-circle"></i>
|
||||
{{ "restoreAccess" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="revoke(u, organization)"
|
||||
*ngIf="u.status !== userStatusType.Revoked"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-minus-circle"></i>
|
||||
{{ "revokeAccess" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
*ngIf="!u.managedByOrganization"
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="remove(u, organization)"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i aria-hidden="true" class="bwi bwi-close"></i> {{ "remove" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
*ngIf="u.managedByOrganization"
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="deleteUser(u, organization)"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i class="bwi bwi-trash" aria-hidden="true"></i>
|
||||
{{ "delete" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
</ng-container>
|
||||
@if (showUserManagementControls()) {
|
||||
@if (u.status === userStatusType.Revoked) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : restore(u, organization)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-plus-circle"></i>
|
||||
{{ "restoreAccess" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (u.status !== userStatusType.Revoked) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : revoke(u, organization)"
|
||||
>
|
||||
<i aria-hidden="true" class="bwi bwi-minus-circle"></i>
|
||||
{{ "revokeAccess" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (!u.managedByOrganization) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : remove(u, organization)"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i aria-hidden="true" class="bwi bwi-close"></i> {{ "remove" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
} @else {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
(click)="isProcessing ? null : deleteUser(u, organization)"
|
||||
>
|
||||
<span class="tw-text-danger">
|
||||
<i class="bwi bwi-trash" aria-hidden="true"></i>
|
||||
{{ "delete" | i18n }}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
}
|
||||
</bit-menu>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</bit-table>
|
||||
</cdk-virtual-scroll-viewport>
|
||||
</ng-container>
|
||||
</ng-container>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
import { NO_ERRORS_SCHEMA } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { ActivatedRoute } from "@angular/router";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
import { BehaviorSubject, of } 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 { OrganizationManagementPreferencesService } from "@bitwarden/common/admin-console/abstractions/organization-management-preferences/organization-management-preferences.service";
|
||||
import { PolicyApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy-api.service.abstraction";
|
||||
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
|
||||
import {
|
||||
OrganizationUserStatusType,
|
||||
OrganizationUserType,
|
||||
} from "@bitwarden/common/admin-console/enums";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { OrganizationMetadataServiceAbstraction } from "@bitwarden/common/billing/abstractions/organization-metadata.service.abstraction";
|
||||
import { OrganizationBillingMetadataResponse } from "@bitwarden/common/billing/models/response/organization-billing-metadata.response";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service";
|
||||
import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/spec";
|
||||
import { OrganizationId, UserId } from "@bitwarden/common/types/guid";
|
||||
import { DialogService, ToastService } from "@bitwarden/components";
|
||||
import { newGuid } from "@bitwarden/guid";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
import { BillingConstraintService } from "@bitwarden/web-vault/app/billing/members/billing-constraint/billing-constraint.service";
|
||||
import { OrganizationWarningsService } from "@bitwarden/web-vault/app/billing/organizations/warnings/services";
|
||||
|
||||
import { OrganizationUserView } from "../core/views/organization-user.view";
|
||||
|
||||
import { AccountRecoveryDialogResultType } from "./components/account-recovery/account-recovery-dialog.component";
|
||||
import { MemberDialogResult } from "./components/member-dialog";
|
||||
import { vNextMembersComponent } from "./members.component";
|
||||
import {
|
||||
MemberDialogManagerService,
|
||||
MemberExportService,
|
||||
OrganizationMembersService,
|
||||
} from "./services";
|
||||
import { DeleteManagedMemberWarningService } from "./services/delete-managed-member/delete-managed-member-warning.service";
|
||||
import {
|
||||
MemberActionsService,
|
||||
MemberActionResult,
|
||||
} from "./services/member-actions/member-actions.service";
|
||||
|
||||
describe("vNextMembersComponent", () => {
|
||||
let component: vNextMembersComponent;
|
||||
let fixture: ComponentFixture<vNextMembersComponent>;
|
||||
|
||||
let mockApiService: MockProxy<ApiService>;
|
||||
let mockI18nService: MockProxy<I18nService>;
|
||||
let mockOrganizationManagementPreferencesService: MockProxy<OrganizationManagementPreferencesService>;
|
||||
let mockKeyService: MockProxy<KeyService>;
|
||||
let mockValidationService: MockProxy<ValidationService>;
|
||||
let mockLogService: MockProxy<LogService>;
|
||||
let mockUserNamePipe: MockProxy<UserNamePipe>;
|
||||
let mockDialogService: MockProxy<DialogService>;
|
||||
let mockToastService: MockProxy<ToastService>;
|
||||
let mockActivatedRoute: ActivatedRoute;
|
||||
let mockDeleteManagedMemberWarningService: MockProxy<DeleteManagedMemberWarningService>;
|
||||
let mockOrganizationWarningsService: MockProxy<OrganizationWarningsService>;
|
||||
let mockMemberActionsService: MockProxy<MemberActionsService>;
|
||||
let mockMemberDialogManager: MockProxy<MemberDialogManagerService>;
|
||||
let mockBillingConstraint: MockProxy<BillingConstraintService>;
|
||||
let mockMemberService: MockProxy<OrganizationMembersService>;
|
||||
let mockOrganizationService: MockProxy<OrganizationService>;
|
||||
let mockAccountService: FakeAccountService;
|
||||
let mockPolicyService: MockProxy<PolicyService>;
|
||||
let mockPolicyApiService: MockProxy<PolicyApiServiceAbstraction>;
|
||||
let mockOrganizationMetadataService: MockProxy<OrganizationMetadataServiceAbstraction>;
|
||||
let mockConfigService: MockProxy<ConfigService>;
|
||||
let mockEnvironmentService: MockProxy<EnvironmentService>;
|
||||
let mockMemberExportService: MockProxy<MemberExportService>;
|
||||
let mockFileDownloadService: MockProxy<FileDownloadService>;
|
||||
|
||||
let routeParamsSubject: BehaviorSubject<any>;
|
||||
let queryParamsSubject: BehaviorSubject<any>;
|
||||
|
||||
const mockUserId = newGuid() as UserId;
|
||||
const mockOrgId = newGuid() as OrganizationId;
|
||||
const mockOrg = {
|
||||
id: mockOrgId,
|
||||
name: "Test Organization",
|
||||
enabled: true,
|
||||
canManageUsers: true,
|
||||
useSecretsManager: true,
|
||||
useResetPassword: true,
|
||||
isProviderUser: false,
|
||||
} as Organization;
|
||||
|
||||
const mockUser = {
|
||||
id: newGuid(),
|
||||
userId: newGuid(),
|
||||
type: OrganizationUserType.User,
|
||||
status: OrganizationUserStatusType.Confirmed,
|
||||
email: "test@example.com",
|
||||
name: "Test User",
|
||||
resetPasswordEnrolled: false,
|
||||
accessSecretsManager: false,
|
||||
managedByOrganization: false,
|
||||
twoFactorEnabled: false,
|
||||
usesKeyConnector: false,
|
||||
hasMasterPassword: true,
|
||||
} as OrganizationUserView;
|
||||
|
||||
const mockBillingMetadata = {
|
||||
isSubscriptionUnpaid: false,
|
||||
} as Partial<OrganizationBillingMetadataResponse>;
|
||||
|
||||
beforeEach(async () => {
|
||||
routeParamsSubject = new BehaviorSubject({ organizationId: mockOrgId });
|
||||
queryParamsSubject = new BehaviorSubject({});
|
||||
|
||||
mockActivatedRoute = {
|
||||
params: routeParamsSubject.asObservable(),
|
||||
queryParams: queryParamsSubject.asObservable(),
|
||||
} as any;
|
||||
|
||||
mockApiService = mock<ApiService>();
|
||||
mockI18nService = mock<I18nService>();
|
||||
mockI18nService.t.mockImplementation((key: string) => key);
|
||||
|
||||
mockOrganizationManagementPreferencesService = mock<OrganizationManagementPreferencesService>();
|
||||
mockOrganizationManagementPreferencesService.autoConfirmFingerPrints = {
|
||||
state$: of(false),
|
||||
} as any;
|
||||
|
||||
mockKeyService = mock<KeyService>();
|
||||
mockValidationService = mock<ValidationService>();
|
||||
mockLogService = mock<LogService>();
|
||||
mockUserNamePipe = mock<UserNamePipe>();
|
||||
mockUserNamePipe.transform.mockReturnValue("Test User");
|
||||
|
||||
mockDialogService = mock<DialogService>();
|
||||
mockToastService = mock<ToastService>();
|
||||
mockDeleteManagedMemberWarningService = mock<DeleteManagedMemberWarningService>();
|
||||
mockOrganizationWarningsService = mock<OrganizationWarningsService>();
|
||||
mockMemberActionsService = mock<MemberActionsService>();
|
||||
mockMemberDialogManager = mock<MemberDialogManagerService>();
|
||||
mockBillingConstraint = mock<BillingConstraintService>();
|
||||
|
||||
mockMemberService = mock<OrganizationMembersService>();
|
||||
mockMemberService.loadUsers.mockResolvedValue([mockUser]);
|
||||
|
||||
mockOrganizationService = mock<OrganizationService>();
|
||||
mockOrganizationService.organizations$.mockReturnValue(of([mockOrg]));
|
||||
|
||||
mockAccountService = mockAccountServiceWith(mockUserId);
|
||||
|
||||
mockPolicyService = mock<PolicyService>();
|
||||
|
||||
mockPolicyApiService = mock<PolicyApiServiceAbstraction>();
|
||||
mockOrganizationMetadataService = mock<OrganizationMetadataServiceAbstraction>();
|
||||
mockOrganizationMetadataService.getOrganizationMetadata$.mockReturnValue(
|
||||
of(mockBillingMetadata),
|
||||
);
|
||||
|
||||
mockConfigService = mock<ConfigService>();
|
||||
mockConfigService.getFeatureFlag$.mockReturnValue(of(false));
|
||||
|
||||
mockEnvironmentService = mock<EnvironmentService>();
|
||||
mockEnvironmentService.environment$ = of({
|
||||
isCloud: () => false,
|
||||
} as any);
|
||||
|
||||
mockMemberExportService = mock<MemberExportService>();
|
||||
mockFileDownloadService = mock<FileDownloadService>();
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
declarations: [vNextMembersComponent],
|
||||
providers: [
|
||||
{ provide: ApiService, useValue: mockApiService },
|
||||
{ provide: I18nService, useValue: mockI18nService },
|
||||
{
|
||||
provide: OrganizationManagementPreferencesService,
|
||||
useValue: mockOrganizationManagementPreferencesService,
|
||||
},
|
||||
{ provide: KeyService, useValue: mockKeyService },
|
||||
{ provide: ValidationService, useValue: mockValidationService },
|
||||
{ provide: LogService, useValue: mockLogService },
|
||||
{ provide: UserNamePipe, useValue: mockUserNamePipe },
|
||||
{ provide: DialogService, useValue: mockDialogService },
|
||||
{ provide: ToastService, useValue: mockToastService },
|
||||
{ provide: ActivatedRoute, useValue: mockActivatedRoute },
|
||||
{
|
||||
provide: DeleteManagedMemberWarningService,
|
||||
useValue: mockDeleteManagedMemberWarningService,
|
||||
},
|
||||
{ provide: OrganizationWarningsService, useValue: mockOrganizationWarningsService },
|
||||
{ provide: MemberActionsService, useValue: mockMemberActionsService },
|
||||
{ provide: MemberDialogManagerService, useValue: mockMemberDialogManager },
|
||||
{ provide: BillingConstraintService, useValue: mockBillingConstraint },
|
||||
{ provide: OrganizationMembersService, useValue: mockMemberService },
|
||||
{ provide: OrganizationService, useValue: mockOrganizationService },
|
||||
{ provide: AccountService, useValue: mockAccountService },
|
||||
{ provide: PolicyService, useValue: mockPolicyService },
|
||||
{ provide: PolicyApiServiceAbstraction, useValue: mockPolicyApiService },
|
||||
{
|
||||
provide: OrganizationMetadataServiceAbstraction,
|
||||
useValue: mockOrganizationMetadataService,
|
||||
},
|
||||
{ provide: ConfigService, useValue: mockConfigService },
|
||||
{ provide: EnvironmentService, useValue: mockEnvironmentService },
|
||||
{ provide: MemberExportService, useValue: mockMemberExportService },
|
||||
{ provide: FileDownloadService, useValue: mockFileDownloadService },
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA],
|
||||
})
|
||||
.overrideComponent(vNextMembersComponent, {
|
||||
remove: { imports: [] },
|
||||
add: { template: "<div></div>" },
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(vNextMembersComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (fixture) {
|
||||
fixture.destroy();
|
||||
}
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("load", () => {
|
||||
it("should load users and set data source", async () => {
|
||||
const users = [mockUser];
|
||||
mockMemberService.loadUsers.mockResolvedValue(users);
|
||||
|
||||
await component.load(mockOrg);
|
||||
|
||||
expect(mockMemberService.loadUsers).toHaveBeenCalledWith(mockOrg);
|
||||
expect(component["dataSource"]().data).toEqual(users);
|
||||
expect(component["firstLoaded"]()).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle empty response", async () => {
|
||||
mockMemberService.loadUsers.mockResolvedValue([]);
|
||||
|
||||
await component.load(mockOrg);
|
||||
|
||||
expect(component["dataSource"]().data).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("remove", () => {
|
||||
it("should remove user when confirmed", async () => {
|
||||
mockMemberDialogManager.openRemoveUserConfirmationDialog.mockResolvedValue(true);
|
||||
mockMemberActionsService.removeUser.mockResolvedValue({ success: true });
|
||||
|
||||
const removeSpy = jest.spyOn(component["dataSource"](), "removeUser");
|
||||
|
||||
await component.remove(mockUser, mockOrg);
|
||||
|
||||
expect(mockMemberDialogManager.openRemoveUserConfirmationDialog).toHaveBeenCalledWith(
|
||||
mockUser,
|
||||
);
|
||||
expect(mockMemberActionsService.removeUser).toHaveBeenCalledWith(mockOrg, mockUser.id);
|
||||
expect(removeSpy).toHaveBeenCalledWith(mockUser);
|
||||
expect(mockToastService.showToast).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should not remove user when not confirmed", async () => {
|
||||
mockMemberDialogManager.openRemoveUserConfirmationDialog.mockResolvedValue(false);
|
||||
|
||||
const result = await component.remove(mockUser, mockOrg);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(mockMemberActionsService.removeUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle errors via handleMemberActionResult", async () => {
|
||||
mockMemberDialogManager.openRemoveUserConfirmationDialog.mockResolvedValue(true);
|
||||
mockMemberActionsService.removeUser.mockResolvedValue({
|
||||
success: false,
|
||||
error: "Remove failed",
|
||||
});
|
||||
|
||||
await component.remove(mockUser, mockOrg);
|
||||
|
||||
expect(mockToastService.showToast).toHaveBeenCalledWith({
|
||||
variant: "error",
|
||||
message: "Remove failed",
|
||||
});
|
||||
expect(mockLogService.error).toHaveBeenCalledWith("Remove failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("reinvite", () => {
|
||||
it("should reinvite user successfully", async () => {
|
||||
mockMemberActionsService.reinviteUser.mockResolvedValue({ success: true });
|
||||
|
||||
await component.reinvite(mockUser, mockOrg);
|
||||
|
||||
expect(mockMemberActionsService.reinviteUser).toHaveBeenCalledWith(mockOrg, mockUser.id);
|
||||
expect(mockToastService.showToast).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle errors via handleMemberActionResult", async () => {
|
||||
mockMemberActionsService.reinviteUser.mockResolvedValue({
|
||||
success: false,
|
||||
error: "Reinvite failed",
|
||||
});
|
||||
|
||||
await component.reinvite(mockUser, mockOrg);
|
||||
|
||||
expect(mockToastService.showToast).toHaveBeenCalledWith({
|
||||
variant: "error",
|
||||
message: "Reinvite failed",
|
||||
});
|
||||
expect(mockLogService.error).toHaveBeenCalledWith("Reinvite failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("confirm", () => {
|
||||
it("should confirm user with auto-confirm enabled", async () => {
|
||||
mockOrganizationManagementPreferencesService.autoConfirmFingerPrints.state$ = of(true);
|
||||
mockMemberActionsService.confirmUser.mockResolvedValue({ success: true });
|
||||
|
||||
// Mock getPublicKeyForConfirm to return a public key
|
||||
const mockPublicKey = new Uint8Array([1, 2, 3, 4]);
|
||||
mockMemberActionsService.getPublicKeyForConfirm.mockResolvedValue(mockPublicKey);
|
||||
|
||||
const replaceSpy = jest.spyOn(component["dataSource"](), "replaceUser");
|
||||
|
||||
await component.confirm(mockUser, mockOrg);
|
||||
|
||||
expect(mockMemberActionsService.getPublicKeyForConfirm).toHaveBeenCalledWith(mockUser);
|
||||
expect(mockMemberActionsService.confirmUser).toHaveBeenCalledWith(
|
||||
mockUser,
|
||||
mockPublicKey,
|
||||
mockOrg,
|
||||
);
|
||||
expect(replaceSpy).toHaveBeenCalled();
|
||||
expect(mockToastService.showToast).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle null user", async () => {
|
||||
mockOrganizationManagementPreferencesService.autoConfirmFingerPrints.state$ = of(true);
|
||||
|
||||
// Mock getPublicKeyForConfirm to return null
|
||||
mockMemberActionsService.getPublicKeyForConfirm.mockResolvedValue(null);
|
||||
|
||||
await component.confirm(mockUser, mockOrg);
|
||||
|
||||
expect(mockMemberActionsService.getPublicKeyForConfirm).toHaveBeenCalled();
|
||||
expect(mockMemberActionsService.confirmUser).not.toHaveBeenCalled();
|
||||
expect(mockLogService.warning).toHaveBeenCalledWith("Public key not found");
|
||||
});
|
||||
|
||||
it("should handle API errors gracefully", async () => {
|
||||
// Mock getPublicKeyForConfirm to return null
|
||||
mockMemberActionsService.getPublicKeyForConfirm.mockResolvedValue(null);
|
||||
|
||||
await component.confirm(mockUser, mockOrg);
|
||||
|
||||
expect(mockMemberActionsService.getPublicKeyForConfirm).toHaveBeenCalled();
|
||||
expect(mockLogService.warning).toHaveBeenCalledWith("Public key not found");
|
||||
});
|
||||
});
|
||||
|
||||
describe("revoke", () => {
|
||||
it("should revoke user when confirmed", async () => {
|
||||
mockMemberDialogManager.openRevokeUserConfirmationDialog.mockResolvedValue(true);
|
||||
mockMemberActionsService.revokeUser.mockResolvedValue({ success: true });
|
||||
mockMemberService.loadUsers.mockResolvedValue([mockUser]);
|
||||
|
||||
await component.revoke(mockUser, mockOrg);
|
||||
|
||||
expect(mockMemberDialogManager.openRevokeUserConfirmationDialog).toHaveBeenCalledWith(
|
||||
mockUser,
|
||||
);
|
||||
expect(mockMemberActionsService.revokeUser).toHaveBeenCalledWith(mockOrg, mockUser.id);
|
||||
expect(mockToastService.showToast).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should not revoke user when not confirmed", async () => {
|
||||
mockMemberDialogManager.openRevokeUserConfirmationDialog.mockResolvedValue(false);
|
||||
|
||||
const result = await component.revoke(mockUser, mockOrg);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(mockMemberActionsService.revokeUser).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("restore", () => {
|
||||
it("should restore user successfully", async () => {
|
||||
mockMemberActionsService.restoreUser.mockResolvedValue({ success: true });
|
||||
mockMemberService.loadUsers.mockResolvedValue([mockUser]);
|
||||
|
||||
await component.restore(mockUser, mockOrg);
|
||||
|
||||
expect(mockMemberActionsService.restoreUser).toHaveBeenCalledWith(mockOrg, mockUser.id);
|
||||
expect(mockToastService.showToast).toHaveBeenCalled();
|
||||
expect(mockMemberService.loadUsers).toHaveBeenCalledWith(mockOrg);
|
||||
});
|
||||
|
||||
it("should handle errors via handleMemberActionResult", async () => {
|
||||
mockMemberActionsService.restoreUser.mockResolvedValue({
|
||||
success: false,
|
||||
error: "Restore failed",
|
||||
});
|
||||
|
||||
await component.restore(mockUser, mockOrg);
|
||||
|
||||
expect(mockToastService.showToast).toHaveBeenCalledWith({
|
||||
variant: "error",
|
||||
message: "Restore failed",
|
||||
});
|
||||
expect(mockLogService.error).toHaveBeenCalledWith("Restore failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("invite", () => {
|
||||
it("should open invite dialog when seat limit not reached", async () => {
|
||||
mockBillingConstraint.seatLimitReached.mockResolvedValue(false);
|
||||
mockMemberDialogManager.openInviteDialog.mockResolvedValue(MemberDialogResult.Saved);
|
||||
|
||||
await component.invite(mockOrg);
|
||||
|
||||
expect(mockBillingConstraint.checkSeatLimit).toHaveBeenCalledWith(
|
||||
mockOrg,
|
||||
mockBillingMetadata,
|
||||
);
|
||||
expect(mockMemberDialogManager.openInviteDialog).toHaveBeenCalledWith(
|
||||
mockOrg,
|
||||
mockBillingMetadata,
|
||||
expect.any(Array),
|
||||
);
|
||||
});
|
||||
|
||||
it("should reload organization and refresh metadata cache after successful invite", async () => {
|
||||
mockBillingConstraint.seatLimitReached.mockResolvedValue(false);
|
||||
mockMemberDialogManager.openInviteDialog.mockResolvedValue(MemberDialogResult.Saved);
|
||||
mockMemberService.loadUsers.mockResolvedValue([mockUser]);
|
||||
|
||||
await component.invite(mockOrg);
|
||||
|
||||
expect(mockMemberService.loadUsers).toHaveBeenCalledWith(mockOrg);
|
||||
expect(mockOrganizationMetadataService.refreshMetadataCache).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should not open dialog when seat limit reached", async () => {
|
||||
mockBillingConstraint.seatLimitReached.mockResolvedValue(true);
|
||||
|
||||
await component.invite(mockOrg);
|
||||
|
||||
expect(mockMemberDialogManager.openInviteDialog).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("bulkRemove", () => {
|
||||
it("should open bulk remove dialog and reload", async () => {
|
||||
const users = [mockUser];
|
||||
jest.spyOn(component["dataSource"](), "getCheckedUsersWithLimit").mockReturnValue(users);
|
||||
mockMemberService.loadUsers.mockResolvedValue([mockUser]);
|
||||
|
||||
await component.bulkRemove(mockOrg);
|
||||
|
||||
expect(mockMemberDialogManager.openBulkRemoveDialog).toHaveBeenCalledWith(mockOrg, users);
|
||||
expect(mockOrganizationMetadataService.refreshMetadataCache).toHaveBeenCalled();
|
||||
expect(mockMemberService.loadUsers).toHaveBeenCalledWith(mockOrg);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bulkDelete", () => {
|
||||
it("should open bulk delete dialog and reload", async () => {
|
||||
const users = [mockUser];
|
||||
jest.spyOn(component["dataSource"](), "getCheckedUsersWithLimit").mockReturnValue(users);
|
||||
mockMemberService.loadUsers.mockResolvedValue([mockUser]);
|
||||
|
||||
await component.bulkDelete(mockOrg);
|
||||
|
||||
expect(mockMemberDialogManager.openBulkDeleteDialog).toHaveBeenCalledWith(mockOrg, users);
|
||||
expect(mockMemberService.loadUsers).toHaveBeenCalledWith(mockOrg);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bulkRevokeOrRestore", () => {
|
||||
it.each([
|
||||
{ isRevoking: true, action: "revoke" },
|
||||
{ isRevoking: false, action: "restore" },
|
||||
])(
|
||||
"should open bulk $action dialog and reload when isRevoking is $isRevoking",
|
||||
async ({ isRevoking }) => {
|
||||
const users = [mockUser];
|
||||
jest.spyOn(component["dataSource"](), "getCheckedUsersWithLimit").mockReturnValue(users);
|
||||
mockMemberService.loadUsers.mockResolvedValue([mockUser]);
|
||||
|
||||
await component.bulkRevokeOrRestore(isRevoking, mockOrg);
|
||||
|
||||
expect(mockMemberDialogManager.openBulkRestoreRevokeDialog).toHaveBeenCalledWith(
|
||||
mockOrg,
|
||||
users,
|
||||
isRevoking,
|
||||
);
|
||||
expect(mockMemberService.loadUsers).toHaveBeenCalledWith(mockOrg);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("bulkReinvite", () => {
|
||||
it("should reinvite invited users", async () => {
|
||||
const invitedUser = {
|
||||
...mockUser,
|
||||
status: OrganizationUserStatusType.Invited,
|
||||
};
|
||||
jest.spyOn(component["dataSource"](), "isIncreasedBulkLimitEnabled").mockReturnValue(false);
|
||||
jest.spyOn(component["dataSource"](), "getCheckedUsers").mockReturnValue([invitedUser]);
|
||||
mockMemberActionsService.bulkReinvite.mockResolvedValue({ successful: true });
|
||||
|
||||
await component.bulkReinvite(mockOrg);
|
||||
|
||||
expect(mockMemberActionsService.bulkReinvite).toHaveBeenCalledWith(mockOrg, [invitedUser.id]);
|
||||
expect(mockMemberDialogManager.openBulkStatusDialog).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should show error when no invited users selected", async () => {
|
||||
const confirmedUser = {
|
||||
...mockUser,
|
||||
status: OrganizationUserStatusType.Confirmed,
|
||||
};
|
||||
jest.spyOn(component["dataSource"](), "isIncreasedBulkLimitEnabled").mockReturnValue(false);
|
||||
jest.spyOn(component["dataSource"](), "getCheckedUsers").mockReturnValue([confirmedUser]);
|
||||
|
||||
await component.bulkReinvite(mockOrg);
|
||||
|
||||
expect(mockToastService.showToast).toHaveBeenCalledWith({
|
||||
variant: "error",
|
||||
title: "errorOccurred",
|
||||
message: "noSelectedUsersApplicable",
|
||||
});
|
||||
expect(mockMemberActionsService.bulkReinvite).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle errors", async () => {
|
||||
const invitedUser = {
|
||||
...mockUser,
|
||||
status: OrganizationUserStatusType.Invited,
|
||||
};
|
||||
jest.spyOn(component["dataSource"](), "isIncreasedBulkLimitEnabled").mockReturnValue(false);
|
||||
jest.spyOn(component["dataSource"](), "getCheckedUsers").mockReturnValue([invitedUser]);
|
||||
const error = new Error("Bulk reinvite failed");
|
||||
mockMemberActionsService.bulkReinvite.mockResolvedValue({ successful: false, failed: error });
|
||||
|
||||
await component.bulkReinvite(mockOrg);
|
||||
|
||||
expect(mockValidationService.showError).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bulkConfirm", () => {
|
||||
it("should open bulk confirm dialog and reload", async () => {
|
||||
const users = [mockUser];
|
||||
jest.spyOn(component["dataSource"](), "getCheckedUsersWithLimit").mockReturnValue(users);
|
||||
mockMemberService.loadUsers.mockResolvedValue([mockUser]);
|
||||
|
||||
await component.bulkConfirm(mockOrg);
|
||||
|
||||
expect(mockMemberDialogManager.openBulkConfirmDialog).toHaveBeenCalledWith(mockOrg, users);
|
||||
expect(mockMemberService.loadUsers).toHaveBeenCalledWith(mockOrg);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bulkEnableSM", () => {
|
||||
it("should open bulk enable SM dialog and reload", async () => {
|
||||
const users = [mockUser];
|
||||
jest.spyOn(component["dataSource"](), "getCheckedUsersWithLimit").mockReturnValue(users);
|
||||
jest.spyOn(component["dataSource"](), "uncheckAllUsers");
|
||||
mockMemberService.loadUsers.mockResolvedValue([mockUser]);
|
||||
|
||||
await component.bulkEnableSM(mockOrg);
|
||||
|
||||
expect(mockMemberDialogManager.openBulkEnableSecretsManagerDialog).toHaveBeenCalledWith(
|
||||
mockOrg,
|
||||
users,
|
||||
);
|
||||
expect(component["dataSource"]().uncheckAllUsers).toHaveBeenCalled();
|
||||
expect(mockMemberService.loadUsers).toHaveBeenCalledWith(mockOrg);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resetPassword", () => {
|
||||
it("should open account recovery dialog", async () => {
|
||||
mockMemberDialogManager.openAccountRecoveryDialog.mockResolvedValue(
|
||||
AccountRecoveryDialogResultType.Ok,
|
||||
);
|
||||
mockMemberService.loadUsers.mockResolvedValue([mockUser]);
|
||||
|
||||
await component.resetPassword(mockUser, mockOrg);
|
||||
|
||||
expect(mockMemberDialogManager.openAccountRecoveryDialog).toHaveBeenCalledWith(
|
||||
mockUser,
|
||||
mockOrg,
|
||||
);
|
||||
expect(mockMemberService.loadUsers).toHaveBeenCalledWith(mockOrg);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteUser", () => {
|
||||
it("should delete user when confirmed", async () => {
|
||||
mockMemberDialogManager.openDeleteUserConfirmationDialog.mockResolvedValue(true);
|
||||
mockMemberActionsService.deleteUser.mockResolvedValue({ success: true });
|
||||
const removeSpy = jest.spyOn(component["dataSource"](), "removeUser");
|
||||
|
||||
await component.deleteUser(mockUser, mockOrg);
|
||||
|
||||
expect(mockMemberDialogManager.openDeleteUserConfirmationDialog).toHaveBeenCalledWith(
|
||||
mockUser,
|
||||
mockOrg,
|
||||
);
|
||||
expect(mockMemberActionsService.deleteUser).toHaveBeenCalledWith(mockOrg, mockUser.id);
|
||||
expect(removeSpy).toHaveBeenCalledWith(mockUser);
|
||||
expect(mockToastService.showToast).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should not delete user when not confirmed", async () => {
|
||||
mockMemberDialogManager.openDeleteUserConfirmationDialog.mockResolvedValue(false);
|
||||
|
||||
const result = await component.deleteUser(mockUser, mockOrg);
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(mockMemberActionsService.deleteUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle errors via handleMemberActionResult", async () => {
|
||||
mockMemberDialogManager.openDeleteUserConfirmationDialog.mockResolvedValue(true);
|
||||
mockMemberActionsService.deleteUser.mockResolvedValue({
|
||||
success: false,
|
||||
error: "Delete failed",
|
||||
});
|
||||
|
||||
await component.deleteUser(mockUser, mockOrg);
|
||||
|
||||
expect(mockToastService.showToast).toHaveBeenCalledWith({
|
||||
variant: "error",
|
||||
message: "Delete failed",
|
||||
});
|
||||
expect(mockLogService.error).toHaveBeenCalledWith("Delete failed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleMemberActionResult", () => {
|
||||
it("should show success toast when result is successful", async () => {
|
||||
const result: MemberActionResult = { success: true };
|
||||
|
||||
await component.handleMemberActionResult(result, "testSuccessKey", mockUser);
|
||||
|
||||
expect(mockToastService.showToast).toHaveBeenCalledWith({
|
||||
variant: "success",
|
||||
message: "testSuccessKey",
|
||||
});
|
||||
});
|
||||
|
||||
it("should execute side effect when provided and successful", async () => {
|
||||
const result: MemberActionResult = { success: true };
|
||||
const sideEffect = jest.fn();
|
||||
|
||||
await component.handleMemberActionResult(result, "testSuccessKey", mockUser, sideEffect);
|
||||
|
||||
expect(sideEffect).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should show error toast when result is not successful", async () => {
|
||||
const result: MemberActionResult = { success: false, error: "Error message" };
|
||||
const sideEffect = jest.fn();
|
||||
|
||||
await component.handleMemberActionResult(result, "testSuccessKey", mockUser, sideEffect);
|
||||
|
||||
expect(mockToastService.showToast).toHaveBeenCalledWith({
|
||||
variant: "error",
|
||||
message: "Error message",
|
||||
});
|
||||
expect(mockLogService.error).toHaveBeenCalledWith("Error message");
|
||||
expect(sideEffect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should propagate error when side effect throws", async () => {
|
||||
const result: MemberActionResult = { success: true };
|
||||
const error = new Error("Side effect failed");
|
||||
const sideEffect = jest.fn().mockRejectedValue(error);
|
||||
|
||||
await expect(
|
||||
component.handleMemberActionResult(result, "testSuccessKey", mockUser, sideEffect),
|
||||
).rejects.toThrow("Side effect failed");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,12 @@
|
||||
import { Component, computed, Signal } from "@angular/core";
|
||||
import { Component, computed, inject, signal, Signal, WritableSignal } from "@angular/core";
|
||||
import { takeUntilDestroyed, toSignal } from "@angular/core/rxjs-interop";
|
||||
import { FormControl } from "@angular/forms";
|
||||
import { ActivatedRoute } from "@angular/router";
|
||||
import {
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
concatMap,
|
||||
debounceTime,
|
||||
filter,
|
||||
firstValueFrom,
|
||||
from,
|
||||
@@ -15,11 +18,8 @@ import {
|
||||
take,
|
||||
} from "rxjs";
|
||||
|
||||
import { OrganizationUserUserDetailsResponse } from "@bitwarden/admin-console/common";
|
||||
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 { OrganizationManagementPreferencesService } from "@bitwarden/common/admin-console/abstractions/organization-management-preferences/organization-management-preferences.service";
|
||||
import { PolicyApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy-api.service.abstraction";
|
||||
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
|
||||
import {
|
||||
@@ -35,22 +35,21 @@ import { OrganizationMetadataServiceAbstraction } from "@bitwarden/common/billin
|
||||
import { OrganizationBillingMetadataResponse } from "@bitwarden/common/billing/models/response/organization-billing-metadata.response";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service";
|
||||
import { getById } from "@bitwarden/common/platform/misc";
|
||||
import { DialogService, ToastService } from "@bitwarden/components";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
import { UserId } from "@bitwarden/user-core";
|
||||
import { BillingConstraintService } from "@bitwarden/web-vault/app/billing/members/billing-constraint/billing-constraint.service";
|
||||
import { OrganizationWarningsService } from "@bitwarden/web-vault/app/billing/organizations/warnings/services";
|
||||
|
||||
import { BaseMembersComponent } from "../../common/base-members.component";
|
||||
import {
|
||||
CloudBulkReinviteLimit,
|
||||
MaxCheckedCount,
|
||||
PeopleTableDataSource,
|
||||
MembersTableDataSource,
|
||||
peopleFilter,
|
||||
showConfirmBanner,
|
||||
} from "../../common/people-table-data-source";
|
||||
import { OrganizationUserView } from "../core/views/organization-user.view";
|
||||
|
||||
@@ -67,8 +66,13 @@ import {
|
||||
MemberActionResult,
|
||||
} from "./services/member-actions/member-actions.service";
|
||||
|
||||
class MembersTableDataSource extends PeopleTableDataSource<OrganizationUserView> {
|
||||
protected statusType = OrganizationUserStatusType;
|
||||
interface BulkMemberFlags {
|
||||
showBulkRestoreUsers: boolean;
|
||||
showBulkRevokeUsers: boolean;
|
||||
showBulkRemoveUsers: boolean;
|
||||
showBulkDeleteUsers: boolean;
|
||||
showBulkConfirmUsers: boolean;
|
||||
showBulkReinviteUsers: boolean;
|
||||
}
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
@@ -77,71 +81,76 @@ class MembersTableDataSource extends PeopleTableDataSource<OrganizationUserView>
|
||||
templateUrl: "members.component.html",
|
||||
standalone: false,
|
||||
})
|
||||
export class MembersComponent extends BaseMembersComponent<OrganizationUserView> {
|
||||
userType = OrganizationUserType;
|
||||
userStatusType = OrganizationUserStatusType;
|
||||
memberTab = MemberDialogTab;
|
||||
protected dataSource: MembersTableDataSource;
|
||||
|
||||
readonly organization: Signal<Organization | undefined>;
|
||||
status: OrganizationUserStatusType | undefined;
|
||||
export class vNextMembersComponent {
|
||||
protected i18nService = inject(I18nService);
|
||||
protected validationService = inject(ValidationService);
|
||||
protected logService = inject(LogService);
|
||||
protected userNamePipe = inject(UserNamePipe);
|
||||
protected dialogService = inject(DialogService);
|
||||
protected toastService = inject(ToastService);
|
||||
private route = inject(ActivatedRoute);
|
||||
protected deleteManagedMemberWarningService = inject(DeleteManagedMemberWarningService);
|
||||
private organizationWarningsService = inject(OrganizationWarningsService);
|
||||
private memberActionsService = inject(MemberActionsService);
|
||||
private memberDialogManager = inject(MemberDialogManagerService);
|
||||
protected billingConstraint = inject(BillingConstraintService);
|
||||
protected memberService = inject(OrganizationMembersService);
|
||||
private organizationService = inject(OrganizationService);
|
||||
private accountService = inject(AccountService);
|
||||
private policyService = inject(PolicyService);
|
||||
private policyApiService = inject(PolicyApiServiceAbstraction);
|
||||
private organizationMetadataService = inject(OrganizationMetadataServiceAbstraction);
|
||||
private configService = inject(ConfigService);
|
||||
private environmentService = inject(EnvironmentService);
|
||||
private memberExportService = inject(MemberExportService);
|
||||
|
||||
private userId$: Observable<UserId> = this.accountService.activeAccount$.pipe(getUserId);
|
||||
|
||||
resetPasswordPolicyEnabled$: Observable<boolean>;
|
||||
protected userType = OrganizationUserType;
|
||||
protected userStatusType = OrganizationUserStatusType;
|
||||
protected memberTab = MemberDialogTab;
|
||||
|
||||
protected searchControl = new FormControl("", { nonNullable: true });
|
||||
protected statusToggle = new BehaviorSubject<OrganizationUserStatusType | undefined>(undefined);
|
||||
|
||||
protected readonly dataSource: Signal<MembersTableDataSource> = signal(
|
||||
new MembersTableDataSource(this.configService, this.environmentService),
|
||||
);
|
||||
protected readonly organization: Signal<Organization | undefined>;
|
||||
protected readonly firstLoaded: WritableSignal<boolean> = signal(false);
|
||||
|
||||
protected bulkMenuOptions$ = this.dataSource()
|
||||
.usersUpdated()
|
||||
.pipe(map((members) => this.bulkMenuOptions(members)));
|
||||
|
||||
protected showConfirmBanner$ = this.dataSource()
|
||||
.usersUpdated()
|
||||
.pipe(map(() => showConfirmBanner(this.dataSource())));
|
||||
|
||||
protected isProcessing = this.memberActionsService.isProcessing;
|
||||
|
||||
protected readonly canUseSecretsManager: Signal<boolean> = computed(
|
||||
() => this.organization()?.useSecretsManager ?? false,
|
||||
);
|
||||
|
||||
protected readonly showUserManagementControls: Signal<boolean> = computed(
|
||||
() => this.organization()?.canManageUsers ?? false,
|
||||
);
|
||||
|
||||
protected billingMetadata$: Observable<OrganizationBillingMetadataResponse>;
|
||||
|
||||
protected resetPasswordPolicyEnabled$: Observable<boolean>;
|
||||
|
||||
// Fixed sizes used for cdkVirtualScroll
|
||||
protected rowHeight = 66;
|
||||
protected rowHeightClass = `tw-h-[66px]`;
|
||||
|
||||
constructor(
|
||||
apiService: ApiService,
|
||||
i18nService: I18nService,
|
||||
organizationManagementPreferencesService: OrganizationManagementPreferencesService,
|
||||
keyService: KeyService,
|
||||
validationService: ValidationService,
|
||||
logService: LogService,
|
||||
userNamePipe: UserNamePipe,
|
||||
dialogService: DialogService,
|
||||
toastService: ToastService,
|
||||
private route: ActivatedRoute,
|
||||
protected deleteManagedMemberWarningService: DeleteManagedMemberWarningService,
|
||||
private organizationWarningsService: OrganizationWarningsService,
|
||||
private memberActionsService: MemberActionsService,
|
||||
private memberDialogManager: MemberDialogManagerService,
|
||||
protected billingConstraint: BillingConstraintService,
|
||||
protected memberService: OrganizationMembersService,
|
||||
private organizationService: OrganizationService,
|
||||
private accountService: AccountService,
|
||||
private policyService: PolicyService,
|
||||
private policyApiService: PolicyApiServiceAbstraction,
|
||||
private organizationMetadataService: OrganizationMetadataServiceAbstraction,
|
||||
private memberExportService: MemberExportService,
|
||||
private fileDownloadService: FileDownloadService,
|
||||
private configService: ConfigService,
|
||||
private environmentService: EnvironmentService,
|
||||
) {
|
||||
super(
|
||||
apiService,
|
||||
i18nService,
|
||||
keyService,
|
||||
validationService,
|
||||
logService,
|
||||
userNamePipe,
|
||||
dialogService,
|
||||
organizationManagementPreferencesService,
|
||||
toastService,
|
||||
);
|
||||
|
||||
this.dataSource = new MembersTableDataSource(this.configService, this.environmentService);
|
||||
constructor() {
|
||||
combineLatest([this.searchControl.valueChanges.pipe(debounceTime(200)), this.statusToggle])
|
||||
.pipe(takeUntilDestroyed())
|
||||
.subscribe(
|
||||
([searchText, status]) => (this.dataSource().filter = peopleFilter(searchText, status)),
|
||||
);
|
||||
|
||||
const organization$ = this.route.params.pipe(
|
||||
concatMap((params) =>
|
||||
@@ -184,7 +193,7 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
this.searchControl.setValue(qParams.search);
|
||||
|
||||
if (qParams.viewEvents != null) {
|
||||
const user = this.dataSource.data.filter((u) => u.id === qParams.viewEvents);
|
||||
const user = this.dataSource().data.filter((u) => u.id === qParams.viewEvents);
|
||||
if (user.length > 0 && user[0].status === OrganizationUserStatusType.Confirmed) {
|
||||
this.openEventsDialog(user[0], organization!);
|
||||
}
|
||||
@@ -218,80 +227,62 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
this.billingMetadata$.pipe(take(1), takeUntilDestroyed()).subscribe();
|
||||
}
|
||||
|
||||
override async load(organization: Organization) {
|
||||
await super.load(organization);
|
||||
async load(organization: Organization) {
|
||||
const response = await this.memberService.loadUsers(organization);
|
||||
this.dataSource().data = response;
|
||||
this.firstLoaded.set(true);
|
||||
}
|
||||
|
||||
async getUsers(organization: Organization): Promise<OrganizationUserView[]> {
|
||||
return await this.memberService.loadUsers(organization);
|
||||
}
|
||||
|
||||
async removeUser(id: string, organization: Organization): Promise<MemberActionResult> {
|
||||
return await this.memberActionsService.removeUser(organization, id);
|
||||
}
|
||||
|
||||
async revokeUser(id: string, organization: Organization): Promise<MemberActionResult> {
|
||||
return await this.memberActionsService.revokeUser(organization, id);
|
||||
}
|
||||
|
||||
async restoreUser(id: string, organization: Organization): Promise<MemberActionResult> {
|
||||
return await this.memberActionsService.restoreUser(organization, id);
|
||||
}
|
||||
|
||||
async reinviteUser(id: string, organization: Organization): Promise<MemberActionResult> {
|
||||
return await this.memberActionsService.reinviteUser(organization, id);
|
||||
}
|
||||
|
||||
async confirmUser(
|
||||
user: OrganizationUserView,
|
||||
publicKey: Uint8Array,
|
||||
organization: Organization,
|
||||
): Promise<MemberActionResult> {
|
||||
return await this.memberActionsService.confirmUser(user, publicKey, organization);
|
||||
}
|
||||
|
||||
async revoke(user: OrganizationUserView, organization: Organization) {
|
||||
const confirmed = await this.revokeUserConfirmationDialog(user);
|
||||
async remove(user: OrganizationUserView, organization: Organization) {
|
||||
const confirmed = await this.memberDialogManager.openRemoveUserConfirmationDialog(user);
|
||||
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.actionPromise = this.revokeUser(user.id, organization);
|
||||
try {
|
||||
const result = await this.actionPromise;
|
||||
if (result.success) {
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("revokedUserId", this.userNamePipe.transform(user)),
|
||||
});
|
||||
await this.load(organization);
|
||||
} else {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
} catch (e) {
|
||||
this.validationService.showError(e);
|
||||
const result = await this.memberActionsService.removeUser(organization, user.id);
|
||||
const sideEffect = () => this.dataSource().removeUser(user);
|
||||
await this.handleMemberActionResult(result, "removedUserId", user, sideEffect);
|
||||
}
|
||||
|
||||
async reinvite(user: OrganizationUserView, organization: Organization) {
|
||||
const result = await this.memberActionsService.reinviteUser(organization, user.id);
|
||||
await this.handleMemberActionResult(result, "hasBeenReinvited", user);
|
||||
}
|
||||
|
||||
async confirm(user: OrganizationUserView, organization: Organization) {
|
||||
const confirmUserSideEffect = () => {
|
||||
user.status = this.userStatusType.Confirmed;
|
||||
this.dataSource().replaceUser(user);
|
||||
};
|
||||
|
||||
const publicKeyResult = await this.memberActionsService.getPublicKeyForConfirm(user);
|
||||
|
||||
if (publicKeyResult == null) {
|
||||
this.logService.warning("Public key not found");
|
||||
return;
|
||||
}
|
||||
this.actionPromise = undefined;
|
||||
|
||||
const result = await this.memberActionsService.confirmUser(user, publicKeyResult, organization);
|
||||
await this.handleMemberActionResult(result, "hasBeenConfirmed", user, confirmUserSideEffect);
|
||||
}
|
||||
|
||||
async revoke(user: OrganizationUserView, organization: Organization) {
|
||||
const confirmed = await this.memberDialogManager.openRevokeUserConfirmationDialog(user);
|
||||
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const result = await this.memberActionsService.revokeUser(organization, user.id);
|
||||
const sideEffect = async () => await this.load(organization);
|
||||
await this.handleMemberActionResult(result, "revokedUserId", user, sideEffect);
|
||||
}
|
||||
|
||||
async restore(user: OrganizationUserView, organization: Organization) {
|
||||
this.actionPromise = this.restoreUser(user.id, organization);
|
||||
try {
|
||||
const result = await this.actionPromise;
|
||||
if (result.success) {
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("restoredUserId", this.userNamePipe.transform(user)),
|
||||
});
|
||||
await this.load(organization);
|
||||
} else {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
} catch (e) {
|
||||
this.validationService.showError(e);
|
||||
}
|
||||
this.actionPromise = undefined;
|
||||
const result = await this.memberActionsService.restoreUser(organization, user.id);
|
||||
const sideEffect = async () => await this.load(organization);
|
||||
await this.handleMemberActionResult(result, "restoredUserId", user, sideEffect);
|
||||
}
|
||||
|
||||
allowResetPassword(
|
||||
@@ -307,7 +298,7 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
}
|
||||
|
||||
showEnrolledStatus(
|
||||
orgUser: OrganizationUserUserDetailsResponse,
|
||||
orgUser: OrganizationUserView,
|
||||
organization: Organization,
|
||||
orgResetPasswordPolicyEnabled: boolean,
|
||||
): boolean {
|
||||
@@ -318,9 +309,15 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
);
|
||||
}
|
||||
|
||||
private async handleInviteDialog(organization: Organization) {
|
||||
async invite(organization: Organization) {
|
||||
const billingMetadata = await firstValueFrom(this.billingMetadata$);
|
||||
const allUserEmails = this.dataSource.data?.map((user) => user.email) ?? [];
|
||||
const seatLimitResult = this.billingConstraint.checkSeatLimit(organization, billingMetadata);
|
||||
|
||||
if (await this.billingConstraint.seatLimitReached(seatLimitResult, organization)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const allUserEmails = this.dataSource().data?.map((user) => user.email) ?? [];
|
||||
|
||||
const result = await this.memberDialogManager.openInviteDialog(
|
||||
organization,
|
||||
@@ -330,14 +327,6 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
|
||||
if (result === MemberDialogResult.Saved) {
|
||||
await this.load(organization);
|
||||
}
|
||||
}
|
||||
|
||||
async invite(organization: Organization) {
|
||||
const billingMetadata = await firstValueFrom(this.billingMetadata$);
|
||||
const seatLimitResult = this.billingConstraint.checkSeatLimit(organization, billingMetadata);
|
||||
if (!(await this.billingConstraint.seatLimitReached(seatLimitResult, organization))) {
|
||||
await this.handleInviteDialog(organization);
|
||||
this.organizationMetadataService.refreshMetadataCache();
|
||||
}
|
||||
}
|
||||
@@ -358,7 +347,7 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
|
||||
switch (result) {
|
||||
case MemberDialogResult.Deleted:
|
||||
this.dataSource.removeUser(user);
|
||||
this.dataSource().removeUser(user);
|
||||
break;
|
||||
case MemberDialogResult.Saved:
|
||||
case MemberDialogResult.Revoked:
|
||||
@@ -369,57 +358,30 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
}
|
||||
|
||||
async bulkRemove(organization: Organization) {
|
||||
if (this.actionPromise != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const users = this.dataSource.getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
|
||||
const users = this.dataSource().getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
await this.memberDialogManager.openBulkRemoveDialog(organization, users);
|
||||
this.organizationMetadataService.refreshMetadataCache();
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
async bulkDelete(organization: Organization) {
|
||||
if (this.actionPromise != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const users = this.dataSource.getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
|
||||
const users = this.dataSource().getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
await this.memberDialogManager.openBulkDeleteDialog(organization, users);
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
async bulkRevoke(organization: Organization) {
|
||||
await this.bulkRevokeOrRestore(true, organization);
|
||||
}
|
||||
|
||||
async bulkRestore(organization: Organization) {
|
||||
await this.bulkRevokeOrRestore(false, organization);
|
||||
}
|
||||
|
||||
async bulkRevokeOrRestore(isRevoking: boolean, organization: Organization) {
|
||||
if (this.actionPromise != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const users = this.dataSource.getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
|
||||
const users = this.dataSource().getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
await this.memberDialogManager.openBulkRestoreRevokeDialog(organization, users, isRevoking);
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
async bulkReinvite(organization: Organization) {
|
||||
if (this.actionPromise != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
let users: OrganizationUserView[];
|
||||
if (this.dataSource.isIncreasedBulkLimitEnabled()) {
|
||||
users = this.dataSource.getCheckedUsersInVisibleOrder();
|
||||
if (this.dataSource().isIncreasedBulkLimitEnabled()) {
|
||||
users = this.dataSource().getCheckedUsersInVisibleOrder();
|
||||
} else {
|
||||
users = this.dataSource.getCheckedUsers();
|
||||
users = this.dataSource().getCheckedUsers();
|
||||
}
|
||||
|
||||
const allInvitedUsers = users.filter((u) => u.status === OrganizationUserStatusType.Invited);
|
||||
@@ -429,8 +391,8 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
|
||||
// When feature flag is enabled, limit invited users and uncheck the excess
|
||||
let filteredUsers: OrganizationUserView[];
|
||||
if (this.dataSource.isIncreasedBulkLimitEnabled()) {
|
||||
filteredUsers = this.dataSource.limitAndUncheckExcess(
|
||||
if (this.dataSource().isIncreasedBulkLimitEnabled()) {
|
||||
filteredUsers = this.dataSource().limitAndUncheckExcess(
|
||||
allInvitedUsers,
|
||||
CloudBulkReinviteLimit,
|
||||
);
|
||||
@@ -447,70 +409,59 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.memberActionsService.bulkReinvite(
|
||||
organization,
|
||||
filteredUsers.map((user) => user.id as UserId),
|
||||
);
|
||||
const result = await this.memberActionsService.bulkReinvite(
|
||||
organization,
|
||||
filteredUsers.map((user) => user.id as UserId),
|
||||
);
|
||||
|
||||
if (!result.successful) {
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
// When feature flag is enabled, show toast instead of dialog
|
||||
if (this.dataSource.isIncreasedBulkLimitEnabled()) {
|
||||
const selectedCount = originalInvitedCount;
|
||||
const invitedCount = filteredUsers.length;
|
||||
|
||||
if (selectedCount > CloudBulkReinviteLimit) {
|
||||
const excludedCount = selectedCount - CloudBulkReinviteLimit;
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t(
|
||||
"bulkReinviteLimitedSuccessToast",
|
||||
CloudBulkReinviteLimit.toLocaleString(),
|
||||
selectedCount.toLocaleString(),
|
||||
excludedCount.toLocaleString(),
|
||||
),
|
||||
});
|
||||
} else {
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("bulkReinviteSuccessToast", invitedCount.toString()),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Feature flag disabled - show legacy dialog
|
||||
await this.memberDialogManager.openBulkStatusDialog(
|
||||
users,
|
||||
filteredUsers,
|
||||
Promise.resolve(result.successful),
|
||||
this.i18nService.t("bulkReinviteMessage"),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
this.validationService.showError(e);
|
||||
if (!result.successful) {
|
||||
this.validationService.showError(result.failed);
|
||||
}
|
||||
|
||||
// When feature flag is enabled, show toast instead of dialog
|
||||
if (this.dataSource().isIncreasedBulkLimitEnabled()) {
|
||||
const selectedCount = originalInvitedCount;
|
||||
const invitedCount = filteredUsers.length;
|
||||
|
||||
if (selectedCount > CloudBulkReinviteLimit) {
|
||||
const excludedCount = selectedCount - CloudBulkReinviteLimit;
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t(
|
||||
"bulkReinviteLimitedSuccessToast",
|
||||
CloudBulkReinviteLimit.toLocaleString(),
|
||||
selectedCount.toLocaleString(),
|
||||
excludedCount.toLocaleString(),
|
||||
),
|
||||
});
|
||||
} else {
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("bulkReinviteSuccessToast", invitedCount.toString()),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Feature flag disabled - show legacy dialog
|
||||
await this.memberDialogManager.openBulkStatusDialog(
|
||||
users,
|
||||
filteredUsers,
|
||||
Promise.resolve(result.successful),
|
||||
this.i18nService.t("bulkReinviteMessage"),
|
||||
);
|
||||
}
|
||||
this.actionPromise = undefined;
|
||||
}
|
||||
|
||||
async bulkConfirm(organization: Organization) {
|
||||
if (this.actionPromise != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const users = this.dataSource.getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
|
||||
const users = this.dataSource().getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
await this.memberDialogManager.openBulkConfirmDialog(organization, users);
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
async bulkEnableSM(organization: Organization) {
|
||||
const users = this.dataSource.getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
|
||||
const users = this.dataSource().getCheckedUsersWithLimit(MaxCheckedCount);
|
||||
await this.memberDialogManager.openBulkEnableSecretsManagerDialog(organization, users);
|
||||
|
||||
this.dataSource.uncheckAllUsers();
|
||||
this.dataSource().uncheckAllUsers();
|
||||
await this.load(organization);
|
||||
}
|
||||
|
||||
@@ -538,14 +489,6 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
return;
|
||||
}
|
||||
|
||||
protected async removeUserConfirmationDialog(user: OrganizationUserView) {
|
||||
return await this.memberDialogManager.openRemoveUserConfirmationDialog(user);
|
||||
}
|
||||
|
||||
protected async revokeUserConfirmationDialog(user: OrganizationUserView) {
|
||||
return await this.memberDialogManager.openRevokeUserConfirmationDialog(user);
|
||||
}
|
||||
|
||||
async deleteUser(user: OrganizationUserView, organization: Organization) {
|
||||
const confirmed = await this.memberDialogManager.openDeleteUserConfirmationDialog(
|
||||
user,
|
||||
@@ -556,80 +499,72 @@ export class MembersComponent extends BaseMembersComponent<OrganizationUserView>
|
||||
return false;
|
||||
}
|
||||
|
||||
this.actionPromise = this.memberActionsService.deleteUser(organization, user.id);
|
||||
try {
|
||||
const result = await this.actionPromise;
|
||||
if (!result.success) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
const result = await this.memberActionsService.deleteUser(organization, user.id);
|
||||
await this.handleMemberActionResult(result, "organizationUserDeleted", user, () => {
|
||||
this.dataSource().removeUser(user);
|
||||
});
|
||||
}
|
||||
|
||||
async handleMemberActionResult(
|
||||
result: MemberActionResult,
|
||||
successKey: string,
|
||||
user: OrganizationUserView,
|
||||
sideEffect?: () => void | Promise<void>,
|
||||
) {
|
||||
if (result.error != null) {
|
||||
this.toastService.showToast({
|
||||
variant: "error",
|
||||
message: this.i18nService.t(result.error),
|
||||
});
|
||||
this.logService.error(result.error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.success) {
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("organizationUserDeleted", this.userNamePipe.transform(user)),
|
||||
message: this.i18nService.t(successKey, this.userNamePipe.transform(user)),
|
||||
});
|
||||
this.dataSource.removeUser(user);
|
||||
} catch (e) {
|
||||
this.validationService.showError(e);
|
||||
|
||||
if (sideEffect) {
|
||||
await sideEffect();
|
||||
}
|
||||
}
|
||||
this.actionPromise = undefined;
|
||||
}
|
||||
|
||||
get showBulkRestoreUsers(): boolean {
|
||||
return this.dataSource
|
||||
.getCheckedUsers()
|
||||
.every((member) => member.status == this.userStatusType.Revoked);
|
||||
}
|
||||
|
||||
get showBulkRevokeUsers(): boolean {
|
||||
return this.dataSource
|
||||
.getCheckedUsers()
|
||||
.every((member) => member.status != this.userStatusType.Revoked);
|
||||
}
|
||||
|
||||
get showBulkRemoveUsers(): boolean {
|
||||
return this.dataSource.getCheckedUsers().every((member) => !member.managedByOrganization);
|
||||
}
|
||||
|
||||
get showBulkDeleteUsers(): boolean {
|
||||
private bulkMenuOptions(members: OrganizationUserView[]): BulkMemberFlags {
|
||||
const validStatuses = [
|
||||
this.userStatusType.Accepted,
|
||||
this.userStatusType.Confirmed,
|
||||
this.userStatusType.Revoked,
|
||||
OrganizationUserStatusType.Accepted,
|
||||
OrganizationUserStatusType.Confirmed,
|
||||
OrganizationUserStatusType.Revoked,
|
||||
];
|
||||
|
||||
return this.dataSource
|
||||
.getCheckedUsers()
|
||||
.every((member) => member.managedByOrganization && validStatuses.includes(member.status));
|
||||
const result = {
|
||||
showBulkConfirmUsers: members.every((m) => m.status == OrganizationUserStatusType.Accepted),
|
||||
showBulkReinviteUsers: members.every((m) => m.status == OrganizationUserStatusType.Invited),
|
||||
showBulkRestoreUsers: members.every((m) => m.status == OrganizationUserStatusType.Revoked),
|
||||
showBulkRevokeUsers: members.every((m) => m.status != OrganizationUserStatusType.Revoked),
|
||||
showBulkRemoveUsers: members.every((m) => !m.managedByOrganization),
|
||||
showBulkDeleteUsers: members.every(
|
||||
(m) => m.managedByOrganization && validStatuses.includes(m.status),
|
||||
),
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
exportMembers = async (): Promise<void> => {
|
||||
try {
|
||||
const members = this.dataSource.data;
|
||||
if (!members || members.length === 0) {
|
||||
this.toastService.showToast({
|
||||
variant: "error",
|
||||
title: this.i18nService.t("errorOccurred"),
|
||||
message: this.i18nService.t("noMembersToExport"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const csvData = this.memberExportService.getMemberExport(members);
|
||||
const fileName = this.memberExportService.getFileName("org-members");
|
||||
|
||||
this.fileDownloadService.download({
|
||||
fileName: fileName,
|
||||
blobData: csvData,
|
||||
blobOptions: { type: "text/plain" },
|
||||
});
|
||||
|
||||
exportMembers = () => {
|
||||
const result = this.memberExportService.getMemberExport(this.dataSource().data);
|
||||
if (result.success) {
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
title: undefined,
|
||||
message: this.i18nService.t("dataExportSuccess"),
|
||||
});
|
||||
} catch (e) {
|
||||
this.validationService.showError(e);
|
||||
this.logService.error(`Failed to export members: ${e}`);
|
||||
}
|
||||
|
||||
if (result.error != null) {
|
||||
this.validationService.showError(result.error.message);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,8 +17,9 @@ import { BulkRemoveDialogComponent } from "./components/bulk/bulk-remove-dialog.
|
||||
import { BulkRestoreRevokeComponent } from "./components/bulk/bulk-restore-revoke.component";
|
||||
import { BulkStatusComponent } from "./components/bulk/bulk-status.component";
|
||||
import { UserDialogModule } from "./components/member-dialog";
|
||||
import { MembersComponent } from "./deprecated_members.component";
|
||||
import { MembersRoutingModule } from "./members-routing.module";
|
||||
import { MembersComponent } from "./members.component";
|
||||
import { vNextMembersComponent } from "./members.component";
|
||||
import { UserStatusPipe } from "./pipes";
|
||||
import {
|
||||
OrganizationMembersService,
|
||||
@@ -46,6 +47,7 @@ import {
|
||||
BulkRestoreRevokeComponent,
|
||||
BulkStatusComponent,
|
||||
MembersComponent,
|
||||
vNextMembersComponent,
|
||||
BulkDeleteDialogComponent,
|
||||
UserStatusPipe,
|
||||
],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { TestBed } from "@angular/core/testing";
|
||||
import { MockProxy, mock } from "jest-mock-extended";
|
||||
import { of } from "rxjs";
|
||||
|
||||
@@ -6,6 +7,9 @@ import {
|
||||
OrganizationUserBulkResponse,
|
||||
OrganizationUserService,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { UserNamePipe } from "@bitwarden/angular/pipes/user-name.pipe";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { OrganizationManagementPreferencesService } from "@bitwarden/common/admin-console/abstractions/organization-management-preferences/organization-management-preferences.service";
|
||||
import {
|
||||
OrganizationUserType,
|
||||
OrganizationUserStatusType,
|
||||
@@ -14,8 +18,11 @@ import { Organization } from "@bitwarden/common/admin-console/models/domain/orga
|
||||
import { OrganizationMetadataServiceAbstraction } from "@bitwarden/common/billing/abstractions/organization-metadata.service.abstraction";
|
||||
import { ListResponse } from "@bitwarden/common/models/response/list.response";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { OrganizationId, UserId } from "@bitwarden/common/types/guid";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { newGuid } from "@bitwarden/guid";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
|
||||
import { OrganizationUserView } from "../../../core/views/organization-user.view";
|
||||
|
||||
@@ -56,12 +63,29 @@ describe("MemberActionsService", () => {
|
||||
resetPasswordEnrolled: true,
|
||||
} as OrganizationUserView;
|
||||
|
||||
service = new MemberActionsService(
|
||||
organizationUserApiService,
|
||||
organizationUserService,
|
||||
configService,
|
||||
organizationMetadataService,
|
||||
);
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
MemberActionsService,
|
||||
{ provide: OrganizationUserApiService, useValue: organizationUserApiService },
|
||||
{ provide: OrganizationUserService, useValue: organizationUserService },
|
||||
{ provide: ConfigService, useValue: configService },
|
||||
{
|
||||
provide: OrganizationMetadataServiceAbstraction,
|
||||
useValue: organizationMetadataService,
|
||||
},
|
||||
{ provide: ApiService, useValue: mock<ApiService>() },
|
||||
{ provide: DialogService, useValue: mock<DialogService>() },
|
||||
{ provide: KeyService, useValue: mock<KeyService>() },
|
||||
{ provide: LogService, useValue: mock<LogService>() },
|
||||
{
|
||||
provide: OrganizationManagementPreferencesService,
|
||||
useValue: mock<OrganizationManagementPreferencesService>(),
|
||||
},
|
||||
{ provide: UserNamePipe, useValue: mock<UserNamePipe>() },
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(MemberActionsService);
|
||||
});
|
||||
|
||||
describe("inviteUser", () => {
|
||||
@@ -660,4 +684,26 @@ describe("MemberActionsService", () => {
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isProcessing signal", () => {
|
||||
it("should be false initially", () => {
|
||||
expect(service.isProcessing()).toBe(false);
|
||||
});
|
||||
|
||||
it("should be false after operation completes successfully", async () => {
|
||||
organizationUserApiService.removeOrganizationUser.mockResolvedValue(undefined);
|
||||
|
||||
await service.removeUser(mockOrganization, userIdToManage);
|
||||
|
||||
expect(service.isProcessing()).toBe(false);
|
||||
});
|
||||
|
||||
it("should be false after operation fails", async () => {
|
||||
organizationUserApiService.removeOrganizationUser.mockRejectedValue(new Error("Failed"));
|
||||
|
||||
await service.removeUser(mockOrganization, userIdToManage);
|
||||
|
||||
expect(service.isProcessing()).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,23 +1,33 @@
|
||||
import { Injectable } from "@angular/core";
|
||||
import { firstValueFrom } from "rxjs";
|
||||
import { inject, Injectable, signal } from "@angular/core";
|
||||
import { lastValueFrom, firstValueFrom } from "rxjs";
|
||||
|
||||
import {
|
||||
OrganizationUserApiService,
|
||||
OrganizationUserBulkResponse,
|
||||
OrganizationUserService,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { UserNamePipe } from "@bitwarden/angular/pipes/user-name.pipe";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { OrganizationManagementPreferencesService } from "@bitwarden/common/admin-console/abstractions/organization-management-preferences/organization-management-preferences.service";
|
||||
import {
|
||||
OrganizationUserType,
|
||||
OrganizationUserStatusType,
|
||||
} from "@bitwarden/common/admin-console/enums";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { assertNonNullish } from "@bitwarden/common/auth/utils";
|
||||
import { OrganizationMetadataServiceAbstraction } from "@bitwarden/common/billing/abstractions/organization-metadata.service.abstraction";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ListResponse } from "@bitwarden/common/models/response/list.response";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
import { UserId } from "@bitwarden/user-core";
|
||||
import { ProviderUser } from "@bitwarden/web-vault/app/admin-console/common/people-table-data-source";
|
||||
|
||||
import { OrganizationUserView } from "../../../core/views/organization-user.view";
|
||||
import { UserConfirmComponent } from "../../../manage/user-confirm.component";
|
||||
|
||||
export const REQUESTS_PER_BATCH = 500;
|
||||
|
||||
@@ -33,12 +43,26 @@ export interface BulkActionResult {
|
||||
|
||||
@Injectable()
|
||||
export class MemberActionsService {
|
||||
constructor(
|
||||
private organizationUserApiService: OrganizationUserApiService,
|
||||
private organizationUserService: OrganizationUserService,
|
||||
private configService: ConfigService,
|
||||
private organizationMetadataService: OrganizationMetadataServiceAbstraction,
|
||||
) {}
|
||||
private organizationUserApiService = inject(OrganizationUserApiService);
|
||||
private organizationUserService = inject(OrganizationUserService);
|
||||
private configService = inject(ConfigService);
|
||||
private organizationMetadataService = inject(OrganizationMetadataServiceAbstraction);
|
||||
private apiService = inject(ApiService);
|
||||
private dialogService = inject(DialogService);
|
||||
private keyService = inject(KeyService);
|
||||
private logService = inject(LogService);
|
||||
private orgManagementPrefs = inject(OrganizationManagementPreferencesService);
|
||||
private userNamePipe = inject(UserNamePipe);
|
||||
|
||||
readonly isProcessing = signal(false);
|
||||
|
||||
private startProcessing(): void {
|
||||
this.isProcessing.set(true);
|
||||
}
|
||||
|
||||
private endProcessing(): void {
|
||||
this.isProcessing.set(false);
|
||||
}
|
||||
|
||||
async inviteUser(
|
||||
organization: Organization,
|
||||
@@ -48,6 +72,7 @@ export class MemberActionsService {
|
||||
collections?: any[],
|
||||
groups?: string[],
|
||||
): Promise<MemberActionResult> {
|
||||
this.startProcessing();
|
||||
try {
|
||||
await this.organizationUserApiService.postOrganizationUserInvite(organization.id, {
|
||||
emails: [email],
|
||||
@@ -60,55 +85,72 @@ export class MemberActionsService {
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message ?? String(error) };
|
||||
} finally {
|
||||
this.endProcessing();
|
||||
}
|
||||
}
|
||||
|
||||
async removeUser(organization: Organization, userId: string): Promise<MemberActionResult> {
|
||||
this.startProcessing();
|
||||
try {
|
||||
await this.organizationUserApiService.removeOrganizationUser(organization.id, userId);
|
||||
this.organizationMetadataService.refreshMetadataCache();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message ?? String(error) };
|
||||
} finally {
|
||||
this.endProcessing();
|
||||
}
|
||||
}
|
||||
|
||||
async revokeUser(organization: Organization, userId: string): Promise<MemberActionResult> {
|
||||
this.startProcessing();
|
||||
try {
|
||||
await this.organizationUserApiService.revokeOrganizationUser(organization.id, userId);
|
||||
this.organizationMetadataService.refreshMetadataCache();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message ?? String(error) };
|
||||
} finally {
|
||||
this.endProcessing();
|
||||
}
|
||||
}
|
||||
|
||||
async restoreUser(organization: Organization, userId: string): Promise<MemberActionResult> {
|
||||
this.startProcessing();
|
||||
try {
|
||||
await this.organizationUserApiService.restoreOrganizationUser(organization.id, userId);
|
||||
this.organizationMetadataService.refreshMetadataCache();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message ?? String(error) };
|
||||
} finally {
|
||||
this.endProcessing();
|
||||
}
|
||||
}
|
||||
|
||||
async deleteUser(organization: Organization, userId: string): Promise<MemberActionResult> {
|
||||
this.startProcessing();
|
||||
try {
|
||||
await this.organizationUserApiService.deleteOrganizationUser(organization.id, userId);
|
||||
this.organizationMetadataService.refreshMetadataCache();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message ?? String(error) };
|
||||
} finally {
|
||||
this.endProcessing();
|
||||
}
|
||||
}
|
||||
|
||||
async reinviteUser(organization: Organization, userId: string): Promise<MemberActionResult> {
|
||||
this.startProcessing();
|
||||
try {
|
||||
await this.organizationUserApiService.postOrganizationUserReinvite(organization.id, userId);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message ?? String(error) };
|
||||
} finally {
|
||||
this.endProcessing();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +159,7 @@ export class MemberActionsService {
|
||||
publicKey: Uint8Array,
|
||||
organization: Organization,
|
||||
): Promise<MemberActionResult> {
|
||||
this.startProcessing();
|
||||
try {
|
||||
await firstValueFrom(
|
||||
this.organizationUserService.confirmUser(organization, user.id, publicKey),
|
||||
@@ -124,27 +167,32 @@ export class MemberActionsService {
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: (error as Error).message ?? String(error) };
|
||||
} finally {
|
||||
this.endProcessing();
|
||||
}
|
||||
}
|
||||
|
||||
async bulkReinvite(organization: Organization, userIds: UserId[]): Promise<BulkActionResult> {
|
||||
const increaseBulkReinviteLimitForCloud = await firstValueFrom(
|
||||
this.configService.getFeatureFlag$(FeatureFlag.IncreaseBulkReinviteLimitForCloud),
|
||||
);
|
||||
if (increaseBulkReinviteLimitForCloud) {
|
||||
return await this.vNextBulkReinvite(organization, userIds);
|
||||
} else {
|
||||
try {
|
||||
this.startProcessing();
|
||||
try {
|
||||
const increaseBulkReinviteLimitForCloud = await firstValueFrom(
|
||||
this.configService.getFeatureFlag$(FeatureFlag.IncreaseBulkReinviteLimitForCloud),
|
||||
);
|
||||
if (increaseBulkReinviteLimitForCloud) {
|
||||
return await this.vNextBulkReinvite(organization, userIds);
|
||||
} else {
|
||||
const result = await this.organizationUserApiService.postManyOrganizationUserReinvite(
|
||||
organization.id,
|
||||
userIds,
|
||||
);
|
||||
return { successful: result, failed: [] };
|
||||
} catch (error) {
|
||||
return {
|
||||
failed: userIds.map((id) => ({ id, error: (error as Error).message ?? String(error) })),
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
return {
|
||||
failed: userIds.map((id) => ({ id, error: (error as Error).message ?? String(error) })),
|
||||
};
|
||||
} finally {
|
||||
this.endProcessing();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,4 +284,50 @@ export class MemberActionsService {
|
||||
failed: allFailed,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared dialog workflow that returns the public key when the user accepts the selected confirmation
|
||||
* action.
|
||||
*
|
||||
* @param user - The user to confirm (must implement ConfirmableUser interface)
|
||||
* @param userNamePipe - Pipe to transform user names for display
|
||||
* @param orgManagementPrefs - Service providing organization management preferences
|
||||
* @returns Promise containing the pulic key that resolves when the confirm action is accepted
|
||||
* or undefined when cancelled
|
||||
*/
|
||||
async getPublicKeyForConfirm(
|
||||
user: OrganizationUserView | ProviderUser,
|
||||
): Promise<Uint8Array | undefined> {
|
||||
try {
|
||||
assertNonNullish(user, "Cannot confirm null user.");
|
||||
|
||||
const autoConfirmFingerPrint = await firstValueFrom(
|
||||
this.orgManagementPrefs.autoConfirmFingerPrints.state$,
|
||||
);
|
||||
|
||||
const publicKeyResponse = await this.apiService.getUserPublicKey(user.userId);
|
||||
const publicKey = Utils.fromB64ToArray(publicKeyResponse.publicKey);
|
||||
|
||||
if (autoConfirmFingerPrint == null || !autoConfirmFingerPrint) {
|
||||
const fingerprint = await this.keyService.getFingerprint(user.userId, publicKey);
|
||||
this.logService.info(`User's fingerprint: ${fingerprint.join("-")}`);
|
||||
|
||||
const confirmed = UserConfirmComponent.open(this.dialogService, {
|
||||
data: {
|
||||
name: this.userNamePipe.transform(user),
|
||||
userId: user.userId,
|
||||
publicKey: publicKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (!(await lastValueFrom(confirmed.closed))) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
return publicKey;
|
||||
} catch (e) {
|
||||
this.logService.error(`Handled exception: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
OrganizationUserStatusType,
|
||||
OrganizationUserType,
|
||||
} from "@bitwarden/common/admin-console/enums";
|
||||
import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { LogService } from "@bitwarden/logging";
|
||||
|
||||
import { OrganizationUserView } from "../../../core";
|
||||
import { UserStatusPipe } from "../../pipes";
|
||||
@@ -16,9 +18,13 @@ import { MemberExportService } from "./member-export.service";
|
||||
describe("MemberExportService", () => {
|
||||
let service: MemberExportService;
|
||||
let i18nService: MockProxy<I18nService>;
|
||||
let fileDownloadService: MockProxy<FileDownloadService>;
|
||||
let logService: MockProxy<LogService>;
|
||||
|
||||
beforeEach(() => {
|
||||
i18nService = mock<I18nService>();
|
||||
fileDownloadService = mock<FileDownloadService>();
|
||||
logService = mock<LogService>();
|
||||
|
||||
// Setup common i18n translations
|
||||
i18nService.t.mockImplementation((key: string) => {
|
||||
@@ -44,9 +50,12 @@ describe("MemberExportService", () => {
|
||||
custom: "Custom",
|
||||
// Boolean states
|
||||
enabled: "Enabled",
|
||||
optionEnabled: "Enabled",
|
||||
disabled: "Disabled",
|
||||
enrolled: "Enrolled",
|
||||
notEnrolled: "Not Enrolled",
|
||||
// Error messages
|
||||
noMembersToExport: "No members to export",
|
||||
};
|
||||
return translations[key] || key;
|
||||
});
|
||||
@@ -54,6 +63,8 @@ describe("MemberExportService", () => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
MemberExportService,
|
||||
{ provide: FileDownloadService, useValue: fileDownloadService },
|
||||
{ provide: LogService, useValue: logService },
|
||||
{ provide: I18nService, useValue: i18nService },
|
||||
UserTypePipe,
|
||||
UserStatusPipe,
|
||||
@@ -88,8 +99,18 @@ describe("MemberExportService", () => {
|
||||
} as OrganizationUserView,
|
||||
];
|
||||
|
||||
const csvData = service.getMemberExport(members);
|
||||
const result = service.getMemberExport(members);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(fileDownloadService.download).toHaveBeenCalledTimes(1);
|
||||
|
||||
const downloadCall = fileDownloadService.download.mock.calls[0][0];
|
||||
expect(downloadCall.fileName).toContain("org-members");
|
||||
expect(downloadCall.fileName).toContain(".csv");
|
||||
expect(downloadCall.blobOptions).toEqual({ type: "text/plain" });
|
||||
|
||||
const csvData = downloadCall.blobData as string;
|
||||
expect(csvData).toContain("Email,Name,Status,Role,Two-step Login,Account Recovery");
|
||||
expect(csvData).toContain("user1@example.com");
|
||||
expect(csvData).toContain("User One");
|
||||
@@ -114,8 +135,12 @@ describe("MemberExportService", () => {
|
||||
} as OrganizationUserView,
|
||||
];
|
||||
|
||||
const csvData = service.getMemberExport(members);
|
||||
const result = service.getMemberExport(members);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(fileDownloadService.download).toHaveBeenCalled();
|
||||
|
||||
const csvData = fileDownloadService.download.mock.calls[0][0].blobData as string;
|
||||
expect(csvData).toContain("user@example.com");
|
||||
// Empty name is represented as an empty field in CSV
|
||||
expect(csvData).toContain("user@example.com,,Confirmed");
|
||||
@@ -135,17 +160,23 @@ describe("MemberExportService", () => {
|
||||
} as OrganizationUserView,
|
||||
];
|
||||
|
||||
const csvData = service.getMemberExport(members);
|
||||
const result = service.getMemberExport(members);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(fileDownloadService.download).toHaveBeenCalled();
|
||||
|
||||
const csvData = fileDownloadService.download.mock.calls[0][0].blobData as string;
|
||||
expect(csvData).toContain("user@example.com");
|
||||
expect(csvData).toBeDefined();
|
||||
});
|
||||
|
||||
it("should handle empty members array", () => {
|
||||
const csvData = service.getMemberExport([]);
|
||||
const result = service.getMemberExport([]);
|
||||
|
||||
// When array is empty, papaparse returns an empty string
|
||||
expect(csvData).toBe("");
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBeDefined();
|
||||
expect(result.error?.message).toBe("No members to export");
|
||||
expect(fileDownloadService.download).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,9 @@ import { inject, Injectable } from "@angular/core";
|
||||
import * as papa from "papaparse";
|
||||
|
||||
import { UserTypePipe } from "@bitwarden/angular/pipes/user-type.pipe";
|
||||
import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { ExportHelper } from "@bitwarden/vault-export-core";
|
||||
|
||||
import { OrganizationUserView } from "../../../core";
|
||||
@@ -10,40 +12,71 @@ import { UserStatusPipe } from "../../pipes";
|
||||
|
||||
import { MemberExport } from "./member.export";
|
||||
|
||||
export interface MemberExportResult {
|
||||
success: boolean;
|
||||
error?: { message: string };
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class MemberExportService {
|
||||
private i18nService = inject(I18nService);
|
||||
private userTypePipe = inject(UserTypePipe);
|
||||
private userStatusPipe = inject(UserStatusPipe);
|
||||
private fileDownloadService = inject(FileDownloadService);
|
||||
private logService = inject(LogService);
|
||||
|
||||
getMemberExport(members: OrganizationUserView[]): string {
|
||||
const exportData = members.map((m) =>
|
||||
MemberExport.fromOrganizationUserView(
|
||||
this.i18nService,
|
||||
this.userTypePipe,
|
||||
this.userStatusPipe,
|
||||
m,
|
||||
),
|
||||
);
|
||||
getMemberExport(data: OrganizationUserView[]): MemberExportResult {
|
||||
try {
|
||||
const members = data;
|
||||
if (!members || members.length === 0) {
|
||||
return { success: false, error: { message: this.i18nService.t("noMembersToExport") } };
|
||||
}
|
||||
|
||||
const headers: string[] = [
|
||||
this.i18nService.t("email"),
|
||||
this.i18nService.t("name"),
|
||||
this.i18nService.t("status"),
|
||||
this.i18nService.t("role"),
|
||||
this.i18nService.t("twoStepLogin"),
|
||||
this.i18nService.t("accountRecovery"),
|
||||
this.i18nService.t("secretsManager"),
|
||||
this.i18nService.t("groups"),
|
||||
];
|
||||
const exportData = members.map((m) =>
|
||||
MemberExport.fromOrganizationUserView(
|
||||
this.i18nService,
|
||||
this.userTypePipe,
|
||||
this.userStatusPipe,
|
||||
m,
|
||||
),
|
||||
);
|
||||
|
||||
return papa.unparse(exportData, {
|
||||
columns: headers,
|
||||
header: true,
|
||||
});
|
||||
const headers: string[] = [
|
||||
this.i18nService.t("email"),
|
||||
this.i18nService.t("name"),
|
||||
this.i18nService.t("status"),
|
||||
this.i18nService.t("role"),
|
||||
this.i18nService.t("twoStepLogin"),
|
||||
this.i18nService.t("accountRecovery"),
|
||||
this.i18nService.t("secretsManager"),
|
||||
this.i18nService.t("groups"),
|
||||
];
|
||||
|
||||
const csvData = papa.unparse(exportData, {
|
||||
columns: headers,
|
||||
header: true,
|
||||
});
|
||||
|
||||
const fileName = this.getFileName("org-members");
|
||||
|
||||
this.fileDownloadService.download({
|
||||
fileName: fileName,
|
||||
blobData: csvData,
|
||||
blobOptions: { type: "text/plain" },
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
this.logService.error(`Failed to export members: ${error}`);
|
||||
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : this.i18nService.t("unexpectedError");
|
||||
|
||||
return { success: false, error: { message: errorMessage } };
|
||||
}
|
||||
}
|
||||
|
||||
getFileName(prefix: string | null = null, extension = "csv"): string {
|
||||
private getFileName(prefix: string | null = null, extension = "csv"): string {
|
||||
return ExportHelper.getFileName(prefix ?? "", extension);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { Injectable } from "@angular/core";
|
||||
import { combineLatest, firstValueFrom, from, map, switchMap } from "rxjs";
|
||||
|
||||
import { CollectionService, OrganizationUserApiService } from "@bitwarden/admin-console/common";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import {
|
||||
CollectionDetailsResponse,
|
||||
Collection,
|
||||
CollectionData,
|
||||
CollectionDetailsResponse,
|
||||
CollectionService,
|
||||
OrganizationUserApiService,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
} from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
|
||||
@@ -2,6 +2,6 @@ export { PoliciesComponent } from "./policies.component";
|
||||
export { ossPolicyEditRegister } from "./policy-edit-register";
|
||||
export { BasePolicyEditDefinition, BasePolicyEditComponent } from "./base-policy-edit.component";
|
||||
export { POLICY_EDIT_REGISTER } from "./policy-register-token";
|
||||
export { AutoConfirmPolicyDialogComponent } from "./auto-confirm-edit-policy-dialog.component";
|
||||
export { AutoConfirmPolicy } from "./policy-edit-definitions";
|
||||
export { PolicyEditDialogResult } from "./policy-edit-dialog.component";
|
||||
export * from "./policy-edit-dialogs";
|
||||
|
||||
@@ -15,8 +15,8 @@ import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import { AutoConfirmPolicyDialogComponent } from "../auto-confirm-edit-policy-dialog.component";
|
||||
import { BasePolicyEditDefinition, BasePolicyEditComponent } from "../base-policy-edit.component";
|
||||
import { AutoConfirmPolicyDialogComponent } from "../policy-edit-dialogs/auto-confirm-edit-policy-dialog.component";
|
||||
|
||||
export class AutoConfirmPolicy extends BasePolicyEditDefinition {
|
||||
name = "autoConfirm";
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
export { DisableSendPolicy } from "./disable-send.component";
|
||||
export { DesktopAutotypeDefaultSettingPolicy } from "./autotype-policy.component";
|
||||
export { MasterPasswordPolicy } from "./master-password.component";
|
||||
export { OrganizationDataOwnershipPolicy } from "./organization-data-ownership.component";
|
||||
export {
|
||||
OrganizationDataOwnershipPolicy,
|
||||
OrganizationDataOwnershipPolicyComponent,
|
||||
} from "./organization-data-ownership.component";
|
||||
export { PasswordGeneratorPolicy } from "./password-generator.component";
|
||||
export { RemoveUnlockWithPinPolicy } from "./remove-unlock-with-pin.component";
|
||||
export { RequireSsoPolicy } from "./require-sso.component";
|
||||
|
||||
@@ -1,8 +1,57 @@
|
||||
<bit-callout type="warning">
|
||||
{{ "personalOwnershipExemption" | i18n }}
|
||||
</bit-callout>
|
||||
<p>
|
||||
{{ "organizationDataOwnershipDescContent" | i18n }}
|
||||
<a
|
||||
bitLink
|
||||
href="https://bitwarden.com/resources/credential-lifecycle-management/"
|
||||
target="_blank"
|
||||
>
|
||||
{{ "organizationDataOwnershipContentAnchor" | i18n }}.
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<bit-form-control>
|
||||
<input type="checkbox" bitCheckbox [formControl]="enabled" id="enabled" />
|
||||
<bit-label>{{ "turnOn" | i18n }}</bit-label>
|
||||
</bit-form-control>
|
||||
|
||||
<ng-template #dialog>
|
||||
<bit-simple-dialog background="alt">
|
||||
<span bitDialogTitle>{{ "organizationDataOwnershipWarningTitle" | i18n }}</span>
|
||||
<ng-container bitDialogContent>
|
||||
<div class="tw-text-left tw-overflow-hidden">
|
||||
{{ "organizationDataOwnershipWarningContentTop" | i18n }}
|
||||
<div class="tw-flex tw-flex-col tw-p-2">
|
||||
<ul class="tw-list-disc tw-pl-5 tw-space-y-2 tw-break-words tw-mb-0">
|
||||
<li>
|
||||
{{ "organizationDataOwnershipWarning1" | i18n }}
|
||||
</li>
|
||||
<li>
|
||||
{{ "organizationDataOwnershipWarning2" | i18n }}
|
||||
</li>
|
||||
<li>
|
||||
{{ "organizationDataOwnershipWarning3" | i18n }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
{{ "organizationDataOwnershipWarningContentBottom" | i18n }}
|
||||
<a
|
||||
bitLink
|
||||
href="https://bitwarden.com/resources/credential-lifecycle-management/"
|
||||
target="_blank"
|
||||
>
|
||||
{{ "organizationDataOwnershipContentAnchor" | i18n }}.
|
||||
</a>
|
||||
</div>
|
||||
</ng-container>
|
||||
<ng-container bitDialogFooter>
|
||||
<span class="tw-flex tw-gap-2">
|
||||
<button bitButton buttonType="primary" [bitDialogClose]="true" type="submit">
|
||||
{{ "continue" | i18n }}
|
||||
</button>
|
||||
<button bitButton buttonType="secondary" [bitDialogClose]="false" type="button">
|
||||
{{ "cancel" | i18n }}
|
||||
</button>
|
||||
</span>
|
||||
</ng-container>
|
||||
</bit-simple-dialog>
|
||||
</ng-template>
|
||||
|
||||
@@ -1,22 +1,38 @@
|
||||
import { ChangeDetectionStrategy, Component } from "@angular/core";
|
||||
import { of, Observable } from "rxjs";
|
||||
import { ChangeDetectionStrategy, Component, OnInit, TemplateRef, ViewChild } from "@angular/core";
|
||||
import { lastValueFrom, map, Observable } from "rxjs";
|
||||
|
||||
import { PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { PolicyRequest } from "@bitwarden/common/admin-console/models/request/policy.request";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { EncryptService } from "@bitwarden/common/key-management/crypto/abstractions/encrypt.service";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { OrgKey } from "@bitwarden/common/types/key";
|
||||
import { CenterPositionStrategy, DialogService } from "@bitwarden/components";
|
||||
import { EncString } from "@bitwarden/sdk-internal";
|
||||
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import { BasePolicyEditDefinition, BasePolicyEditComponent } from "../base-policy-edit.component";
|
||||
|
||||
export interface VNextPolicyRequest {
|
||||
policy: PolicyRequest;
|
||||
metadata: {
|
||||
defaultUserCollectionName: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class OrganizationDataOwnershipPolicy extends BasePolicyEditDefinition {
|
||||
name = "organizationDataOwnership";
|
||||
description = "personalOwnershipPolicyDesc";
|
||||
description = "organizationDataOwnershipDesc";
|
||||
type = PolicyType.OrganizationDataOwnership;
|
||||
component = OrganizationDataOwnershipPolicyComponent;
|
||||
showDescription = false;
|
||||
|
||||
display$(organization: Organization, configService: ConfigService): Observable<boolean> {
|
||||
// TODO Remove this entire component upon verifying that it can be deleted due to its sole reliance of the CreateDefaultLocation feature flag
|
||||
return of(false);
|
||||
override display$(organization: Organization, configService: ConfigService): Observable<boolean> {
|
||||
return configService
|
||||
.getFeatureFlag$(FeatureFlag.MigrateMyVaultToMyItems)
|
||||
.pipe(map((enabled) => !enabled));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,4 +42,61 @@ export class OrganizationDataOwnershipPolicy extends BasePolicyEditDefinition {
|
||||
imports: [SharedModule],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
})
|
||||
export class OrganizationDataOwnershipPolicyComponent extends BasePolicyEditComponent {}
|
||||
export class OrganizationDataOwnershipPolicyComponent
|
||||
extends BasePolicyEditComponent
|
||||
implements OnInit
|
||||
{
|
||||
constructor(
|
||||
private dialogService: DialogService,
|
||||
private i18nService: I18nService,
|
||||
private encryptService: EncryptService,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-903): Migrate to Signals
|
||||
// eslint-disable-next-line @angular-eslint/prefer-signals
|
||||
@ViewChild("dialog", { static: true }) warningContent!: TemplateRef<unknown>;
|
||||
|
||||
override async confirm(): Promise<boolean> {
|
||||
if (this.policyResponse?.enabled && !this.enabled.value) {
|
||||
const dialogRef = this.dialogService.open(this.warningContent, {
|
||||
positionStrategy: new CenterPositionStrategy(),
|
||||
});
|
||||
const result = await lastValueFrom(dialogRef.closed);
|
||||
return Boolean(result);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async buildVNextRequest(orgKey: OrgKey): Promise<VNextPolicyRequest> {
|
||||
if (!this.policy) {
|
||||
throw new Error("Policy was not found");
|
||||
}
|
||||
|
||||
const defaultUserCollectionName = await this.getEncryptedDefaultUserCollectionName(orgKey);
|
||||
|
||||
const request: VNextPolicyRequest = {
|
||||
policy: {
|
||||
enabled: this.enabled.value ?? false,
|
||||
data: this.buildRequestData(),
|
||||
},
|
||||
metadata: {
|
||||
defaultUserCollectionName,
|
||||
},
|
||||
};
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
private async getEncryptedDefaultUserCollectionName(orgKey: OrgKey): Promise<EncString> {
|
||||
const defaultCollectionName = this.i18nService.t("myItems");
|
||||
const encrypted = await this.encryptService.encryptString(defaultCollectionName, orgKey);
|
||||
|
||||
if (!encrypted.encryptedString) {
|
||||
throw new Error("Encryption error");
|
||||
}
|
||||
|
||||
return encrypted.encryptedString;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,57 +1,52 @@
|
||||
<p>
|
||||
{{ "organizationDataOwnershipDescContent" | i18n }}
|
||||
<a
|
||||
bitLink
|
||||
href="https://bitwarden.com/resources/credential-lifecycle-management/"
|
||||
target="_blank"
|
||||
>
|
||||
{{ "organizationDataOwnershipContentAnchor" | i18n }}.
|
||||
</a>
|
||||
</p>
|
||||
<ng-container [ngTemplateOutlet]="steps[step()]()"></ng-container>
|
||||
|
||||
<bit-form-control>
|
||||
<input type="checkbox" bitCheckbox [formControl]="enabled" id="enabled" />
|
||||
<bit-label>{{ "turnOn" | i18n }}</bit-label>
|
||||
</bit-form-control>
|
||||
<ng-template #step0>
|
||||
<p>
|
||||
{{ "centralizeDataOwnershipDesc" | i18n }}
|
||||
<a
|
||||
bitLink
|
||||
href="https://bitwarden.com/resources/credential-lifecycle-management/"
|
||||
target="_blank"
|
||||
>
|
||||
{{ "centralizeDataOwnershipContentAnchor" | i18n }}
|
||||
<i class="bwi bwi-external-link"></i>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<ng-template #dialog>
|
||||
<bit-simple-dialog background="alt">
|
||||
<span bitDialogTitle>{{ "organizationDataOwnershipWarningTitle" | i18n }}</span>
|
||||
<ng-container bitDialogContent>
|
||||
<div class="tw-text-left tw-overflow-hidden">
|
||||
{{ "organizationDataOwnershipWarningContentTop" | i18n }}
|
||||
<div class="tw-flex tw-flex-col tw-p-2">
|
||||
<ul class="tw-list-disc tw-pl-5 tw-space-y-2 tw-break-words tw-mb-0">
|
||||
<li>
|
||||
{{ "organizationDataOwnershipWarning1" | i18n }}
|
||||
</li>
|
||||
<li>
|
||||
{{ "organizationDataOwnershipWarning2" | i18n }}
|
||||
</li>
|
||||
<li>
|
||||
{{ "organizationDataOwnershipWarning3" | i18n }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
{{ "organizationDataOwnershipWarningContentBottom" | i18n }}
|
||||
<a
|
||||
bitLink
|
||||
href="https://bitwarden.com/resources/credential-lifecycle-management/"
|
||||
target="_blank"
|
||||
>
|
||||
{{ "organizationDataOwnershipContentAnchor" | i18n }}.
|
||||
</a>
|
||||
</div>
|
||||
</ng-container>
|
||||
<ng-container bitDialogFooter>
|
||||
<span class="tw-flex tw-gap-2">
|
||||
<button bitButton buttonType="primary" [bitDialogClose]="true" type="submit">
|
||||
{{ "continue" | i18n }}
|
||||
</button>
|
||||
<button bitButton buttonType="secondary" [bitDialogClose]="false" type="button">
|
||||
{{ "cancel" | i18n }}
|
||||
</button>
|
||||
</span>
|
||||
</ng-container>
|
||||
</bit-simple-dialog>
|
||||
<div class="tw-text-left tw-overflow-hidden tw-mb-2">
|
||||
<strong>{{ "benefits" | i18n }}:</strong>
|
||||
<ul class="tw-pl-7 tw-space-y-2 tw-pt-2">
|
||||
<li>
|
||||
{{ "centralizeDataOwnershipBenefit1" | i18n }}
|
||||
</li>
|
||||
<li>
|
||||
{{ "centralizeDataOwnershipBenefit2" | i18n }}
|
||||
</li>
|
||||
<li>
|
||||
{{ "centralizeDataOwnershipBenefit3" | i18n }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<bit-form-control>
|
||||
<input class="tw-mt-4" type="checkbox" bitCheckbox [formControl]="enabled" id="enabled" />
|
||||
<bit-label>{{ "turnOn" | i18n }}</bit-label>
|
||||
</bit-form-control>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #step1>
|
||||
<div class="tw-flex tw-flex-col tw-gap-2 tw-overflow-hidden">
|
||||
<span>
|
||||
{{ "centralizeDataOwnershipWarningDesc" | i18n }}
|
||||
</span>
|
||||
<a
|
||||
class="tw-mt-4"
|
||||
bitLink
|
||||
href="https://bitwarden.com/resources/credential-lifecycle-management/"
|
||||
target="_blank"
|
||||
>
|
||||
{{ "centralizeDataOwnershipWarningLink" | i18n }}
|
||||
<i class="bwi bwi-external-link"></i>
|
||||
</a>
|
||||
</div>
|
||||
</ng-template>
|
||||
|
||||
@@ -1,18 +1,30 @@
|
||||
import { ChangeDetectionStrategy, Component, OnInit, TemplateRef, ViewChild } from "@angular/core";
|
||||
import { lastValueFrom } from "rxjs";
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
OnInit,
|
||||
signal,
|
||||
Signal,
|
||||
TemplateRef,
|
||||
viewChild,
|
||||
WritableSignal,
|
||||
} from "@angular/core";
|
||||
import { Observable } from "rxjs";
|
||||
|
||||
import { PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { PolicyRequest } from "@bitwarden/common/admin-console/models/request/policy.request";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { EncryptService } from "@bitwarden/common/key-management/crypto/abstractions/encrypt.service";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { OrgKey } from "@bitwarden/common/types/key";
|
||||
import { CenterPositionStrategy, DialogService } from "@bitwarden/components";
|
||||
import { EncString } from "@bitwarden/sdk-internal";
|
||||
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import { BasePolicyEditDefinition, BasePolicyEditComponent } from "../base-policy-edit.component";
|
||||
import { OrganizationDataOwnershipPolicyDialogComponent } from "../policy-edit-dialogs";
|
||||
|
||||
interface VNextPolicyRequest {
|
||||
export interface VNextPolicyRequest {
|
||||
policy: PolicyRequest;
|
||||
metadata: {
|
||||
defaultUserCollectionName: string;
|
||||
@@ -20,11 +32,17 @@ interface VNextPolicyRequest {
|
||||
}
|
||||
|
||||
export class vNextOrganizationDataOwnershipPolicy extends BasePolicyEditDefinition {
|
||||
name = "organizationDataOwnership";
|
||||
description = "organizationDataOwnershipDesc";
|
||||
name = "centralizeDataOwnership";
|
||||
description = "centralizeDataOwnershipDesc";
|
||||
type = PolicyType.OrganizationDataOwnership;
|
||||
component = vNextOrganizationDataOwnershipPolicyComponent;
|
||||
showDescription = false;
|
||||
|
||||
editDialogComponent = OrganizationDataOwnershipPolicyDialogComponent;
|
||||
|
||||
override display$(organization: Organization, configService: ConfigService): Observable<boolean> {
|
||||
return configService.getFeatureFlag$(FeatureFlag.MigrateMyVaultToMyItems);
|
||||
}
|
||||
}
|
||||
|
||||
@Component({
|
||||
@@ -38,27 +56,16 @@ export class vNextOrganizationDataOwnershipPolicyComponent
|
||||
implements OnInit
|
||||
{
|
||||
constructor(
|
||||
private dialogService: DialogService,
|
||||
private i18nService: I18nService,
|
||||
private encryptService: EncryptService,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
private readonly policyForm: Signal<TemplateRef<any> | undefined> = viewChild("step0");
|
||||
private readonly warningContent: Signal<TemplateRef<any> | undefined> = viewChild("step1");
|
||||
protected readonly step: WritableSignal<number> = signal(0);
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-903): Migrate to Signals
|
||||
// eslint-disable-next-line @angular-eslint/prefer-signals
|
||||
@ViewChild("dialog", { static: true }) warningContent!: TemplateRef<unknown>;
|
||||
|
||||
override async confirm(): Promise<boolean> {
|
||||
if (this.policyResponse?.enabled && !this.enabled.value) {
|
||||
const dialogRef = this.dialogService.open(this.warningContent, {
|
||||
positionStrategy: new CenterPositionStrategy(),
|
||||
});
|
||||
const result = await lastValueFrom(dialogRef.closed);
|
||||
return Boolean(result);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
protected steps = [this.policyForm, this.warningContent];
|
||||
|
||||
async buildVNextRequest(orgKey: OrgKey): Promise<VNextPolicyRequest> {
|
||||
if (!this.policy) {
|
||||
@@ -90,4 +97,8 @@ export class vNextOrganizationDataOwnershipPolicyComponent
|
||||
|
||||
return encrypted.encryptedString;
|
||||
}
|
||||
|
||||
setStep(step: number) {
|
||||
this.step.set(step);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { OrgKey } from "@bitwarden/common/types/key";
|
||||
import {
|
||||
DIALOG_DATA,
|
||||
DialogConfig,
|
||||
@@ -28,7 +29,7 @@ import { KeyService } from "@bitwarden/key-management";
|
||||
import { SharedModule } from "../../../shared";
|
||||
|
||||
import { BasePolicyEditDefinition, BasePolicyEditComponent } from "./base-policy-edit.component";
|
||||
import { vNextOrganizationDataOwnershipPolicyComponent } from "./policy-edit-definitions/vnext-organization-data-ownership.component";
|
||||
import { VNextPolicyRequest } from "./policy-edit-definitions/organization-data-ownership.component";
|
||||
|
||||
export type PolicyEditDialogData = {
|
||||
/**
|
||||
@@ -73,13 +74,24 @@ export class PolicyEditDialogComponent implements AfterViewInit {
|
||||
private formBuilder: FormBuilder,
|
||||
protected dialogRef: DialogRef<PolicyEditDialogResult>,
|
||||
protected toastService: ToastService,
|
||||
private keyService: KeyService,
|
||||
protected keyService: KeyService,
|
||||
) {}
|
||||
|
||||
get policy(): BasePolicyEditDefinition {
|
||||
return this.data.policy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard to check if the policy component has the buildVNextRequest method.
|
||||
*/
|
||||
private hasVNextRequest(
|
||||
component: BasePolicyEditComponent,
|
||||
): component is BasePolicyEditComponent & {
|
||||
buildVNextRequest: (orgKey: OrgKey) => Promise<VNextPolicyRequest>;
|
||||
} {
|
||||
return "buildVNextRequest" in component && typeof component.buildVNextRequest === "function";
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates the child policy component and inserts it into the view.
|
||||
*/
|
||||
@@ -129,7 +141,7 @@ export class PolicyEditDialogComponent implements AfterViewInit {
|
||||
}
|
||||
|
||||
try {
|
||||
if (this.policyComponent instanceof vNextOrganizationDataOwnershipPolicyComponent) {
|
||||
if (this.hasVNextRequest(this.policyComponent)) {
|
||||
await this.handleVNextSubmission(this.policyComponent);
|
||||
} else {
|
||||
await this.handleStandardSubmission();
|
||||
@@ -158,7 +170,9 @@ export class PolicyEditDialogComponent implements AfterViewInit {
|
||||
}
|
||||
|
||||
private async handleVNextSubmission(
|
||||
policyComponent: vNextOrganizationDataOwnershipPolicyComponent,
|
||||
policyComponent: BasePolicyEditComponent & {
|
||||
buildVNextRequest: (orgKey: OrgKey) => Promise<VNextPolicyRequest>;
|
||||
},
|
||||
): Promise<void> {
|
||||
const orgKey = await firstValueFrom(
|
||||
this.accountService.activeAccount$.pipe(
|
||||
@@ -173,12 +187,12 @@ export class PolicyEditDialogComponent implements AfterViewInit {
|
||||
throw new Error("No encryption key for this organization.");
|
||||
}
|
||||
|
||||
const vNextRequest = await policyComponent.buildVNextRequest(orgKey);
|
||||
const request = await policyComponent.buildVNextRequest(orgKey);
|
||||
|
||||
await this.policyApiService.putPolicyVNext(
|
||||
this.data.organizationId,
|
||||
this.data.policy.type,
|
||||
vNextRequest,
|
||||
request,
|
||||
);
|
||||
}
|
||||
static open = (dialogService: DialogService, config: DialogConfig<PolicyEditDialogData>) => {
|
||||
|
||||
@@ -41,20 +41,15 @@ import {
|
||||
} from "@bitwarden/components";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
|
||||
import { SharedModule } from "../../../shared";
|
||||
|
||||
import { AutoConfirmPolicyEditComponent } from "./policy-edit-definitions/auto-confirm-policy.component";
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import { AutoConfirmPolicyEditComponent } from "../policy-edit-definitions/auto-confirm-policy.component";
|
||||
import {
|
||||
PolicyEditDialogComponent,
|
||||
PolicyEditDialogData,
|
||||
PolicyEditDialogResult,
|
||||
} from "./policy-edit-dialog.component";
|
||||
} from "../policy-edit-dialog.component";
|
||||
|
||||
export type MultiStepSubmit = {
|
||||
sideEffect: () => Promise<void>;
|
||||
footerContent: Signal<TemplateRef<unknown> | undefined>;
|
||||
titleContent: Signal<TemplateRef<unknown> | undefined>;
|
||||
};
|
||||
import { MultiStepSubmit } from "./models";
|
||||
|
||||
export type AutoConfirmPolicyDialogData = PolicyEditDialogData & {
|
||||
firstTimeDialog?: boolean;
|
||||
@@ -202,6 +197,7 @@ export class AutoConfirmPolicyDialogComponent
|
||||
}
|
||||
|
||||
const autoConfirmRequest = await this.policyComponent.buildRequest();
|
||||
|
||||
await this.policyApiService.putPolicy(
|
||||
this.data.organizationId,
|
||||
this.data.policy.type,
|
||||
@@ -235,7 +231,7 @@ export class AutoConfirmPolicyDialogComponent
|
||||
data: null,
|
||||
};
|
||||
|
||||
await this.policyApiService.putPolicy(
|
||||
await this.policyApiService.putPolicyVNext(
|
||||
this.data.organizationId,
|
||||
PolicyType.SingleOrg,
|
||||
singleOrgRequest,
|
||||
@@ -260,7 +256,10 @@ export class AutoConfirmPolicyDialogComponent
|
||||
|
||||
try {
|
||||
const multiStepSubmit = await firstValueFrom(this.multiStepSubmit);
|
||||
await multiStepSubmit[this.currentStep()].sideEffect();
|
||||
const sideEffect = multiStepSubmit[this.currentStep()].sideEffect;
|
||||
if (sideEffect) {
|
||||
await sideEffect();
|
||||
}
|
||||
|
||||
if (this.currentStep() === multiStepSubmit.length - 1) {
|
||||
this.dialogRef.close("saved");
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./auto-confirm-edit-policy-dialog.component";
|
||||
export * from "./organization-data-ownership-edit-policy-dialog.component";
|
||||
export * from "./models";
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Signal, TemplateRef } from "@angular/core";
|
||||
|
||||
export type MultiStepSubmit = {
|
||||
sideEffect?: () => Promise<void>;
|
||||
footerContent: Signal<TemplateRef<unknown> | undefined>;
|
||||
titleContent: Signal<TemplateRef<unknown> | undefined>;
|
||||
};
|
||||
@@ -0,0 +1,72 @@
|
||||
<form [formGroup]="formGroup" [bitSubmit]="submit">
|
||||
<bit-dialog [loading]="loading">
|
||||
<ng-container bitDialogTitle>
|
||||
@let title = multiStepSubmit()[currentStep()]?.titleContent();
|
||||
@if (title) {
|
||||
<ng-container [ngTemplateOutlet]="title"></ng-container>
|
||||
}
|
||||
</ng-container>
|
||||
|
||||
<ng-container bitDialogContent>
|
||||
@if (loading) {
|
||||
<div>
|
||||
<i
|
||||
class="bwi bwi-spinner bwi-spin tw-text-muted"
|
||||
title="{{ 'loading' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "loading" | i18n }}</span>
|
||||
</div>
|
||||
}
|
||||
<div [hidden]="loading">
|
||||
@if (policy.showDescription) {
|
||||
<p bitTypography="body1">{{ policy.description | i18n }}</p>
|
||||
}
|
||||
</div>
|
||||
<ng-template #policyForm></ng-template>
|
||||
</ng-container>
|
||||
<ng-container bitDialogFooter>
|
||||
@let footer = multiStepSubmit()[currentStep()]?.footerContent();
|
||||
@if (footer) {
|
||||
<ng-container [ngTemplateOutlet]="footer"></ng-container>
|
||||
}
|
||||
</ng-container>
|
||||
</bit-dialog>
|
||||
</form>
|
||||
|
||||
<ng-template #step0Title>
|
||||
{{ policy.name | i18n }}
|
||||
</ng-template>
|
||||
|
||||
<ng-template #step1Title>
|
||||
{{ "centralizeDataOwnershipWarningTitle" | i18n }}
|
||||
</ng-template>
|
||||
|
||||
<ng-template #step0>
|
||||
<button
|
||||
bitButton
|
||||
buttonType="primary"
|
||||
[disabled]="saveDisabled$ | async"
|
||||
bitFormButton
|
||||
type="submit"
|
||||
>
|
||||
@if (policyComponent?.policyResponse?.enabled) {
|
||||
{{ "save" | i18n }}
|
||||
} @else {
|
||||
{{ "continue" | i18n }}
|
||||
}
|
||||
</button>
|
||||
|
||||
<button bitButton buttonType="secondary" bitDialogClose type="button">
|
||||
{{ "cancel" | i18n }}
|
||||
</button>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #step1>
|
||||
<button bitButton buttonType="primary" bitFormButton type="submit">
|
||||
{{ "continue" | i18n }}
|
||||
</button>
|
||||
<button bitButton buttonType="secondary" bitDialogClose type="button">
|
||||
{{ "cancel" | i18n }}
|
||||
</button>
|
||||
</ng-template>
|
||||
@@ -0,0 +1,224 @@
|
||||
import {
|
||||
AfterViewInit,
|
||||
ChangeDetectorRef,
|
||||
Component,
|
||||
Inject,
|
||||
signal,
|
||||
TemplateRef,
|
||||
viewChild,
|
||||
WritableSignal,
|
||||
} from "@angular/core";
|
||||
import { FormBuilder } from "@angular/forms";
|
||||
import {
|
||||
catchError,
|
||||
combineLatest,
|
||||
defer,
|
||||
firstValueFrom,
|
||||
from,
|
||||
map,
|
||||
Observable,
|
||||
of,
|
||||
startWith,
|
||||
switchMap,
|
||||
} from "rxjs";
|
||||
|
||||
import { PolicyApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy-api.service.abstraction";
|
||||
import { PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { assertNonNullish } from "@bitwarden/common/auth/utils";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import {
|
||||
DIALOG_DATA,
|
||||
DialogConfig,
|
||||
DialogRef,
|
||||
DialogService,
|
||||
ToastService,
|
||||
} from "@bitwarden/components";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import { vNextOrganizationDataOwnershipPolicyComponent } from "../policy-edit-definitions";
|
||||
import {
|
||||
PolicyEditDialogComponent,
|
||||
PolicyEditDialogData,
|
||||
PolicyEditDialogResult,
|
||||
} from "../policy-edit-dialog.component";
|
||||
|
||||
import { MultiStepSubmit } from "./models";
|
||||
|
||||
/**
|
||||
* Custom policy dialog component for Centralize Organization Data
|
||||
* Ownership policy. Satisfies the PolicyDialogComponent interface
|
||||
* structurally via its static open() function.
|
||||
*/
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
|
||||
@Component({
|
||||
templateUrl: "organization-data-ownership-edit-policy-dialog.component.html",
|
||||
imports: [SharedModule],
|
||||
})
|
||||
export class OrganizationDataOwnershipPolicyDialogComponent
|
||||
extends PolicyEditDialogComponent
|
||||
implements AfterViewInit
|
||||
{
|
||||
policyType = PolicyType;
|
||||
|
||||
protected centralizeDataOwnershipEnabled$: Observable<boolean> = defer(() =>
|
||||
from(
|
||||
this.policyApiService.getPolicy(
|
||||
this.data.organizationId,
|
||||
PolicyType.OrganizationDataOwnership,
|
||||
),
|
||||
).pipe(
|
||||
map((policy) => policy.enabled),
|
||||
catchError(() => of(false)),
|
||||
),
|
||||
);
|
||||
|
||||
protected readonly currentStep: WritableSignal<number> = signal(0);
|
||||
protected readonly multiStepSubmit: WritableSignal<MultiStepSubmit[]> = signal([]);
|
||||
|
||||
private readonly policyForm = viewChild.required<TemplateRef<unknown>>("step0");
|
||||
private readonly warningContent = viewChild.required<TemplateRef<unknown>>("step1");
|
||||
private readonly policyFormTitle = viewChild.required<TemplateRef<unknown>>("step0Title");
|
||||
private readonly warningTitle = viewChild.required<TemplateRef<unknown>>("step1Title");
|
||||
|
||||
override policyComponent: vNextOrganizationDataOwnershipPolicyComponent | undefined;
|
||||
|
||||
constructor(
|
||||
@Inject(DIALOG_DATA) protected data: PolicyEditDialogData,
|
||||
accountService: AccountService,
|
||||
policyApiService: PolicyApiServiceAbstraction,
|
||||
i18nService: I18nService,
|
||||
cdr: ChangeDetectorRef,
|
||||
formBuilder: FormBuilder,
|
||||
dialogRef: DialogRef<PolicyEditDialogResult>,
|
||||
toastService: ToastService,
|
||||
protected keyService: KeyService,
|
||||
) {
|
||||
super(
|
||||
data,
|
||||
accountService,
|
||||
policyApiService,
|
||||
i18nService,
|
||||
cdr,
|
||||
formBuilder,
|
||||
dialogRef,
|
||||
toastService,
|
||||
keyService,
|
||||
);
|
||||
}
|
||||
|
||||
async ngAfterViewInit() {
|
||||
await super.ngAfterViewInit();
|
||||
|
||||
if (this.policyComponent) {
|
||||
this.saveDisabled$ = combineLatest([
|
||||
this.centralizeDataOwnershipEnabled$,
|
||||
this.policyComponent.enabled.valueChanges.pipe(
|
||||
startWith(this.policyComponent.enabled.value),
|
||||
),
|
||||
]).pipe(map(([policyEnabled, value]) => !policyEnabled && !value));
|
||||
}
|
||||
|
||||
this.multiStepSubmit.set(this.buildMultiStepSubmit());
|
||||
}
|
||||
|
||||
private buildMultiStepSubmit(): MultiStepSubmit[] {
|
||||
if (this.policyComponent?.policyResponse?.enabled) {
|
||||
return [
|
||||
{
|
||||
sideEffect: () => this.handleSubmit(),
|
||||
footerContent: this.policyForm,
|
||||
titleContent: this.policyFormTitle,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
footerContent: this.policyForm,
|
||||
titleContent: this.policyFormTitle,
|
||||
},
|
||||
{
|
||||
sideEffect: () => this.handleSubmit(),
|
||||
footerContent: this.warningContent,
|
||||
titleContent: this.warningTitle,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
private async handleSubmit() {
|
||||
if (!this.policyComponent) {
|
||||
throw new Error("PolicyComponent not initialized.");
|
||||
}
|
||||
|
||||
const orgKey = await firstValueFrom(
|
||||
this.accountService.activeAccount$.pipe(
|
||||
getUserId,
|
||||
switchMap((userId) => this.keyService.orgKeys$(userId)),
|
||||
),
|
||||
);
|
||||
|
||||
assertNonNullish(orgKey, "Org key not provided");
|
||||
|
||||
const request = await this.policyComponent.buildVNextRequest(
|
||||
orgKey[this.data.organizationId as OrganizationId],
|
||||
);
|
||||
|
||||
await this.policyApiService.putPolicyVNext(
|
||||
this.data.organizationId,
|
||||
this.data.policy.type,
|
||||
request,
|
||||
);
|
||||
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t("editedPolicyId", this.i18nService.t(this.data.policy.name)),
|
||||
});
|
||||
|
||||
if (!this.policyComponent.enabled.value) {
|
||||
this.dialogRef.close("saved");
|
||||
}
|
||||
}
|
||||
|
||||
submit = async () => {
|
||||
if (!this.policyComponent) {
|
||||
throw new Error("PolicyComponent not initialized.");
|
||||
}
|
||||
|
||||
if ((await this.policyComponent.confirm()) == false) {
|
||||
this.dialogRef.close();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const sideEffect = this.multiStepSubmit()[this.currentStep()].sideEffect;
|
||||
if (sideEffect) {
|
||||
await sideEffect();
|
||||
}
|
||||
|
||||
if (this.currentStep() === this.multiStepSubmit().length - 1) {
|
||||
this.dialogRef.close("saved");
|
||||
return;
|
||||
}
|
||||
|
||||
this.currentStep.update((value) => value + 1);
|
||||
this.policyComponent.setStep(this.currentStep());
|
||||
} catch (error: any) {
|
||||
this.toastService.showToast({
|
||||
variant: "error",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
static open = (dialogService: DialogService, config: DialogConfig<PolicyEditDialogData>) => {
|
||||
return dialogService.open<PolicyEditDialogResult>(
|
||||
OrganizationDataOwnershipPolicyDialogComponent,
|
||||
config,
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -1,13 +1,11 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
import {
|
||||
CollectionAccessSelectionView,
|
||||
OrganizationUserUserDetailsResponse,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { OrganizationUserUserDetailsResponse } from "@bitwarden/admin-console/common";
|
||||
import {
|
||||
OrganizationUserStatusType,
|
||||
OrganizationUserType,
|
||||
} from "@bitwarden/common/admin-console/enums";
|
||||
import { CollectionAccessSelectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { SelectItemView } from "@bitwarden/components";
|
||||
|
||||
import { GroupView } from "../../../core";
|
||||
|
||||
@@ -18,19 +18,21 @@ import {
|
||||
import { first } from "rxjs/operators";
|
||||
|
||||
import {
|
||||
CollectionAccessSelectionView,
|
||||
CollectionAdminService,
|
||||
CollectionAdminView,
|
||||
OrganizationUserApiService,
|
||||
OrganizationUserUserMiniResponse,
|
||||
CollectionResponse,
|
||||
CollectionView,
|
||||
CollectionService,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import {
|
||||
getOrganizationById,
|
||||
OrganizationService,
|
||||
} from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import {
|
||||
CollectionAccessSelectionView,
|
||||
CollectionAdminView,
|
||||
CollectionView,
|
||||
CollectionResponse,
|
||||
} from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { AbstractControl, AsyncValidatorFn, FormControl, ValidationErrors } from "@angular/forms";
|
||||
import { combineLatest, map, Observable, of } from "rxjs";
|
||||
|
||||
import { Collection } from "@bitwarden/admin-console/common";
|
||||
import { Collection } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { getById } from "@bitwarden/common/platform/misc";
|
||||
|
||||
@@ -3,6 +3,7 @@ import { BehaviorSubject, of } from "rxjs";
|
||||
|
||||
import { OrganizationUserApiService } from "@bitwarden/admin-console/common";
|
||||
import {
|
||||
InitializeJitPasswordCredentials,
|
||||
SetInitialPasswordCredentials,
|
||||
SetInitialPasswordService,
|
||||
SetInitialPasswordUserType,
|
||||
@@ -20,11 +21,13 @@ import { AccountCryptographicStateService } from "@bitwarden/common/key-manageme
|
||||
import { EncryptService } from "@bitwarden/common/key-management/crypto/abstractions/encrypt.service";
|
||||
import { EncString } from "@bitwarden/common/key-management/crypto/models/enc-string";
|
||||
import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/key-management/master-password/abstractions/master-password.service.abstraction";
|
||||
import { MasterPasswordSalt } from "@bitwarden/common/key-management/master-password/types/master-password.types";
|
||||
import { KeysRequest } from "@bitwarden/common/models/request/keys.request";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { RegisterSdkService } from "@bitwarden/common/platform/abstractions/sdk/register-sdk.service";
|
||||
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { CsprngArray } from "@bitwarden/common/types/csprng";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { OrganizationId, UserId } from "@bitwarden/common/types/guid";
|
||||
import { MasterKey, UserKey } from "@bitwarden/common/types/key";
|
||||
import { DEFAULT_KDF_CONFIG, KdfConfigService, KeyService } from "@bitwarden/key-management";
|
||||
import { RouterService } from "@bitwarden/web-vault/app/core";
|
||||
@@ -47,6 +50,7 @@ describe("WebSetInitialPasswordService", () => {
|
||||
let organizationInviteService: MockProxy<OrganizationInviteService>;
|
||||
let routerService: MockProxy<RouterService>;
|
||||
let accountCryptographicStateService: MockProxy<AccountCryptographicStateService>;
|
||||
let registerSdkService: MockProxy<RegisterSdkService>;
|
||||
|
||||
beforeEach(() => {
|
||||
apiService = mock<ApiService>();
|
||||
@@ -62,6 +66,7 @@ describe("WebSetInitialPasswordService", () => {
|
||||
organizationInviteService = mock<OrganizationInviteService>();
|
||||
routerService = mock<RouterService>();
|
||||
accountCryptographicStateService = mock<AccountCryptographicStateService>();
|
||||
registerSdkService = mock<RegisterSdkService>();
|
||||
|
||||
sut = new WebSetInitialPasswordService(
|
||||
apiService,
|
||||
@@ -77,6 +82,7 @@ describe("WebSetInitialPasswordService", () => {
|
||||
organizationInviteService,
|
||||
routerService,
|
||||
accountCryptographicStateService,
|
||||
registerSdkService,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -208,4 +214,36 @@ describe("WebSetInitialPasswordService", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("initializePasswordJitPasswordUserV2Encryption(...)", () => {
|
||||
it("should call routerService.getAndClearLoginRedirectUrl() and organizationInviteService.clearOrganizationInvitation()", async () => {
|
||||
// Arrange
|
||||
const credentials: InitializeJitPasswordCredentials = {
|
||||
newPasswordHint: "newPasswordHint",
|
||||
orgSsoIdentifier: "orgSsoIdentifier",
|
||||
orgId: "orgId" as OrganizationId,
|
||||
resetPasswordAutoEnroll: false,
|
||||
newPassword: "newPassword123!",
|
||||
salt: "user@example.com" as MasterPasswordSalt,
|
||||
};
|
||||
const userId = "userId" as UserId;
|
||||
|
||||
const superSpy = jest
|
||||
.spyOn(
|
||||
Object.getPrototypeOf(Object.getPrototypeOf(sut)),
|
||||
"initializePasswordJitPasswordUserV2Encryption",
|
||||
)
|
||||
.mockResolvedValue(undefined);
|
||||
|
||||
// Act
|
||||
await sut.initializePasswordJitPasswordUserV2Encryption(credentials, userId);
|
||||
|
||||
// Assert
|
||||
expect(superSpy).toHaveBeenCalledWith(credentials, userId);
|
||||
expect(routerService.getAndClearLoginRedirectUrl).toHaveBeenCalledTimes(1);
|
||||
expect(organizationInviteService.clearOrganizationInvitation).toHaveBeenCalledTimes(1);
|
||||
|
||||
superSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { OrganizationUserApiService } from "@bitwarden/admin-console/common";
|
||||
import { DefaultSetInitialPasswordService } from "@bitwarden/angular/auth/password-management/set-initial-password/default-set-initial-password.service.implementation";
|
||||
import {
|
||||
InitializeJitPasswordCredentials,
|
||||
SetInitialPasswordCredentials,
|
||||
SetInitialPasswordService,
|
||||
SetInitialPasswordUserType,
|
||||
@@ -14,6 +15,7 @@ import { AccountCryptographicStateService } from "@bitwarden/common/key-manageme
|
||||
import { EncryptService } from "@bitwarden/common/key-management/crypto/abstractions/encrypt.service";
|
||||
import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/key-management/master-password/abstractions/master-password.service.abstraction";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { RegisterSdkService } from "@bitwarden/common/platform/abstractions/sdk/register-sdk.service";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { KdfConfigService, KeyService } from "@bitwarden/key-management";
|
||||
import { RouterService } from "@bitwarden/web-vault/app/core";
|
||||
@@ -36,6 +38,7 @@ export class WebSetInitialPasswordService
|
||||
private organizationInviteService: OrganizationInviteService,
|
||||
private routerService: RouterService,
|
||||
protected accountCryptographicStateService: AccountCryptographicStateService,
|
||||
protected registerSdkService: RegisterSdkService,
|
||||
) {
|
||||
super(
|
||||
apiService,
|
||||
@@ -49,6 +52,7 @@ export class WebSetInitialPasswordService
|
||||
organizationUserApiService,
|
||||
userDecryptionOptionsService,
|
||||
accountCryptographicStateService,
|
||||
registerSdkService,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -83,4 +87,15 @@ export class WebSetInitialPasswordService
|
||||
await this.routerService.getAndClearLoginRedirectUrl();
|
||||
await this.organizationInviteService.clearOrganizationInvitation();
|
||||
}
|
||||
|
||||
override async initializePasswordJitPasswordUserV2Encryption(
|
||||
credentials: InitializeJitPasswordCredentials,
|
||||
userId: UserId,
|
||||
): Promise<void> {
|
||||
await super.initializePasswordJitPasswordUserV2Encryption(credentials, userId);
|
||||
|
||||
// TODO: Investigate refactoring the following logic in https://bitwarden.atlassian.net/browse/PM-22615
|
||||
await this.routerService.getAndClearLoginRedirectUrl();
|
||||
await this.organizationInviteService.clearOrganizationInvitation();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,11 @@ import { Router } from "@angular/router";
|
||||
|
||||
import {
|
||||
CollectionAdminService,
|
||||
DefaultCollectionAdminService,
|
||||
OrganizationUserApiService,
|
||||
CollectionService,
|
||||
OrganizationUserService,
|
||||
DefaultCollectionAdminService,
|
||||
DefaultOrganizationUserService,
|
||||
OrganizationUserApiService,
|
||||
OrganizationUserService,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { DefaultDeviceManagementComponentService } from "@bitwarden/angular/auth/device-management/default-device-management-component.service";
|
||||
import { DeviceManagementComponentServiceAbstraction } from "@bitwarden/angular/auth/device-management/device-management-component.service.abstraction";
|
||||
@@ -27,17 +27,17 @@ import {
|
||||
OBSERVABLE_DISK_LOCAL_STORAGE,
|
||||
OBSERVABLE_DISK_STORAGE,
|
||||
OBSERVABLE_MEMORY_STORAGE,
|
||||
SafeInjectionToken,
|
||||
SECURE_STORAGE,
|
||||
SYSTEM_LANGUAGE,
|
||||
SafeInjectionToken,
|
||||
WINDOW,
|
||||
} from "@bitwarden/angular/services/injection-tokens";
|
||||
import { JslibServicesModule } from "@bitwarden/angular/services/jslib-services.module";
|
||||
import {
|
||||
RegistrationFinishService as RegistrationFinishServiceAbstraction,
|
||||
LoginComponentService,
|
||||
SsoComponentService,
|
||||
LoginDecryptionOptionsService,
|
||||
RegistrationFinishService as RegistrationFinishServiceAbstraction,
|
||||
SsoComponentService,
|
||||
TwoFactorAuthDuoComponentService,
|
||||
} from "@bitwarden/auth/angular";
|
||||
import {
|
||||
@@ -90,6 +90,7 @@ import { I18nService as I18nServiceAbstraction } from "@bitwarden/common/platfor
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
|
||||
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
import { RegisterSdkService } from "@bitwarden/common/platform/abstractions/sdk/register-sdk.service";
|
||||
import { SdkClientFactory } from "@bitwarden/common/platform/abstractions/sdk/sdk-client-factory";
|
||||
import { SdkLoadService } from "@bitwarden/common/platform/abstractions/sdk/sdk-load.service";
|
||||
import { AbstractStorageService } from "@bitwarden/common/platform/abstractions/storage.service";
|
||||
@@ -120,9 +121,9 @@ import { DialogService, ToastService } from "@bitwarden/components";
|
||||
import { GeneratorServicesModule } from "@bitwarden/generator-components";
|
||||
import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy";
|
||||
import {
|
||||
BiometricsService,
|
||||
KdfConfigService,
|
||||
KeyService as KeyServiceAbstraction,
|
||||
BiometricsService,
|
||||
} from "@bitwarden/key-management";
|
||||
import {
|
||||
LockComponentService,
|
||||
@@ -135,17 +136,17 @@ import { WebVaultPremiumUpgradePromptService } from "@bitwarden/web-vault/app/va
|
||||
|
||||
import { flagEnabled } from "../../utils/flags";
|
||||
import {
|
||||
POLICY_EDIT_REGISTER,
|
||||
ossPolicyEditRegister,
|
||||
POLICY_EDIT_REGISTER,
|
||||
} from "../admin-console/organizations/policies";
|
||||
import {
|
||||
LinkSsoService,
|
||||
WebChangePasswordService,
|
||||
WebRegistrationFinishService,
|
||||
WebLoginComponentService,
|
||||
WebLoginDecryptionOptionsService,
|
||||
WebTwoFactorAuthDuoComponentService,
|
||||
LinkSsoService,
|
||||
WebRegistrationFinishService,
|
||||
WebSetInitialPasswordService,
|
||||
WebTwoFactorAuthDuoComponentService,
|
||||
} from "../auth";
|
||||
import { WebSsoComponentService } from "../auth/core/services/login/web-sso-component.service";
|
||||
import { WebPremiumInterestStateService } from "../billing/services/premium-interest/web-premium-interest-state.service";
|
||||
@@ -320,6 +321,7 @@ const safeProviders: SafeProvider[] = [
|
||||
OrganizationInviteService,
|
||||
RouterService,
|
||||
AccountCryptographicStateService,
|
||||
RegisterSdkService,
|
||||
],
|
||||
}),
|
||||
safeProvider({
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
import { Component, ChangeDetectionStrategy } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { ReactiveFormsModule } from "@angular/forms";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
import { BehaviorSubject } from "rxjs";
|
||||
|
||||
import { I18nPipe } from "@bitwarden/angular/platform/pipes/i18n.pipe";
|
||||
import { AuditService } from "@bitwarden/common/abstractions/audit.service";
|
||||
import { AccountInfo, AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { BreachAccountResponse } from "@bitwarden/common/dirt/models/response/breach-account.response";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { mockAccountInfoWith } from "@bitwarden/common/spec";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { AsyncActionsModule, ButtonModule, FormFieldModule } from "@bitwarden/components";
|
||||
import { I18nPipe } from "@bitwarden/ui-common";
|
||||
|
||||
import { BreachReportComponent } from "./breach-report.component";
|
||||
|
||||
@@ -32,6 +32,21 @@ const breachedAccounts = [
|
||||
}),
|
||||
];
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: "app-header",
|
||||
template: "<div></div>",
|
||||
standalone: false,
|
||||
})
|
||||
class MockHeaderComponent {}
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: "bit-container",
|
||||
template: "<div></div>",
|
||||
standalone: false,
|
||||
})
|
||||
class MockBitContainerComponent {}
|
||||
|
||||
describe("BreachReportComponent", () => {
|
||||
let component: BreachReportComponent;
|
||||
let fixture: ComponentFixture<BreachReportComponent>;
|
||||
@@ -51,8 +66,8 @@ describe("BreachReportComponent", () => {
|
||||
accountService.activeAccount$ = activeAccountSubject;
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
declarations: [BreachReportComponent, I18nPipe],
|
||||
imports: [ReactiveFormsModule],
|
||||
declarations: [BreachReportComponent, MockHeaderComponent, MockBitContainerComponent],
|
||||
imports: [ReactiveFormsModule, I18nPipe, AsyncActionsModule, ButtonModule, FormFieldModule],
|
||||
providers: [
|
||||
{
|
||||
provide: AuditService,
|
||||
@@ -67,9 +82,7 @@ describe("BreachReportComponent", () => {
|
||||
useValue: mock<I18nService>(),
|
||||
},
|
||||
],
|
||||
// FIXME(PM-18598): Replace unknownElements and unknownProperties with actual imports
|
||||
errorOnUnknownElements: false,
|
||||
errorOnUnknownProperties: false,
|
||||
schemas: [],
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Component, ChangeDetectionStrategy } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
import { of } from "rxjs";
|
||||
|
||||
import { I18nPipe } from "@bitwarden/angular/platform/pipes/i18n.pipe";
|
||||
import { AuditService } from "@bitwarden/common/abstractions/audit.service";
|
||||
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
@@ -12,7 +12,13 @@ import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/sp
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import {
|
||||
DialogService,
|
||||
AsyncActionsModule,
|
||||
ButtonModule,
|
||||
FormFieldModule,
|
||||
} from "@bitwarden/components";
|
||||
import { I18nPipe } from "@bitwarden/ui-common";
|
||||
import { CipherFormConfigService, PasswordRepromptService } from "@bitwarden/vault";
|
||||
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
@@ -20,6 +26,22 @@ import { AdminConsoleCipherFormConfigService } from "../../../vault/org-vault/se
|
||||
import { ExposedPasswordsReportComponent } from "./exposed-passwords-report.component";
|
||||
import { cipherData } from "./reports-ciphers.mock";
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: "app-header",
|
||||
template: "<div></div>",
|
||||
standalone: false,
|
||||
})
|
||||
class MockHeaderComponent {}
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: "bit-container",
|
||||
template: "<div></div>",
|
||||
standalone: false,
|
||||
})
|
||||
class MockBitContainerComponent {}
|
||||
|
||||
describe("ExposedPasswordsReportComponent", () => {
|
||||
let component: ExposedPasswordsReportComponent;
|
||||
let fixture: ComponentFixture<ExposedPasswordsReportComponent>;
|
||||
@@ -30,16 +52,19 @@ describe("ExposedPasswordsReportComponent", () => {
|
||||
const userId = Utils.newGuid() as UserId;
|
||||
const accountService: FakeAccountService = mockAccountServiceWith(userId);
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
let cipherFormConfigServiceMock: MockProxy<CipherFormConfigService>;
|
||||
syncServiceMock = mock<SyncService>();
|
||||
auditService = mock<AuditService>();
|
||||
organizationService = mock<OrganizationService>();
|
||||
organizationService.organizations$.mockReturnValue(of([]));
|
||||
// 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
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ExposedPasswordsReportComponent, I18nPipe],
|
||||
await TestBed.configureTestingModule({
|
||||
declarations: [
|
||||
ExposedPasswordsReportComponent,
|
||||
MockHeaderComponent,
|
||||
MockBitContainerComponent,
|
||||
],
|
||||
imports: [I18nPipe, AsyncActionsModule, ButtonModule, FormFieldModule],
|
||||
providers: [
|
||||
{
|
||||
provide: CipherService,
|
||||
@@ -83,9 +108,6 @@ describe("ExposedPasswordsReportComponent", () => {
|
||||
},
|
||||
],
|
||||
schemas: [],
|
||||
// FIXME(PM-18598): Replace unknownElements and unknownProperties with actual imports
|
||||
errorOnUnknownElements: false,
|
||||
errorOnUnknownProperties: false,
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
|
||||
@@ -31,81 +31,75 @@
|
||||
</bit-toggle>
|
||||
</ng-container>
|
||||
</bit-toggle-group>
|
||||
<bit-table [dataSource]="dataSource">
|
||||
<bit-table-scroll [dataSource]="dataSource" [rowSize]="75">
|
||||
<ng-container header *ngIf="!isAdminConsoleActive">
|
||||
<tr bitRow>
|
||||
<th bitCell></th>
|
||||
<th bitCell>{{ "name" | i18n }}</th>
|
||||
<th bitCell>{{ "owner" | i18n }}</th>
|
||||
<th bitCell></th>
|
||||
</tr>
|
||||
<th bitCell></th>
|
||||
<th bitCell>{{ "name" | i18n }}</th>
|
||||
<th bitCell>{{ "owner" | i18n }}</th>
|
||||
<th bitCell></th>
|
||||
</ng-container>
|
||||
<tbody>
|
||||
<ng-template body let-rows$>
|
||||
<tr bitRow *ngFor="let r of rows$ | async">
|
||||
<td bitCell>
|
||||
<app-vault-icon [cipher]="r"></app-vault-icon>
|
||||
</td>
|
||||
<td bitCell>
|
||||
<ng-container *ngIf="!organization || canManageCipher(r); else cantManage">
|
||||
<a
|
||||
bitLink
|
||||
href="#"
|
||||
appStopClick
|
||||
(click)="selectCipher(r)"
|
||||
title="{{ 'editItemWithName' | i18n: r.name }}"
|
||||
>{{ r.name }}</a
|
||||
>
|
||||
</ng-container>
|
||||
<ng-template #cantManage>
|
||||
<span>{{ r.name }}</span>
|
||||
</ng-template>
|
||||
<ng-container *ngIf="!organization && r.organizationId">
|
||||
<i
|
||||
class="bwi bwi-collection-shared tw-ml-1"
|
||||
appStopProp
|
||||
title="{{ 'shared' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "shared" | i18n }}</span>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="r.hasAttachments">
|
||||
<i
|
||||
class="bwi bwi-paperclip tw-ml-1"
|
||||
appStopProp
|
||||
title="{{ 'attachments' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "attachments" | i18n }}</span>
|
||||
</ng-container>
|
||||
<br />
|
||||
<small>{{ r.subTitle }}</small>
|
||||
</td>
|
||||
<td bitCell>
|
||||
<app-org-badge
|
||||
*ngIf="!organization"
|
||||
[disabled]="disabled"
|
||||
[organizationId]="r.organizationId"
|
||||
[organizationName]="r.organizationId | orgNameFromId: (organizations$ | async)"
|
||||
appStopProp
|
||||
>
|
||||
</app-org-badge>
|
||||
</td>
|
||||
<td bitCell class="tw-text-right">
|
||||
<a
|
||||
bitBadge
|
||||
href="{{ cipherDocs.get(r.id) }}"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
*ngIf="cipherDocs.has(r.id)"
|
||||
>
|
||||
{{ "instructions" | i18n }}</a
|
||||
>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-template>
|
||||
</tbody></bit-table
|
||||
>
|
||||
<ng-template bitRowDef let-row>
|
||||
<td bitCell>
|
||||
<app-vault-icon [cipher]="row"></app-vault-icon>
|
||||
</td>
|
||||
<td bitCell>
|
||||
<ng-container *ngIf="!organization || canManageCipher(row); else cantManage">
|
||||
<a
|
||||
bitLink
|
||||
href="#"
|
||||
appStopClick
|
||||
(click)="selectCipher(row)"
|
||||
title="{{ 'editItemWithName' | i18n: row.name }}"
|
||||
>{{ row.name }}</a
|
||||
>
|
||||
</ng-container>
|
||||
<ng-template #cantManage>
|
||||
<span>{{ row.name }}</span>
|
||||
</ng-template>
|
||||
<ng-container *ngIf="!organization && row.organizationId">
|
||||
<i
|
||||
class="bwi bwi-collection-shared tw-ml-1"
|
||||
appStopProp
|
||||
title="{{ 'shared' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "shared" | i18n }}</span>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="row.hasAttachments">
|
||||
<i
|
||||
class="bwi bwi-paperclip tw-ml-1"
|
||||
appStopProp
|
||||
title="{{ 'attachments' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "attachments" | i18n }}</span>
|
||||
</ng-container>
|
||||
<br />
|
||||
<small>{{ row.subTitle }}</small>
|
||||
</td>
|
||||
<td bitCell>
|
||||
<app-org-badge
|
||||
*ngIf="!organization"
|
||||
[disabled]="disabled"
|
||||
[organizationId]="row.organizationId"
|
||||
[organizationName]="row.organizationId | orgNameFromId: (organizations$ | async)"
|
||||
appStopProp
|
||||
>
|
||||
</app-org-badge>
|
||||
</td>
|
||||
<td bitCell class="tw-text-right">
|
||||
<a
|
||||
bitBadge
|
||||
href="{{ cipherDocs.get(row.id) }}"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
*ngIf="cipherDocs.has(row.id)"
|
||||
>
|
||||
{{ "instructions" | i18n }}</a
|
||||
>
|
||||
</td>
|
||||
</ng-template>
|
||||
</bit-table-scroll>
|
||||
</ng-container>
|
||||
</div>
|
||||
</bit-container>
|
||||
|
||||
@@ -3,7 +3,6 @@ import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { MockProxy, mock } from "jest-mock-extended";
|
||||
import { of } from "rxjs";
|
||||
|
||||
import { I18nPipe } from "@bitwarden/angular/platform/pipes/i18n.pipe";
|
||||
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
@@ -14,6 +13,7 @@ import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { I18nPipe } from "@bitwarden/ui-common";
|
||||
import { CipherFormConfigService, PasswordRepromptService } from "@bitwarden/vault";
|
||||
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
@@ -37,7 +37,8 @@ describe("InactiveTwoFactorReportComponent", () => {
|
||||
syncServiceMock = mock<SyncService>();
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
declarations: [InactiveTwoFactorReportComponent, I18nPipe],
|
||||
declarations: [InactiveTwoFactorReportComponent],
|
||||
imports: [I18nPipe],
|
||||
providers: [
|
||||
{
|
||||
provide: CipherService,
|
||||
|
||||
@@ -17,14 +17,17 @@ import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.serv
|
||||
import { Cipher } from "@bitwarden/common/vault/models/domain/cipher";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { PasswordRepromptService, CipherFormConfigService } from "@bitwarden/vault";
|
||||
import {
|
||||
PasswordRepromptService,
|
||||
CipherFormConfigService,
|
||||
RoutedVaultFilterBridgeService,
|
||||
RoutedVaultFilterService,
|
||||
} from "@bitwarden/vault";
|
||||
|
||||
import { HeaderModule } from "../../../../layouts/header/header.module";
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import { OrganizationBadgeModule } from "../../../../vault/individual-vault/organization-badge/organization-badge.module";
|
||||
import { PipesModule } from "../../../../vault/individual-vault/pipes/pipes.module";
|
||||
import { RoutedVaultFilterBridgeService } from "../../../../vault/individual-vault/vault-filter/services/routed-vault-filter-bridge.service";
|
||||
import { RoutedVaultFilterService } from "../../../../vault/individual-vault/vault-filter/services/routed-vault-filter.service";
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
import { ExposedPasswordsReportComponent as BaseExposedPasswordsReportComponent } from "../exposed-passwords-report.component";
|
||||
|
||||
|
||||
@@ -12,14 +12,17 @@ import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.serv
|
||||
import { Cipher } from "@bitwarden/common/vault/models/domain/cipher";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { CipherFormConfigService, PasswordRepromptService } from "@bitwarden/vault";
|
||||
import {
|
||||
CipherFormConfigService,
|
||||
PasswordRepromptService,
|
||||
RoutedVaultFilterBridgeService,
|
||||
RoutedVaultFilterService,
|
||||
} from "@bitwarden/vault";
|
||||
|
||||
import { HeaderModule } from "../../../../layouts/header/header.module";
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import { OrganizationBadgeModule } from "../../../../vault/individual-vault/organization-badge/organization-badge.module";
|
||||
import { PipesModule } from "../../../../vault/individual-vault/pipes/pipes.module";
|
||||
import { RoutedVaultFilterBridgeService } from "../../../../vault/individual-vault/vault-filter/services/routed-vault-filter-bridge.service";
|
||||
import { RoutedVaultFilterService } from "../../../../vault/individual-vault/vault-filter/services/routed-vault-filter.service";
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
import { InactiveTwoFactorReportComponent as BaseInactiveTwoFactorReportComponent } from "../inactive-two-factor-report.component";
|
||||
|
||||
|
||||
@@ -16,14 +16,17 @@ import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.serv
|
||||
import { Cipher } from "@bitwarden/common/vault/models/domain/cipher";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { CipherFormConfigService, PasswordRepromptService } from "@bitwarden/vault";
|
||||
import {
|
||||
CipherFormConfigService,
|
||||
PasswordRepromptService,
|
||||
RoutedVaultFilterBridgeService,
|
||||
RoutedVaultFilterService,
|
||||
} from "@bitwarden/vault";
|
||||
|
||||
import { HeaderModule } from "../../../../layouts/header/header.module";
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import { OrganizationBadgeModule } from "../../../../vault/individual-vault/organization-badge/organization-badge.module";
|
||||
import { PipesModule } from "../../../../vault/individual-vault/pipes/pipes.module";
|
||||
import { RoutedVaultFilterBridgeService } from "../../../../vault/individual-vault/vault-filter/services/routed-vault-filter-bridge.service";
|
||||
import { RoutedVaultFilterService } from "../../../../vault/individual-vault/vault-filter/services/routed-vault-filter.service";
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
import { ReusedPasswordsReportComponent as BaseReusedPasswordsReportComponent } from "../reused-passwords-report.component";
|
||||
|
||||
|
||||
@@ -16,14 +16,17 @@ import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.serv
|
||||
import { Cipher } from "@bitwarden/common/vault/models/domain/cipher";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { CipherFormConfigService, PasswordRepromptService } from "@bitwarden/vault";
|
||||
import {
|
||||
CipherFormConfigService,
|
||||
PasswordRepromptService,
|
||||
RoutedVaultFilterBridgeService,
|
||||
RoutedVaultFilterService,
|
||||
} from "@bitwarden/vault";
|
||||
|
||||
import { HeaderModule } from "../../../../layouts/header/header.module";
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import { OrganizationBadgeModule } from "../../../../vault/individual-vault/organization-badge/organization-badge.module";
|
||||
import { PipesModule } from "../../../../vault/individual-vault/pipes/pipes.module";
|
||||
import { RoutedVaultFilterBridgeService } from "../../../../vault/individual-vault/vault-filter/services/routed-vault-filter-bridge.service";
|
||||
import { RoutedVaultFilterService } from "../../../../vault/individual-vault/vault-filter/services/routed-vault-filter.service";
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
import { UnsecuredWebsitesReportComponent as BaseUnsecuredWebsitesReportComponent } from "../unsecured-websites-report.component";
|
||||
|
||||
|
||||
@@ -17,14 +17,17 @@ import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.serv
|
||||
import { Cipher } from "@bitwarden/common/vault/models/domain/cipher";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { CipherFormConfigService, PasswordRepromptService } from "@bitwarden/vault";
|
||||
import {
|
||||
CipherFormConfigService,
|
||||
PasswordRepromptService,
|
||||
RoutedVaultFilterBridgeService,
|
||||
RoutedVaultFilterService,
|
||||
} from "@bitwarden/vault";
|
||||
|
||||
import { HeaderModule } from "../../../../layouts/header/header.module";
|
||||
import { SharedModule } from "../../../../shared";
|
||||
import { OrganizationBadgeModule } from "../../../../vault/individual-vault/organization-badge/organization-badge.module";
|
||||
import { PipesModule } from "../../../../vault/individual-vault/pipes/pipes.module";
|
||||
import { RoutedVaultFilterBridgeService } from "../../../../vault/individual-vault/vault-filter/services/routed-vault-filter-bridge.service";
|
||||
import { RoutedVaultFilterService } from "../../../../vault/individual-vault/vault-filter/services/routed-vault-filter.service";
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
import { WeakPasswordsReportComponent as BaseWeakPasswordsReportComponent } from "../weak-passwords-report.component";
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { ChangeDetectionStrategy, Component } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { MockProxy, mock } from "jest-mock-extended";
|
||||
import { of } from "rxjs";
|
||||
|
||||
import { I18nPipe } from "@bitwarden/angular/platform/pipes/i18n.pipe";
|
||||
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
@@ -12,6 +12,7 @@ import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { I18nPipe } from "@bitwarden/ui-common";
|
||||
import { CipherFormConfigService, PasswordRepromptService } from "@bitwarden/vault";
|
||||
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
@@ -19,6 +20,22 @@ import { AdminConsoleCipherFormConfigService } from "../../../vault/org-vault/se
|
||||
import { cipherData } from "./reports-ciphers.mock";
|
||||
import { ReusedPasswordsReportComponent } from "./reused-passwords-report.component";
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: "app-header",
|
||||
template: "<div></div>",
|
||||
standalone: false,
|
||||
})
|
||||
class MockHeaderComponent {}
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: "bit-container",
|
||||
template: "<div></div>",
|
||||
standalone: false,
|
||||
})
|
||||
class MockBitContainerComponent {}
|
||||
|
||||
describe("ReusedPasswordsReportComponent", () => {
|
||||
let component: ReusedPasswordsReportComponent;
|
||||
let fixture: ComponentFixture<ReusedPasswordsReportComponent>;
|
||||
@@ -28,15 +45,18 @@ describe("ReusedPasswordsReportComponent", () => {
|
||||
const userId = Utils.newGuid() as UserId;
|
||||
const accountService: FakeAccountService = mockAccountServiceWith(userId);
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
let cipherFormConfigServiceMock: MockProxy<CipherFormConfigService>;
|
||||
organizationService = mock<OrganizationService>();
|
||||
organizationService.organizations$.mockReturnValue(of([]));
|
||||
syncServiceMock = mock<SyncService>();
|
||||
// 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
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ReusedPasswordsReportComponent, I18nPipe],
|
||||
await TestBed.configureTestingModule({
|
||||
declarations: [
|
||||
ReusedPasswordsReportComponent,
|
||||
MockHeaderComponent,
|
||||
MockBitContainerComponent,
|
||||
],
|
||||
imports: [I18nPipe],
|
||||
providers: [
|
||||
{
|
||||
provide: CipherService,
|
||||
@@ -76,8 +96,6 @@ describe("ReusedPasswordsReportComponent", () => {
|
||||
},
|
||||
],
|
||||
schemas: [],
|
||||
// FIXME(PM-18598): Replace unknownElements and unknownProperties with actual imports
|
||||
errorOnUnknownElements: false,
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
|
||||
@@ -32,68 +32,63 @@
|
||||
</bit-toggle>
|
||||
</ng-container>
|
||||
</bit-toggle-group>
|
||||
<bit-table [dataSource]="dataSource">
|
||||
<bit-table-scroll [dataSource]="dataSource" [rowSize]="75">
|
||||
<ng-container header *ngIf="!isAdminConsoleActive">
|
||||
<tr bitRow>
|
||||
<th bitCell></th>
|
||||
<th bitCell>{{ "name" | i18n }}</th>
|
||||
<th bitCell>{{ "owner" | i18n }}</th>
|
||||
<th bitCell></th>
|
||||
</tr>
|
||||
<th bitCell></th>
|
||||
<th bitCell>{{ "name" | i18n }}</th>
|
||||
<th bitCell>{{ "owner" | i18n }}</th>
|
||||
</ng-container>
|
||||
<ng-template body let-rows$>
|
||||
<tr bitRow *ngFor="let r of rows$ | async">
|
||||
<td bitCell>
|
||||
<app-vault-icon [cipher]="r"></app-vault-icon>
|
||||
</td>
|
||||
<td bitCell>
|
||||
<ng-container *ngIf="!organization || canManageCipher(r); else cantManage">
|
||||
<a
|
||||
bitLink
|
||||
href="#"
|
||||
appStopClick
|
||||
(click)="selectCipher(r)"
|
||||
title="{{ 'editItemWithName' | i18n: r.name }}"
|
||||
>{{ r.name }}</a
|
||||
>
|
||||
</ng-container>
|
||||
<ng-template #cantManage>
|
||||
<span>{{ r.name }}</span>
|
||||
</ng-template>
|
||||
<ng-container *ngIf="!organization && r.organizationId">
|
||||
<i
|
||||
class="bwi bwi-collection-shared tw-ml-1"
|
||||
appStopProp
|
||||
title="{{ 'shared' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "shared" | i18n }}</span>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="r.hasAttachments">
|
||||
<i
|
||||
class="bwi bwi-paperclip tw-ml-1"
|
||||
appStopProp
|
||||
title="{{ 'attachments' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "attachments" | i18n }}</span>
|
||||
</ng-container>
|
||||
<br />
|
||||
<small>{{ r.subTitle }}</small>
|
||||
</td>
|
||||
<td bitCell>
|
||||
<app-org-badge
|
||||
*ngIf="!organization"
|
||||
[disabled]="disabled"
|
||||
[organizationId]="r.organizationId"
|
||||
[organizationName]="r.organizationId | orgNameFromId: (organizations$ | async)"
|
||||
appStopProp
|
||||
<ng-template bitRowDef let-row>
|
||||
<td bitCell>
|
||||
<app-vault-icon [cipher]="row"></app-vault-icon>
|
||||
</td>
|
||||
<td bitCell>
|
||||
<ng-container *ngIf="!organization || canManageCipher(row); else cantManage">
|
||||
<a
|
||||
bitLink
|
||||
href="#"
|
||||
appStopClick
|
||||
(click)="selectCipher(row)"
|
||||
title="{{ 'editItemWithName' | i18n: row.name }}"
|
||||
>{{ row.name }}</a
|
||||
>
|
||||
</app-org-badge>
|
||||
</td>
|
||||
</tr>
|
||||
</ng-container>
|
||||
<ng-template #cantManage>
|
||||
<span>{{ row.name }}</span>
|
||||
</ng-template>
|
||||
<ng-container *ngIf="!organization && row.organizationId">
|
||||
<i
|
||||
class="bwi bwi-collection-shared tw-ml-1"
|
||||
appStopProp
|
||||
title="{{ 'shared' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "shared" | i18n }}</span>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="row.hasAttachments">
|
||||
<i
|
||||
class="bwi bwi-paperclip tw-ml-1"
|
||||
appStopProp
|
||||
title="{{ 'attachments' | i18n }}"
|
||||
aria-hidden="true"
|
||||
></i>
|
||||
<span class="tw-sr-only">{{ "attachments" | i18n }}</span>
|
||||
</ng-container>
|
||||
<br />
|
||||
<small>{{ row.subTitle }}</small>
|
||||
</td>
|
||||
<td bitCell>
|
||||
<app-org-badge
|
||||
*ngIf="!organization"
|
||||
[disabled]="disabled"
|
||||
[organizationId]="row.organizationId"
|
||||
[organizationName]="row.organizationId | orgNameFromId: (organizations$ | async)"
|
||||
appStopProp
|
||||
>
|
||||
</app-org-badge>
|
||||
</td>
|
||||
</ng-template>
|
||||
</bit-table>
|
||||
</bit-table-scroll>
|
||||
</ng-container>
|
||||
</div>
|
||||
</bit-container>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { ChangeDetectionStrategy, Component } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { MockProxy, mock } from "jest-mock-extended";
|
||||
import { of } from "rxjs";
|
||||
|
||||
import { CollectionService } from "@bitwarden/admin-console/common";
|
||||
import { I18nPipe } from "@bitwarden/angular/platform/pipes/i18n.pipe";
|
||||
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
@@ -13,6 +13,7 @@ import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { I18nPipe } from "@bitwarden/ui-common";
|
||||
import { CipherFormConfigService, PasswordRepromptService } from "@bitwarden/vault";
|
||||
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
@@ -20,6 +21,22 @@ import { AdminConsoleCipherFormConfigService } from "../../../vault/org-vault/se
|
||||
import { cipherData } from "./reports-ciphers.mock";
|
||||
import { UnsecuredWebsitesReportComponent } from "./unsecured-websites-report.component";
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: "app-header",
|
||||
template: "<div></div>",
|
||||
standalone: false,
|
||||
})
|
||||
class MockHeaderComponent {}
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: "bit-container",
|
||||
template: "<div></div>",
|
||||
standalone: false,
|
||||
})
|
||||
class MockBitContainerComponent {}
|
||||
|
||||
describe("UnsecuredWebsitesReportComponent", () => {
|
||||
let component: UnsecuredWebsitesReportComponent;
|
||||
let fixture: ComponentFixture<UnsecuredWebsitesReportComponent>;
|
||||
@@ -30,7 +47,7 @@ describe("UnsecuredWebsitesReportComponent", () => {
|
||||
const userId = Utils.newGuid() as UserId;
|
||||
const accountService: FakeAccountService = mockAccountServiceWith(userId);
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
let cipherFormConfigServiceMock: MockProxy<CipherFormConfigService>;
|
||||
organizationService = mock<OrganizationService>();
|
||||
organizationService.organizations$.mockReturnValue(of([]));
|
||||
@@ -38,10 +55,13 @@ describe("UnsecuredWebsitesReportComponent", () => {
|
||||
collectionService = mock<CollectionService>();
|
||||
adminConsoleCipherFormConfigService = mock<AdminConsoleCipherFormConfigService>();
|
||||
|
||||
// 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
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [UnsecuredWebsitesReportComponent, I18nPipe],
|
||||
await TestBed.configureTestingModule({
|
||||
declarations: [
|
||||
UnsecuredWebsitesReportComponent,
|
||||
MockHeaderComponent,
|
||||
MockBitContainerComponent,
|
||||
],
|
||||
imports: [I18nPipe],
|
||||
providers: [
|
||||
{
|
||||
provide: CipherService,
|
||||
@@ -85,8 +105,6 @@ describe("UnsecuredWebsitesReportComponent", () => {
|
||||
},
|
||||
],
|
||||
schemas: [],
|
||||
// FIXME(PM-18598): Replace unknownElements and unknownProperties with actual imports
|
||||
errorOnUnknownElements: false,
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { ChangeDetectionStrategy, Component } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
import { of } from "rxjs";
|
||||
|
||||
import { I18nPipe } from "@bitwarden/angular/platform/pipes/i18n.pipe";
|
||||
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
@@ -13,6 +13,7 @@ import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import { I18nPipe } from "@bitwarden/ui-common";
|
||||
import { CipherFormConfigService, PasswordRepromptService } from "@bitwarden/vault";
|
||||
|
||||
import { AdminConsoleCipherFormConfigService } from "../../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
@@ -20,6 +21,22 @@ import { AdminConsoleCipherFormConfigService } from "../../../vault/org-vault/se
|
||||
import { cipherData } from "./reports-ciphers.mock";
|
||||
import { WeakPasswordsReportComponent } from "./weak-passwords-report.component";
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: "app-header",
|
||||
template: "<div></div>",
|
||||
standalone: false,
|
||||
})
|
||||
class MockHeaderComponent {}
|
||||
|
||||
@Component({
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
selector: "bit-container",
|
||||
template: "<div></div>",
|
||||
standalone: false,
|
||||
})
|
||||
class MockBitContainerComponent {}
|
||||
|
||||
describe("WeakPasswordsReportComponent", () => {
|
||||
let component: WeakPasswordsReportComponent;
|
||||
let fixture: ComponentFixture<WeakPasswordsReportComponent>;
|
||||
@@ -30,16 +47,16 @@ describe("WeakPasswordsReportComponent", () => {
|
||||
const userId = Utils.newGuid() as UserId;
|
||||
const accountService: FakeAccountService = mockAccountServiceWith(userId);
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
let cipherFormConfigServiceMock: MockProxy<CipherFormConfigService>;
|
||||
syncServiceMock = mock<SyncService>();
|
||||
passwordStrengthService = mock<PasswordStrengthServiceAbstraction>();
|
||||
organizationService = mock<OrganizationService>();
|
||||
organizationService.organizations$.mockReturnValue(of([]));
|
||||
// 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
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [WeakPasswordsReportComponent, I18nPipe],
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
declarations: [WeakPasswordsReportComponent, MockHeaderComponent, MockBitContainerComponent],
|
||||
imports: [I18nPipe],
|
||||
providers: [
|
||||
{
|
||||
provide: CipherService,
|
||||
@@ -84,8 +101,6 @@ describe("WeakPasswordsReportComponent", () => {
|
||||
},
|
||||
],
|
||||
schemas: [],
|
||||
// FIXME(PM-18598): Replace unknownElements and unknownProperties with actual imports
|
||||
errorOnUnknownElements: false,
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
<div class="tw-flex tw-flex-wrap tw-gap-4 tw-mt-4">
|
||||
<div class="tw-w-full">
|
||||
<a bitButton routerLink="./" *ngIf="!homepage">
|
||||
{{ "backToReports" | i18n }}
|
||||
</a>
|
||||
@if (!homepage) {
|
||||
<a bitButton routerLink="./">
|
||||
{{ "backToReports" | i18n }}
|
||||
</a>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Component, OnDestroy } from "@angular/core";
|
||||
import { Component } from "@angular/core";
|
||||
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
|
||||
import { NavigationEnd, Router } from "@angular/router";
|
||||
import { Subscription } from "rxjs";
|
||||
import { filter } from "rxjs/operators";
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
@@ -10,20 +10,20 @@ import { filter } from "rxjs/operators";
|
||||
templateUrl: "reports-layout.component.html",
|
||||
standalone: false,
|
||||
})
|
||||
export class ReportsLayoutComponent implements OnDestroy {
|
||||
export class ReportsLayoutComponent {
|
||||
homepage = true;
|
||||
subscription: Subscription;
|
||||
|
||||
constructor(router: Router) {
|
||||
this.subscription = router.events
|
||||
.pipe(filter((event) => event instanceof NavigationEnd))
|
||||
// eslint-disable-next-line rxjs-angular/prefer-takeuntil
|
||||
const reportsHomeRoute = "/reports";
|
||||
|
||||
this.homepage = router.url === reportsHomeRoute;
|
||||
router.events
|
||||
.pipe(
|
||||
takeUntilDestroyed(),
|
||||
filter((event) => event instanceof NavigationEnd),
|
||||
)
|
||||
.subscribe((event) => {
|
||||
this.homepage = (event as NavigationEnd).url == "/reports";
|
||||
this.homepage = (event as NavigationEnd).url == reportsHomeRoute;
|
||||
});
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.subscription?.unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { CommonModule } from "@angular/common";
|
||||
import { NgModule } from "@angular/core";
|
||||
|
||||
import { CipherFormConfigService, DefaultCipherFormConfigService } from "@bitwarden/vault";
|
||||
import {
|
||||
CipherFormConfigService,
|
||||
DefaultCipherFormConfigService,
|
||||
RoutedVaultFilterBridgeService,
|
||||
RoutedVaultFilterService,
|
||||
} from "@bitwarden/vault";
|
||||
|
||||
import { HeaderModule } from "../../layouts/header/header.module";
|
||||
import { SharedModule } from "../../shared";
|
||||
import { OrganizationBadgeModule } from "../../vault/individual-vault/organization-badge/organization-badge.module";
|
||||
import { PipesModule } from "../../vault/individual-vault/pipes/pipes.module";
|
||||
import { RoutedVaultFilterBridgeService } from "../../vault/individual-vault/vault-filter/services/routed-vault-filter-bridge.service";
|
||||
import { RoutedVaultFilterService } from "../../vault/individual-vault/vault-filter/services/routed-vault-filter.service";
|
||||
import { AdminConsoleCipherFormConfigService } from "../../vault/org-vault/services/admin-console-cipher-form-config.service";
|
||||
|
||||
import { BreachReportComponent } from "./pages/breach-report.component";
|
||||
|
||||
@@ -85,9 +85,14 @@ export class PrivateKeyStep implements RecoveryStep {
|
||||
}
|
||||
|
||||
logger.record("Replacing private key");
|
||||
await this.privateKeyRegenerationService.regenerateUserPublicKeyEncryptionKeyPair(
|
||||
workingData.userId!,
|
||||
);
|
||||
logger.record("Private key replaced successfully");
|
||||
const recovered =
|
||||
await this.privateKeyRegenerationService.regenerateUserPublicKeyEncryptionKeyPair(
|
||||
workingData.userId!,
|
||||
);
|
||||
if (!recovered) {
|
||||
logger.record("Private key replacement could not be performed");
|
||||
} else {
|
||||
logger.record("Private key replacement replaced successfully");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Injectable } from "@angular/core";
|
||||
import { firstValueFrom } from "rxjs";
|
||||
|
||||
import { CollectionAdminService, CollectionAdminView } from "@bitwarden/admin-console/common";
|
||||
import { CollectionAdminService } from "@bitwarden/admin-console/common";
|
||||
import { CollectionAdminView } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { ImportCollectionServiceAbstraction } from "@bitwarden/importer-core";
|
||||
import { UserId } from "@bitwarden/user-core";
|
||||
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
# Send Authentication Flows
|
||||
|
||||
In the below diagrams, activations represent client control flow.
|
||||
|
||||
## Public Sends
|
||||
|
||||
Anyone can access a public send. The token endpoint automatically issues a token. It never issues a challenge.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Visitor
|
||||
participant TryAccess as try-send-access.guard
|
||||
participant SendToken as send-token API
|
||||
participant ViewContent as view-content.component
|
||||
participant SendAccess as send-access API
|
||||
|
||||
Visitor->>TryAccess: Navigate to send URL
|
||||
activate TryAccess
|
||||
TryAccess->>SendToken: Request anonymous access token
|
||||
SendToken-->>TryAccess: OK + Security token
|
||||
TryAccess->>ViewContent: Redirect with token
|
||||
deactivate TryAccess
|
||||
activate ViewContent
|
||||
ViewContent->>SendAccess: Request send content (with token and key)
|
||||
SendAccess-->>ViewContent: Return send content
|
||||
ViewContent->>Visitor: Display send content
|
||||
deactivate ViewContent
|
||||
```
|
||||
|
||||
## Password Protected Sends
|
||||
|
||||
Password protected sends redirect to a password challenge prompt.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Visitor
|
||||
participant TryAccess as try-send-access.guard
|
||||
participant PasswordAuth as password-authentication.component
|
||||
participant SendToken as send-token API
|
||||
participant ViewContent as view-content.component
|
||||
participant SendAccess as send-access API
|
||||
|
||||
Visitor->>TryAccess: Navigate to send URL
|
||||
activate TryAccess
|
||||
TryAccess->>SendToken: Request anonymous access token
|
||||
SendToken-->>TryAccess: Unauthorized + Password challenge
|
||||
TryAccess->>PasswordAuth: Redirect with send ID and key
|
||||
deactivate TryAccess
|
||||
activate PasswordAuth
|
||||
PasswordAuth->>Visitor: Request password
|
||||
Visitor-->>PasswordAuth: Enter password
|
||||
PasswordAuth->>SendToken: Request access token (with password)
|
||||
SendToken-->>PasswordAuth: OK + Security token
|
||||
deactivate PasswordAuth
|
||||
activate ViewContent
|
||||
PasswordAuth->>ViewContent: Redirect with token and send key
|
||||
ViewContent->>SendAccess: Request send content (with token)
|
||||
SendAccess-->>ViewContent: Return send content
|
||||
ViewContent->>Visitor: Display send content
|
||||
deactivate ViewContent
|
||||
```
|
||||
|
||||
## Send Access without token
|
||||
|
||||
Visiting the view page without a token redirects to a try-access flow, above.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Visitor
|
||||
participant ViewContent as view-content.component
|
||||
participant TryAccess as try-send-access.guard
|
||||
|
||||
Visitor->>ViewContent: Navigate to send URL (with id and key)
|
||||
ViewContent->>TryAccess: Redirect to try-access (with id and key)
|
||||
```
|
||||
@@ -1,175 +0,0 @@
|
||||
import { TestBed, fakeAsync, tick } from "@angular/core/testing";
|
||||
import { Router, UrlTree } from "@angular/router";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
import { firstValueFrom, NEVER } from "rxjs";
|
||||
|
||||
import { ErrorResponse } from "@bitwarden/common/models/response/error.response";
|
||||
import { StateProvider } from "@bitwarden/common/platform/state";
|
||||
import { mockAccountServiceWith, FakeStateProvider } from "@bitwarden/common/spec";
|
||||
import { SemanticLogger } from "@bitwarden/common/tools/log";
|
||||
import { SystemServiceProvider } from "@bitwarden/common/tools/providers";
|
||||
import { SendApiService } from "@bitwarden/common/tools/send/services/send-api.service.abstraction";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { SYSTEM_SERVICE_PROVIDER } from "@bitwarden/generator-components";
|
||||
|
||||
import { DefaultSendAccessService } from "./default-send-access-service";
|
||||
import { SEND_RESPONSE_KEY, SEND_CONTEXT_KEY } from "./send-access-memory";
|
||||
|
||||
describe("DefaultSendAccessService", () => {
|
||||
let service: DefaultSendAccessService;
|
||||
let stateProvider: FakeStateProvider;
|
||||
let sendApiService: MockProxy<SendApiService>;
|
||||
let router: MockProxy<Router>;
|
||||
let logger: MockProxy<SemanticLogger>;
|
||||
let systemServiceProvider: MockProxy<SystemServiceProvider>;
|
||||
|
||||
beforeEach(() => {
|
||||
const accountService = mockAccountServiceWith("user-id" as UserId);
|
||||
stateProvider = new FakeStateProvider(accountService);
|
||||
sendApiService = mock<SendApiService>();
|
||||
router = mock<Router>();
|
||||
logger = mock<SemanticLogger>();
|
||||
systemServiceProvider = mock<SystemServiceProvider>();
|
||||
|
||||
systemServiceProvider.log.mockReturnValue(logger);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
DefaultSendAccessService,
|
||||
{ provide: StateProvider, useValue: stateProvider },
|
||||
{ provide: SendApiService, useValue: sendApiService },
|
||||
{ provide: Router, useValue: router },
|
||||
{ provide: SYSTEM_SERVICE_PROVIDER, useValue: systemServiceProvider },
|
||||
],
|
||||
});
|
||||
|
||||
service = TestBed.inject(DefaultSendAccessService);
|
||||
});
|
||||
|
||||
describe("constructor", () => {
|
||||
it("creates logger with type 'SendAccessAuthenticationService' when initialized", () => {
|
||||
expect(systemServiceProvider.log).toHaveBeenCalledWith({
|
||||
type: "SendAccessAuthenticationService",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("redirect$", () => {
|
||||
const sendId = "test-send-id";
|
||||
|
||||
it("returns content page UrlTree and logs info when API returns success", async () => {
|
||||
const expectedUrlTree = { toString: () => "/send/content/test-send-id" } as UrlTree;
|
||||
sendApiService.postSendAccess.mockResolvedValue({} as any);
|
||||
router.createUrlTree.mockReturnValue(expectedUrlTree);
|
||||
|
||||
const result = await firstValueFrom(service.redirect$(sendId));
|
||||
|
||||
expect(result).toBe(expectedUrlTree);
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
"public send detected; redirecting to send access with token.",
|
||||
);
|
||||
});
|
||||
|
||||
describe("given error responses", () => {
|
||||
it("returns password flow UrlTree and logs debug when 401 received", async () => {
|
||||
const expectedUrlTree = { toString: () => "/send/test-send-id" } as UrlTree;
|
||||
const errorResponse = new ErrorResponse([], 401);
|
||||
sendApiService.postSendAccess.mockRejectedValue(errorResponse);
|
||||
router.createUrlTree.mockReturnValue(expectedUrlTree);
|
||||
|
||||
const result = await firstValueFrom(service.redirect$(sendId));
|
||||
|
||||
expect(result).toBe(expectedUrlTree);
|
||||
expect(logger.debug).toHaveBeenCalledWith(errorResponse, "redirecting to password flow");
|
||||
});
|
||||
|
||||
it("returns 404 page UrlTree and logs debug when 404 received", async () => {
|
||||
const expectedUrlTree = { toString: () => "/404.html" } as UrlTree;
|
||||
const errorResponse = new ErrorResponse([], 404);
|
||||
sendApiService.postSendAccess.mockRejectedValue(errorResponse);
|
||||
router.parseUrl.mockReturnValue(expectedUrlTree);
|
||||
|
||||
const result = await firstValueFrom(service.redirect$(sendId));
|
||||
|
||||
expect(result).toBe(expectedUrlTree);
|
||||
expect(logger.debug).toHaveBeenCalledWith(errorResponse, "redirecting to unavailable page");
|
||||
});
|
||||
|
||||
it("logs warning and throws error when 500 received", async () => {
|
||||
const errorResponse = new ErrorResponse([], 500);
|
||||
sendApiService.postSendAccess.mockRejectedValue(errorResponse);
|
||||
|
||||
await expect(firstValueFrom(service.redirect$(sendId))).rejects.toBe(errorResponse);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
errorResponse,
|
||||
"received unexpected error response",
|
||||
);
|
||||
});
|
||||
|
||||
it("throws error when unexpected error code received", async () => {
|
||||
const errorResponse = new ErrorResponse([], 403);
|
||||
sendApiService.postSendAccess.mockRejectedValue(errorResponse);
|
||||
|
||||
await expect(firstValueFrom(service.redirect$(sendId))).rejects.toBe(errorResponse);
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
errorResponse,
|
||||
"received unexpected error response",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("throws error when non-ErrorResponse error occurs", async () => {
|
||||
const regularError = new Error("Network error");
|
||||
sendApiService.postSendAccess.mockRejectedValue(regularError);
|
||||
|
||||
await expect(firstValueFrom(service.redirect$(sendId))).rejects.toThrow("Network error");
|
||||
expect(logger.warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("emits timeout error when API response exceeds 10 seconds", fakeAsync(() => {
|
||||
// Mock API to never resolve (simulating a hung request)
|
||||
sendApiService.postSendAccess.mockReturnValue(firstValueFrom(NEVER));
|
||||
|
||||
const result$ = service.redirect$(sendId);
|
||||
let error: any;
|
||||
|
||||
result$.subscribe({
|
||||
error: (err: unknown) => (error = err),
|
||||
});
|
||||
|
||||
// Advance time past 10 seconds
|
||||
tick(10001);
|
||||
|
||||
expect(error).toBeDefined();
|
||||
expect(error.name).toBe("TimeoutError");
|
||||
}));
|
||||
});
|
||||
|
||||
describe("setContext", () => {
|
||||
it("updates global state with send context when called with sendId and key", async () => {
|
||||
const sendId = "test-send-id";
|
||||
const key = "test-key";
|
||||
|
||||
await service.setContext(sendId, key);
|
||||
|
||||
const context = await firstValueFrom(stateProvider.getGlobal(SEND_CONTEXT_KEY).state$);
|
||||
expect(context).toEqual({ id: sendId, key });
|
||||
});
|
||||
});
|
||||
|
||||
describe("clear", () => {
|
||||
it("sets both SEND_RESPONSE_KEY and SEND_CONTEXT_KEY to null when called", async () => {
|
||||
// Set initial values
|
||||
await stateProvider.getGlobal(SEND_RESPONSE_KEY).update(() => ({ some: "response" }) as any);
|
||||
await stateProvider.getGlobal(SEND_CONTEXT_KEY).update(() => ({ id: "test", key: "test" }));
|
||||
|
||||
await service.clear();
|
||||
|
||||
const response = await firstValueFrom(stateProvider.getGlobal(SEND_RESPONSE_KEY).state$);
|
||||
const context = await firstValueFrom(stateProvider.getGlobal(SEND_CONTEXT_KEY).state$);
|
||||
|
||||
expect(response).toBeNull();
|
||||
expect(context).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,96 +0,0 @@
|
||||
import { Injectable, Inject } from "@angular/core";
|
||||
import { Router, UrlTree } from "@angular/router";
|
||||
import { map, of, from, catchError, timeout } from "rxjs";
|
||||
|
||||
import { ErrorResponse } from "@bitwarden/common/models/response/error.response";
|
||||
import { StateProvider } from "@bitwarden/common/platform/state";
|
||||
import { SemanticLogger } from "@bitwarden/common/tools/log";
|
||||
import { SystemServiceProvider } from "@bitwarden/common/tools/providers";
|
||||
import { SendAccessRequest } from "@bitwarden/common/tools/send/models/request/send-access.request";
|
||||
import { SendApiService } from "@bitwarden/common/tools/send/services/send-api.service.abstraction";
|
||||
import { SYSTEM_SERVICE_PROVIDER } from "@bitwarden/generator-components";
|
||||
|
||||
import { SEND_RESPONSE_KEY, SEND_CONTEXT_KEY } from "./send-access-memory";
|
||||
import { SendAccessService } from "./send-access-service.abstraction";
|
||||
import { isErrorResponse } from "./util";
|
||||
|
||||
const TEN_SECONDS = 10_000;
|
||||
|
||||
@Injectable({ providedIn: "root" })
|
||||
export class DefaultSendAccessService implements SendAccessService {
|
||||
private readonly logger: SemanticLogger;
|
||||
|
||||
constructor(
|
||||
private readonly state: StateProvider,
|
||||
private readonly api: SendApiService,
|
||||
private readonly router: Router,
|
||||
@Inject(SYSTEM_SERVICE_PROVIDER) system: SystemServiceProvider,
|
||||
) {
|
||||
this.logger = system.log({ type: "SendAccessAuthenticationService" });
|
||||
}
|
||||
|
||||
redirect$(sendId: string) {
|
||||
// FIXME: when the send authentication APIs become available, this method
|
||||
// should delegate to the API
|
||||
const response$ = from(this.api.postSendAccess(sendId, new SendAccessRequest()));
|
||||
|
||||
const redirect$ = response$.pipe(
|
||||
timeout({ first: TEN_SECONDS }),
|
||||
map((_response) => {
|
||||
this.logger.info("public send detected; redirecting to send access with token.");
|
||||
const url = this.toViewRedirect(sendId);
|
||||
|
||||
return url;
|
||||
}),
|
||||
catchError((error: unknown) => {
|
||||
let processed: UrlTree | undefined = undefined;
|
||||
|
||||
if (isErrorResponse(error)) {
|
||||
processed = this.toErrorRedirect(sendId, error);
|
||||
}
|
||||
|
||||
if (processed) {
|
||||
return of(processed);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}),
|
||||
);
|
||||
|
||||
return redirect$;
|
||||
}
|
||||
|
||||
private toViewRedirect(sendId: string) {
|
||||
return this.router.createUrlTree(["send", "content", sendId]);
|
||||
}
|
||||
|
||||
private toErrorRedirect(sendId: string, response: ErrorResponse) {
|
||||
let url: UrlTree | undefined = undefined;
|
||||
|
||||
switch (response.statusCode) {
|
||||
case 401:
|
||||
this.logger.debug(response, "redirecting to password flow");
|
||||
url = this.router.createUrlTree(["send/password", sendId]);
|
||||
break;
|
||||
|
||||
case 404:
|
||||
this.logger.debug(response, "redirecting to unavailable page");
|
||||
url = this.router.parseUrl("/404.html");
|
||||
break;
|
||||
|
||||
default:
|
||||
this.logger.warn(response, "received unexpected error response");
|
||||
}
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
async setContext(sendId: string, key: string) {
|
||||
await this.state.getGlobal(SEND_CONTEXT_KEY).update(() => ({ id: sendId, key }));
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
await this.state.getGlobal(SEND_RESPONSE_KEY).update(() => null);
|
||||
await this.state.getGlobal(SEND_CONTEXT_KEY).update(() => null);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,2 @@
|
||||
export { AccessComponent } from "./access.component";
|
||||
export { SendAccessExplainerComponent } from "./send-access-explainer.component";
|
||||
|
||||
export { SendAccessRoutes } from "./routes";
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import { Routes } from "@angular/router";
|
||||
|
||||
import { ActiveSendIcon } from "@bitwarden/assets/svg";
|
||||
import { AnonLayoutWrapperData } from "@bitwarden/components";
|
||||
|
||||
import { RouteDataProperties } from "../../../core";
|
||||
|
||||
import { SendAccessExplainerComponent } from "./send-access-explainer.component";
|
||||
import { SendAccessPasswordComponent } from "./send-access-password.component";
|
||||
import { trySendAccess } from "./try-send-access.guard";
|
||||
|
||||
/** Routes to reach send access screens */
|
||||
export const SendAccessRoutes: Routes = [
|
||||
{
|
||||
path: "send/:sendId",
|
||||
// there are no child pages because `trySendAccess` always performs a redirect
|
||||
canActivate: [trySendAccess],
|
||||
},
|
||||
{
|
||||
path: "send/password/:sendId",
|
||||
data: {
|
||||
pageTitle: {
|
||||
key: "sendAccessPasswordTitle",
|
||||
},
|
||||
pageIcon: ActiveSendIcon,
|
||||
showReadonlyHostname: true,
|
||||
} satisfies RouteDataProperties & AnonLayoutWrapperData,
|
||||
children: [
|
||||
{
|
||||
path: "",
|
||||
component: SendAccessPasswordComponent,
|
||||
},
|
||||
{
|
||||
path: "",
|
||||
outlet: "secondary",
|
||||
component: SendAccessExplainerComponent,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: "send/content/:sendId",
|
||||
data: {
|
||||
pageTitle: {
|
||||
key: "sendAccessContentTitle",
|
||||
},
|
||||
pageIcon: ActiveSendIcon,
|
||||
showReadonlyHostname: true,
|
||||
} satisfies RouteDataProperties & AnonLayoutWrapperData,
|
||||
children: [
|
||||
{
|
||||
path: "send/password/:sendId",
|
||||
},
|
||||
{
|
||||
path: "",
|
||||
outlet: "secondary",
|
||||
component: SendAccessExplainerComponent,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -1,50 +0,0 @@
|
||||
import { KeyDefinition, SEND_ACCESS_AUTH_MEMORY } from "@bitwarden/common/platform/state";
|
||||
import { SendAccessResponse } from "@bitwarden/common/tools/send/models/response/send-access.response";
|
||||
|
||||
import { SEND_CONTEXT_KEY, SEND_RESPONSE_KEY } from "./send-access-memory";
|
||||
import { SendContext } from "./types";
|
||||
|
||||
describe("send-access-memory", () => {
|
||||
describe("SEND_CONTEXT_KEY", () => {
|
||||
it("has correct state definition properties", () => {
|
||||
expect(SEND_CONTEXT_KEY).toBeInstanceOf(KeyDefinition);
|
||||
expect(SEND_CONTEXT_KEY.stateDefinition).toBe(SEND_ACCESS_AUTH_MEMORY);
|
||||
expect(SEND_CONTEXT_KEY.key).toBe("sendContext");
|
||||
});
|
||||
|
||||
it("deserializes data as-is", () => {
|
||||
const testContext: SendContext = { id: "test-id", key: "test-key" };
|
||||
const deserializer = SEND_CONTEXT_KEY.deserializer;
|
||||
expect(deserializer(testContext)).toBe(testContext);
|
||||
});
|
||||
|
||||
it("deserializes null as null", () => {
|
||||
const deserializer = SEND_CONTEXT_KEY.deserializer;
|
||||
expect(deserializer(null)).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("SEND_RESPONSE_KEY", () => {
|
||||
it("has correct state definition properties", () => {
|
||||
expect(SEND_RESPONSE_KEY).toBeInstanceOf(KeyDefinition);
|
||||
expect(SEND_RESPONSE_KEY.stateDefinition).toBe(SEND_ACCESS_AUTH_MEMORY);
|
||||
expect(SEND_RESPONSE_KEY.key).toBe("sendResponse");
|
||||
});
|
||||
|
||||
it("deserializes data into SendAccessResponse instance", () => {
|
||||
const mockData = { id: "test-id", name: "test-send" } as any;
|
||||
const deserializer = SEND_RESPONSE_KEY.deserializer;
|
||||
const result = deserializer(mockData);
|
||||
|
||||
expect(result).toBeInstanceOf(SendAccessResponse);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[null, "null"],
|
||||
[undefined, "undefined"],
|
||||
])("deserializes %s as null", (value, _) => {
|
||||
const deserializer = SEND_RESPONSE_KEY.deserializer;
|
||||
expect(deserializer(value!)).toBe(null);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
import { KeyDefinition, SEND_ACCESS_AUTH_MEMORY } from "@bitwarden/common/platform/state";
|
||||
import { SendAccessResponse } from "@bitwarden/common/tools/send/models/response/send-access.response";
|
||||
|
||||
import { SendContext } from "./types";
|
||||
|
||||
export const SEND_CONTEXT_KEY = new KeyDefinition<SendContext | null>(
|
||||
SEND_ACCESS_AUTH_MEMORY,
|
||||
"sendContext",
|
||||
{
|
||||
deserializer: (data) => data,
|
||||
},
|
||||
);
|
||||
|
||||
/** When send authentication succeeds, this stores the result so that
|
||||
* multiple access attempts don't accrue due to the send workflow.
|
||||
*/
|
||||
// FIXME: replace this with the send authentication token once it's
|
||||
// available
|
||||
export const SEND_RESPONSE_KEY = new KeyDefinition<SendAccessResponse | null>(
|
||||
SEND_ACCESS_AUTH_MEMORY,
|
||||
"sendResponse",
|
||||
{
|
||||
deserializer: (data) => (data ? new SendAccessResponse(data) : null),
|
||||
},
|
||||
);
|
||||
@@ -1,10 +0,0 @@
|
||||
import { UrlTree } from "@angular/router";
|
||||
import { Observable } from "rxjs";
|
||||
|
||||
export abstract class SendAccessService {
|
||||
abstract redirect$: (sendId: string) => Observable<UrlTree>;
|
||||
|
||||
abstract setContext: (sendId: string, key: string) => Promise<void>;
|
||||
|
||||
abstract clear: () => Promise<void>;
|
||||
}
|
||||
@@ -1,426 +0,0 @@
|
||||
import { TestBed } from "@angular/core/testing";
|
||||
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from "@angular/router";
|
||||
import { firstValueFrom, Observable, of } from "rxjs";
|
||||
|
||||
import { SemanticLogger } from "@bitwarden/common/tools/log";
|
||||
import { SystemServiceProvider } from "@bitwarden/common/tools/providers";
|
||||
import { SYSTEM_SERVICE_PROVIDER } from "@bitwarden/generator-components";
|
||||
|
||||
import { SendAccessService } from "./send-access-service.abstraction";
|
||||
import { trySendAccess } from "./try-send-access.guard";
|
||||
|
||||
function createMockRoute(params: Record<string, any>): ActivatedRouteSnapshot {
|
||||
return { params } as ActivatedRouteSnapshot;
|
||||
}
|
||||
|
||||
function createMockLogger(): SemanticLogger {
|
||||
return {
|
||||
warn: jest.fn(),
|
||||
panic: jest.fn().mockImplementation(() => {
|
||||
throw new Error("Logger panic called");
|
||||
}),
|
||||
} as any as SemanticLogger;
|
||||
}
|
||||
|
||||
function createMockSystemServiceProvider(): SystemServiceProvider {
|
||||
return {
|
||||
log: jest.fn().mockReturnValue(createMockLogger()),
|
||||
} as any as SystemServiceProvider;
|
||||
}
|
||||
|
||||
function createMockSendAccessService() {
|
||||
return {
|
||||
setContext: jest.fn().mockResolvedValue(undefined),
|
||||
redirect$: jest.fn().mockReturnValue(of({} as UrlTree)),
|
||||
clear: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
}
|
||||
|
||||
describe("trySendAccess", () => {
|
||||
let mockSendAccessService: ReturnType<typeof createMockSendAccessService>;
|
||||
let mockSystemServiceProvider: SystemServiceProvider;
|
||||
let mockRouterState: RouterStateSnapshot;
|
||||
|
||||
beforeEach(() => {
|
||||
mockSendAccessService = createMockSendAccessService();
|
||||
mockSystemServiceProvider = createMockSystemServiceProvider();
|
||||
mockRouterState = {} as RouterStateSnapshot;
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{ provide: SendAccessService, useValue: mockSendAccessService },
|
||||
{ provide: SYSTEM_SERVICE_PROVIDER, useValue: mockSystemServiceProvider },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("canActivate", () => {
|
||||
describe("given valid route parameters", () => {
|
||||
it("extracts sendId and key from route params when both are valid strings", async () => {
|
||||
const sendId = "test-send-id";
|
||||
const key = "test-key";
|
||||
const mockRoute = createMockRoute({ sendId, key });
|
||||
const expectedUrlTree = { toString: () => "/test-url" } as UrlTree;
|
||||
mockSendAccessService.redirect$.mockReturnValue(of(expectedUrlTree));
|
||||
|
||||
// need to cast the result because `CanActivateFn` performs type erasure
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
|
||||
expect(mockSendAccessService.setContext).toHaveBeenCalledWith(sendId, key);
|
||||
expect(mockSendAccessService.setContext).toHaveBeenCalledTimes(1);
|
||||
await expect(firstValueFrom(result$)).resolves.toEqual(expectedUrlTree);
|
||||
});
|
||||
|
||||
it("does not throw validation errors when sendId and key are valid strings", async () => {
|
||||
const sendId = "valid-send-id";
|
||||
const key = "valid-key";
|
||||
const mockRoute = createMockRoute({ sendId, key });
|
||||
const expectedUrlTree = { toString: () => "/test-url" } as UrlTree;
|
||||
mockSendAccessService.redirect$.mockReturnValue(of(expectedUrlTree));
|
||||
|
||||
// Should not throw any errors during guard execution
|
||||
let guardResult: Observable<UrlTree> | undefined;
|
||||
expect(() => {
|
||||
guardResult = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
}).not.toThrow();
|
||||
|
||||
// Verify the observable can be subscribed to without errors
|
||||
expect(guardResult).toBeDefined();
|
||||
await expect(firstValueFrom(guardResult!)).resolves.toEqual(expectedUrlTree);
|
||||
|
||||
// Logger methods should not be called for warnings or panics
|
||||
const mockLogger = (mockSystemServiceProvider.log as jest.Mock).mock.results[0].value;
|
||||
expect(mockLogger.warn).not.toHaveBeenCalled();
|
||||
expect(mockLogger.panic).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("given invalid route parameters", () => {
|
||||
describe("given invalid sendId", () => {
|
||||
it.each([
|
||||
["undefined", undefined],
|
||||
["null", null],
|
||||
])(
|
||||
"logs warning with correct message when sendId is %s",
|
||||
async (description, sendIdValue) => {
|
||||
const key = "valid-key";
|
||||
const mockRoute = createMockRoute(
|
||||
sendIdValue === undefined ? { key } : { sendId: sendIdValue, key },
|
||||
);
|
||||
const mockLogger = createMockLogger();
|
||||
(mockSystemServiceProvider.log as jest.Mock).mockReturnValue(mockLogger);
|
||||
|
||||
await expect(async () => {
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
await firstValueFrom(result$);
|
||||
}).rejects.toThrow("Logger panic called");
|
||||
|
||||
expect(mockSystemServiceProvider.log).toHaveBeenCalledWith({
|
||||
function: "trySendAccess",
|
||||
});
|
||||
expect(mockLogger.warn).toHaveBeenCalledWith(
|
||||
"sendId missing from the route parameters; redirecting to 404",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["number", 123],
|
||||
["object", {}],
|
||||
["boolean", true],
|
||||
])("logs panic with expected/actual type info when sendId is %s", async (type, value) => {
|
||||
const key = "valid-key";
|
||||
const mockRoute = createMockRoute({ sendId: value, key });
|
||||
const mockLogger = createMockLogger();
|
||||
(mockSystemServiceProvider.log as jest.Mock).mockReturnValue(mockLogger);
|
||||
|
||||
await expect(async () => {
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
await firstValueFrom(result$);
|
||||
}).rejects.toThrow("Logger panic called");
|
||||
|
||||
expect(mockSystemServiceProvider.log).toHaveBeenCalledWith({ function: "trySendAccess" });
|
||||
expect(mockLogger.panic).toHaveBeenCalledWith(
|
||||
{ expected: "string", actual: type },
|
||||
"sendId has invalid type",
|
||||
);
|
||||
});
|
||||
|
||||
it("throws when sendId is not a string", async () => {
|
||||
const key = "valid-key";
|
||||
const invalidSendIdValues = [123, {}, true, null, undefined];
|
||||
|
||||
for (const invalidSendId of invalidSendIdValues) {
|
||||
const mockRoute = createMockRoute(
|
||||
invalidSendId === undefined ? { key } : { sendId: invalidSendId, key },
|
||||
);
|
||||
const mockLogger = createMockLogger();
|
||||
(mockSystemServiceProvider.log as jest.Mock).mockReturnValue(mockLogger);
|
||||
|
||||
await expect(async () => {
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
await firstValueFrom(result$);
|
||||
}).rejects.toThrow("Logger panic called");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("given invalid key", () => {
|
||||
it.each([
|
||||
["undefined", undefined],
|
||||
["null", null],
|
||||
])("logs panic with correct message when key is %s", async (description, keyValue) => {
|
||||
const sendId = "valid-send-id";
|
||||
const mockRoute = createMockRoute(
|
||||
keyValue === undefined ? { sendId } : { sendId, key: keyValue },
|
||||
);
|
||||
const mockLogger = createMockLogger();
|
||||
(mockSystemServiceProvider.log as jest.Mock).mockReturnValue(mockLogger);
|
||||
|
||||
await expect(async () => {
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
await firstValueFrom(result$);
|
||||
}).rejects.toThrow("Logger panic called");
|
||||
|
||||
expect(mockSystemServiceProvider.log).toHaveBeenCalledWith({ function: "trySendAccess" });
|
||||
expect(mockLogger.panic).toHaveBeenCalledWith("key missing from the route parameters");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["number", 123],
|
||||
["object", {}],
|
||||
["boolean", true],
|
||||
])("logs panic with expected/actual type info when key is %s", async (type, value) => {
|
||||
const sendId = "valid-send-id";
|
||||
const mockRoute = createMockRoute({ sendId, key: value });
|
||||
const mockLogger = createMockLogger();
|
||||
(mockSystemServiceProvider.log as jest.Mock).mockReturnValue(mockLogger);
|
||||
|
||||
await expect(async () => {
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
await firstValueFrom(result$);
|
||||
}).rejects.toThrow("Logger panic called");
|
||||
|
||||
expect(mockSystemServiceProvider.log).toHaveBeenCalledWith({ function: "trySendAccess" });
|
||||
expect(mockLogger.panic).toHaveBeenCalledWith(
|
||||
{ expected: "string", actual: type },
|
||||
"key has invalid type",
|
||||
);
|
||||
});
|
||||
|
||||
it("throws when key is not a string", async () => {
|
||||
const sendId = "valid-send-id";
|
||||
const invalidKeyValues = [123, {}, true, null, undefined];
|
||||
|
||||
for (const invalidKey of invalidKeyValues) {
|
||||
const mockRoute = createMockRoute(
|
||||
invalidKey === undefined ? { sendId } : { sendId, key: invalidKey },
|
||||
);
|
||||
const mockLogger = createMockLogger();
|
||||
(mockSystemServiceProvider.log as jest.Mock).mockReturnValue(mockLogger);
|
||||
|
||||
await expect(async () => {
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
await firstValueFrom(result$);
|
||||
}).rejects.toThrow("Logger panic called");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("given service interactions", () => {
|
||||
it("calls setContext with extracted sendId and key when parameters are valid", async () => {
|
||||
const sendId = "test-send-id";
|
||||
const key = "test-key";
|
||||
const mockRoute = createMockRoute({ sendId, key });
|
||||
const expectedUrlTree = { toString: () => "/test-url" } as UrlTree;
|
||||
mockSendAccessService.redirect$.mockReturnValue(of(expectedUrlTree));
|
||||
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
|
||||
await firstValueFrom(result$);
|
||||
|
||||
expect(mockSendAccessService.setContext).toHaveBeenCalledWith(sendId, key);
|
||||
expect(mockSendAccessService.setContext).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls redirect$ with extracted sendId when setContext completes", async () => {
|
||||
const sendId = "test-send-id";
|
||||
const key = "test-key";
|
||||
const mockRoute = createMockRoute({ sendId, key });
|
||||
const expectedUrlTree = { toString: () => "/test-url" } as UrlTree;
|
||||
mockSendAccessService.redirect$.mockReturnValue(of(expectedUrlTree));
|
||||
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
|
||||
await firstValueFrom(result$);
|
||||
|
||||
expect(mockSendAccessService.redirect$).toHaveBeenCalledWith(sendId);
|
||||
expect(mockSendAccessService.redirect$).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("given observable behavior", () => {
|
||||
it("returns redirect$ emissions when setContext completes successfully", async () => {
|
||||
const sendId = "test-send-id";
|
||||
const key = "test-key";
|
||||
const mockRoute = createMockRoute({ sendId, key });
|
||||
const expectedUrlTree = { toString: () => "/test-url" } as UrlTree;
|
||||
mockSendAccessService.redirect$.mockReturnValue(of(expectedUrlTree));
|
||||
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
|
||||
const actualResult = await firstValueFrom(result$);
|
||||
|
||||
expect(actualResult).toEqual(expectedUrlTree);
|
||||
expect(mockSendAccessService.redirect$).toHaveBeenCalledWith(sendId);
|
||||
});
|
||||
|
||||
it("does not emit setContext values when using ignoreElements", async () => {
|
||||
const sendId = "test-send-id";
|
||||
const key = "test-key";
|
||||
const mockRoute = createMockRoute({ sendId, key });
|
||||
const expectedUrlTree = { toString: () => "/test-url" } as UrlTree;
|
||||
const setContextValue = "should-not-be-emitted";
|
||||
|
||||
// Mock setContext to return a value
|
||||
mockSendAccessService.setContext.mockResolvedValue(setContextValue);
|
||||
mockSendAccessService.redirect$.mockReturnValue(of(expectedUrlTree));
|
||||
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
|
||||
const actualResult = await firstValueFrom(result$);
|
||||
|
||||
// Should only emit the redirect$ value, not the setContext value
|
||||
expect(actualResult).toEqual(expectedUrlTree);
|
||||
expect(actualResult).not.toEqual(setContextValue);
|
||||
});
|
||||
|
||||
it("ensures setContext completes before redirect$ executes (sequencing)", async () => {
|
||||
const sendId = "test-send-id";
|
||||
const key = "test-key";
|
||||
const mockRoute = createMockRoute({ sendId, key });
|
||||
const expectedUrlTree = { toString: () => "/test-url" } as UrlTree;
|
||||
|
||||
let setContextResolved = false;
|
||||
|
||||
// Mock setContext to track when it resolves
|
||||
mockSendAccessService.setContext.mockImplementation(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10)); // Small delay
|
||||
setContextResolved = true;
|
||||
});
|
||||
|
||||
// Mock redirect$ to return a delayed observable and check if setContext resolved
|
||||
mockSendAccessService.redirect$.mockImplementation((id) => {
|
||||
return new Observable((subscriber) => {
|
||||
// Check if setContext has resolved when redirect$ subscription starts
|
||||
setTimeout(() => {
|
||||
expect(setContextResolved).toBe(true);
|
||||
subscriber.next(expectedUrlTree);
|
||||
subscriber.complete();
|
||||
}, 0);
|
||||
});
|
||||
});
|
||||
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
|
||||
await firstValueFrom(result$);
|
||||
});
|
||||
});
|
||||
|
||||
describe("given error scenarios", () => {
|
||||
it("does not call redirect$ when setContext rejects", async () => {
|
||||
const sendId = "test-send-id";
|
||||
const key = "test-key";
|
||||
const mockRoute = createMockRoute({ sendId, key });
|
||||
const setContextError = new Error("setContext failed");
|
||||
|
||||
// Reset mocks to ensure clean state
|
||||
jest.clearAllMocks();
|
||||
|
||||
// Mock setContext to reject
|
||||
mockSendAccessService.setContext.mockRejectedValue(setContextError);
|
||||
|
||||
// Create a mock observable that we can spy on subscription
|
||||
const mockRedirectObservable = of({} as UrlTree);
|
||||
const subscribeSpy = jest.spyOn(mockRedirectObservable, "subscribe");
|
||||
mockSendAccessService.redirect$.mockReturnValue(mockRedirectObservable);
|
||||
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
|
||||
// Expect the observable to reject when setContext fails
|
||||
await expect(firstValueFrom(result$)).rejects.toThrow("setContext failed");
|
||||
|
||||
// The redirect$ method will be called (since it's called synchronously)
|
||||
expect(mockSendAccessService.redirect$).toHaveBeenCalledWith(sendId);
|
||||
|
||||
// But the returned observable should not be subscribed to due to the error
|
||||
// Note: This test verifies the error propagation behavior
|
||||
expect(subscribeSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("propagates error to guard return value when redirect$ throws", async () => {
|
||||
const sendId = "test-send-id";
|
||||
const key = "test-key";
|
||||
const mockRoute = createMockRoute({ sendId, key });
|
||||
const redirectError = new Error("redirect$ failed");
|
||||
|
||||
// Reset mocks to ensure clean state
|
||||
jest.clearAllMocks();
|
||||
|
||||
// Mock setContext to succeed and redirect$ to throw
|
||||
mockSendAccessService.setContext.mockResolvedValue(undefined);
|
||||
mockSendAccessService.redirect$.mockReturnValue(
|
||||
new Observable((subscriber) => {
|
||||
subscriber.error(redirectError);
|
||||
}),
|
||||
);
|
||||
|
||||
const result$ = TestBed.runInInjectionContext(() =>
|
||||
trySendAccess(mockRoute, mockRouterState),
|
||||
) as unknown as Observable<UrlTree>;
|
||||
|
||||
// Expect the observable to propagate the redirect$ error
|
||||
await expect(firstValueFrom(result$)).rejects.toThrow("redirect$ failed");
|
||||
|
||||
// Verify that setContext was called (should succeed)
|
||||
expect(mockSendAccessService.setContext).toHaveBeenCalledWith(sendId, key);
|
||||
|
||||
// Verify that redirect$ was called (but it throws)
|
||||
expect(mockSendAccessService.redirect$).toHaveBeenCalledWith(sendId);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
import { inject } from "@angular/core";
|
||||
import { ActivatedRouteSnapshot, CanActivateFn, RouterStateSnapshot } from "@angular/router";
|
||||
import { from, ignoreElements, concat } from "rxjs";
|
||||
|
||||
import { SystemServiceProvider } from "@bitwarden/common/tools/providers";
|
||||
import { SYSTEM_SERVICE_PROVIDER } from "@bitwarden/generator-components";
|
||||
|
||||
import { SendAccessService } from "./send-access-service.abstraction";
|
||||
|
||||
export const trySendAccess: CanActivateFn = (
|
||||
route: ActivatedRouteSnapshot,
|
||||
_state: RouterStateSnapshot,
|
||||
) => {
|
||||
const sendAccess = inject(SendAccessService);
|
||||
const system = inject<SystemServiceProvider>(SYSTEM_SERVICE_PROVIDER);
|
||||
const logger = system.log({ function: "trySendAccess" });
|
||||
|
||||
const { sendId, key } = route.params;
|
||||
if (!sendId) {
|
||||
logger.warn("sendId missing from the route parameters; redirecting to 404");
|
||||
}
|
||||
if (typeof sendId !== "string") {
|
||||
logger.panic({ expected: "string", actual: typeof sendId }, "sendId has invalid type");
|
||||
}
|
||||
|
||||
if (!key) {
|
||||
logger.panic("key missing from the route parameters");
|
||||
}
|
||||
if (typeof key !== "string") {
|
||||
logger.panic({ expected: "string", actual: typeof key }, "key has invalid type");
|
||||
}
|
||||
|
||||
const contextUpdated$ = from(sendAccess.setContext(sendId, key)).pipe(ignoreElements());
|
||||
const redirect$ = sendAccess.redirect$(sendId);
|
||||
|
||||
// ensure the key has loaded before redirecting
|
||||
return concat(contextUpdated$, redirect$);
|
||||
};
|
||||
@@ -1,8 +0,0 @@
|
||||
/** global contextual information for the current send access page. */
|
||||
export type SendContext = {
|
||||
/** identifies the send */
|
||||
id: string;
|
||||
|
||||
/** decrypts the send content */
|
||||
key: string;
|
||||
};
|
||||
@@ -1,69 +0,0 @@
|
||||
import { ErrorResponse } from "@bitwarden/common/models/response/error.response";
|
||||
|
||||
import { isErrorResponse, isSendContext } from "./util";
|
||||
|
||||
describe("util", () => {
|
||||
describe("isErrorResponse", () => {
|
||||
it("returns true when value is an ErrorResponse instance", () => {
|
||||
const error = new ErrorResponse(["Error message"], 400);
|
||||
expect(isErrorResponse(error)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[null, "null"],
|
||||
[undefined, "undefined"],
|
||||
])("returns false when value is %s", (value, description) => {
|
||||
expect(isErrorResponse(value)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["string", "string"],
|
||||
[123, "number"],
|
||||
[true, "boolean"],
|
||||
[{}, "plain object"],
|
||||
[[], "array"],
|
||||
])("returns false when value is not an ErrorResponse (%s)", (value, description) => {
|
||||
expect(isErrorResponse(value)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false when value is a different Error type", () => {
|
||||
const error = new Error("test");
|
||||
expect(isErrorResponse(error)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isSendContext", () => {
|
||||
it("returns true when value has id and key properties", () => {
|
||||
const validContext = { id: "test-id", key: "test-key" };
|
||||
expect(isSendContext(validContext)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true even with additional properties", () => {
|
||||
const contextWithExtras = { id: "test-id", key: "test-key", extra: "data" };
|
||||
expect(isSendContext(contextWithExtras)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[null, "null"],
|
||||
[undefined, "undefined"],
|
||||
])("returns false when value is %s", (value, _) => {
|
||||
expect(isSendContext(value)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["string", "string"],
|
||||
[123, "number"],
|
||||
[true, "boolean"],
|
||||
])("returns false when value is not an object (%s)", (value, _) => {
|
||||
expect(isSendContext(value)).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ key: "test-key" }, "missing id"],
|
||||
[{ id: "test-id" }, "missing key"],
|
||||
[{}, "empty object"],
|
||||
])("returns false when value is %s", (value, _) => {
|
||||
expect(isSendContext(value)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,13 +0,0 @@
|
||||
import { ErrorResponse } from "@bitwarden/common/models/response/error.response";
|
||||
|
||||
import { SendContext } from "./types";
|
||||
|
||||
/** narrows a type to an `ErrorResponse` */
|
||||
export function isErrorResponse(value: unknown): value is ErrorResponse {
|
||||
return value instanceof ErrorResponse;
|
||||
}
|
||||
|
||||
/** narrows a type to a `SendContext` */
|
||||
export function isSendContext(value: unknown): value is SendContext {
|
||||
return !!value && typeof value === "object" && "id" in value && "key" in value;
|
||||
}
|
||||
@@ -19,7 +19,7 @@
|
||||
</bit-callout>
|
||||
|
||||
@if (SendUIRefresh$ | async) {
|
||||
<div class="tw-mb-4 tw-max-w-md">
|
||||
<div class="tw-mb-4">
|
||||
<bit-search
|
||||
[(ngModel)]="searchText"
|
||||
[placeholder]="'searchSends' | i18n"
|
||||
|
||||
@@ -86,7 +86,7 @@
|
||||
|
||||
@if (showActionButtons) {
|
||||
<div class="tw-ml-auto">
|
||||
@if (userCanArchive$ | async) {
|
||||
@if ((userCanArchive$ | async) && !params.isAdminConsoleAction) {
|
||||
@if (isCipherArchived) {
|
||||
<button
|
||||
type="button"
|
||||
@@ -106,15 +106,17 @@
|
||||
></button>
|
||||
}
|
||||
}
|
||||
<button
|
||||
bitIconButton="bwi-trash"
|
||||
type="button"
|
||||
buttonType="danger"
|
||||
[label]="'delete' | i18n"
|
||||
[bitAction]="delete"
|
||||
[disabled]="!canDelete"
|
||||
data-testid="delete-cipher-btn"
|
||||
></button>
|
||||
@if (cipher) {
|
||||
<button
|
||||
bitIconButton="bwi-trash"
|
||||
type="button"
|
||||
buttonType="danger"
|
||||
[label]="'delete' | i18n"
|
||||
[bitAction]="delete"
|
||||
[disabled]="!canDelete"
|
||||
data-testid="delete-cipher-btn"
|
||||
></button>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</ng-container>
|
||||
|
||||
@@ -28,8 +28,7 @@ import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service";
|
||||
import { TaskService } from "@bitwarden/common/vault/tasks";
|
||||
import { DialogRef, DIALOG_DATA, DialogService, ToastService } from "@bitwarden/components";
|
||||
|
||||
import { RoutedVaultFilterService } from "../../individual-vault/vault-filter/services/routed-vault-filter.service";
|
||||
import { RoutedVaultFilterService } from "@bitwarden/vault";
|
||||
|
||||
import { VaultItemDialogComponent } from "./vault-item-dialog.component";
|
||||
|
||||
@@ -250,6 +249,15 @@ describe("VaultItemDialogComponent", () => {
|
||||
});
|
||||
|
||||
describe("archive button", () => {
|
||||
it("should not show archive button in admin console", () => {
|
||||
(component as any).userCanArchive$ = of(true);
|
||||
component.setTestCipher({ canBeArchived: true });
|
||||
component.setTestParams({ mode: "form", isAdminConsoleAction: true });
|
||||
fixture.detectChanges();
|
||||
const archiveButton = fixture.debugElement.query(By.css("[biticonbutton='bwi-archive']"));
|
||||
expect(archiveButton).toBeFalsy();
|
||||
});
|
||||
|
||||
it("should show archive button when the user can archive the item and the item can be archived", () => {
|
||||
component.setTestCipher({ canBeArchived: true });
|
||||
(component as any).userCanArchive$ = of(true);
|
||||
|
||||
@@ -15,11 +15,11 @@ import { Router } from "@angular/router";
|
||||
import { firstValueFrom, Observable, Subject, switchMap } from "rxjs";
|
||||
import { map } from "rxjs/operators";
|
||||
|
||||
import { CollectionView } from "@bitwarden/admin-console/common";
|
||||
import { PremiumBadgeComponent } from "@bitwarden/angular/billing/components/premium-badge";
|
||||
import { VaultViewPasswordHistoryService } from "@bitwarden/angular/services/view-password-history.service";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { EventCollectionService } from "@bitwarden/common/abstractions/event/event-collection.service";
|
||||
import { CollectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
@@ -63,11 +63,11 @@ import {
|
||||
CipherViewComponent,
|
||||
DecryptionFailureDialogComponent,
|
||||
DefaultChangeLoginPasswordService,
|
||||
RoutedVaultFilterService,
|
||||
RoutedVaultFilterModel,
|
||||
} from "@bitwarden/vault";
|
||||
|
||||
import { SharedModule } from "../../../shared/shared.module";
|
||||
import { RoutedVaultFilterService } from "../../individual-vault/vault-filter/services/routed-vault-filter.service";
|
||||
import { RoutedVaultFilterModel } from "../../individual-vault/vault-filter/shared/models/routed-vault-filter.model";
|
||||
import { WebCipherFormGenerationService } from "../../services/web-cipher-form-generation.service";
|
||||
import { WebVaultPremiumUpgradePromptService } from "../../services/web-premium-upgrade-prompt.service";
|
||||
|
||||
@@ -257,7 +257,7 @@ export class VaultItemDialogComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
protected get showActionButtons() {
|
||||
return this.cipher !== null && this.params.mode === "form" && this.formConfig.mode !== "clone";
|
||||
return this.cipher !== null && this.formConfig.mode !== "clone";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -171,37 +171,47 @@
|
||||
|
||||
<bit-menu-divider *ngIf="showMenuDivider"></bit-menu-divider>
|
||||
|
||||
@if (!viewingOrgVault) {
|
||||
<button bitMenuItem type="button" *ngIf="showFavorite" (click)="toggleFavorite()">
|
||||
@if (showFavorite) {
|
||||
<button bitMenuItem type="button" (click)="toggleFavorite()">
|
||||
<i class="bwi bwi-fw bwi-star" aria-hidden="true"></i>
|
||||
{{ (cipher.favorite ? "unfavorite" : "favorite") | i18n }}
|
||||
</button>
|
||||
}
|
||||
<button bitMenuItem type="button" (click)="editCipher()" *ngIf="canEditCipher">
|
||||
<i class="bwi bwi-fw bwi-pencil-square" aria-hidden="true"></i>
|
||||
{{ "edit" | i18n }}
|
||||
</button>
|
||||
<button bitMenuItem *ngIf="showAttachments" type="button" (click)="attachments()">
|
||||
<i class="bwi bwi-fw bwi-paperclip" aria-hidden="true"></i>
|
||||
{{ "attachments" | i18n }}
|
||||
</button>
|
||||
<button bitMenuItem *ngIf="showClone" type="button" (click)="clone()">
|
||||
<i class="bwi bwi-fw bwi-files" aria-hidden="true"></i>
|
||||
{{ "clone" | i18n }}
|
||||
</button>
|
||||
<button
|
||||
bitMenuItem
|
||||
*ngIf="showAssignToCollections"
|
||||
type="button"
|
||||
(click)="assignToCollections()"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-collection-shared" aria-hidden="true"></i>
|
||||
{{ "assignToCollections" | i18n }}
|
||||
</button>
|
||||
<button bitMenuItem *ngIf="showEventLogs" type="button" (click)="events()">
|
||||
<i class="bwi bwi-fw bwi-file-text" aria-hidden="true"></i>
|
||||
{{ "eventLogs" | i18n }}
|
||||
</button>
|
||||
@if (!isDeleted && canEditCipher) {
|
||||
<button bitMenuItem type="button" (click)="editCipher()">
|
||||
<i class="bwi bwi-fw bwi-pencil-square" aria-hidden="true"></i>
|
||||
{{ "edit" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (showAttachments) {
|
||||
<button bitMenuItem type="button" (click)="attachments()">
|
||||
<i class="bwi bwi-fw bwi-paperclip" aria-hidden="true"></i>
|
||||
{{ "attachments" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (showClone) {
|
||||
<button bitMenuItem type="button" (click)="clone()">
|
||||
<i class="bwi bwi-fw bwi-files" aria-hidden="true"></i>
|
||||
{{ "clone" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (showAssignToCollections) {
|
||||
<button
|
||||
bitMenuItem
|
||||
*ngIf="showAssignToCollections"
|
||||
type="button"
|
||||
(click)="assignToCollections()"
|
||||
>
|
||||
<i class="bwi bwi-fw bwi-collection-shared" aria-hidden="true"></i>
|
||||
{{ "assignToCollections" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (showEventLogs) {
|
||||
<button bitMenuItem type="button" (click)="events()">
|
||||
<i class="bwi bwi-fw bwi-file-text" aria-hidden="true"></i>
|
||||
{{ "eventLogs" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (showArchiveButton) {
|
||||
@if (userCanArchive) {
|
||||
<button bitMenuItem (click)="archive()" type="button">
|
||||
|
||||
@@ -142,4 +142,45 @@ describe("VaultCipherRowComponent", () => {
|
||||
expect(overlayContent).not.toContain('appcopyfield="password"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("showAssignToCollections", () => {
|
||||
let archivedCipher: CipherView;
|
||||
|
||||
beforeEach(() => {
|
||||
archivedCipher = new CipherView();
|
||||
archivedCipher.id = "cipher-1";
|
||||
archivedCipher.name = "Test Cipher";
|
||||
archivedCipher.type = CipherType.Login;
|
||||
archivedCipher.organizationId = "org-1";
|
||||
archivedCipher.deletedDate = null;
|
||||
archivedCipher.archivedDate = new Date();
|
||||
|
||||
component.cipher = archivedCipher;
|
||||
component.organizations = [{ id: "org-1" } as any];
|
||||
component.canAssignCollections = true;
|
||||
component.disabled = false;
|
||||
});
|
||||
|
||||
it("returns true when cipher is archived and conditions are met", () => {
|
||||
expect(component["showAssignToCollections"]).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when cipher is deleted", () => {
|
||||
archivedCipher.deletedDate = new Date();
|
||||
|
||||
expect(component["showAssignToCollections"]).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false when user cannot assign collections", () => {
|
||||
component.canAssignCollections = false;
|
||||
|
||||
expect(component["showAssignToCollections"]).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false when there are no organizations", () => {
|
||||
component.organizations = [];
|
||||
|
||||
expect(component["showAssignToCollections"]).toBeFalsy();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
input,
|
||||
} from "@angular/core";
|
||||
|
||||
import { CollectionView } from "@bitwarden/admin-console/common";
|
||||
import { CollectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
@@ -161,7 +161,9 @@ export class VaultCipherRowComponent<C extends CipherViewLike> implements OnInit
|
||||
return false;
|
||||
}
|
||||
|
||||
return CipherViewLikeUtils.isArchived(this.cipher);
|
||||
return (
|
||||
CipherViewLikeUtils.isArchived(this.cipher) && !CipherViewLikeUtils.isDeleted(this.cipher)
|
||||
);
|
||||
}
|
||||
|
||||
protected get clickAction() {
|
||||
@@ -191,7 +193,7 @@ export class VaultCipherRowComponent<C extends CipherViewLike> implements OnInit
|
||||
// Do not show attachments button if:
|
||||
// item is archived AND user is not premium user
|
||||
protected get showAttachments() {
|
||||
if (CipherViewLikeUtils.isArchived(this.cipher) && !this.userCanArchive) {
|
||||
if ((CipherViewLikeUtils.isArchived(this.cipher) && !this.userCanArchive) || this.isDeleted) {
|
||||
return false;
|
||||
}
|
||||
return this.canEditCipher || this.hasAttachments;
|
||||
@@ -217,11 +219,7 @@ export class VaultCipherRowComponent<C extends CipherViewLike> implements OnInit
|
||||
return CipherViewLikeUtils.decryptionFailure(this.cipher);
|
||||
}
|
||||
|
||||
// Do Not show Assign to Collections option if item is archived
|
||||
protected get showAssignToCollections() {
|
||||
if (CipherViewLikeUtils.isArchived(this.cipher)) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
this.organizations?.length &&
|
||||
this.canAssignCollections &&
|
||||
@@ -391,7 +389,12 @@ export class VaultCipherRowComponent<C extends CipherViewLike> implements OnInit
|
||||
}
|
||||
|
||||
protected get showFavorite() {
|
||||
if (CipherViewLikeUtils.isArchived(this.cipher) && !this.userCanArchive) {
|
||||
if (
|
||||
(!this.viewingOrgVault &&
|
||||
CipherViewLikeUtils.isArchived(this.cipher) &&
|
||||
!this.userCanArchive) ||
|
||||
CipherViewLikeUtils.isDeleted(this.cipher)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
Unassigned,
|
||||
CollectionView,
|
||||
CollectionTypes,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
} from "@bitwarden/common/admin-console/models/collections";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { CipherViewLike } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CollectionView } from "@bitwarden/admin-console/common";
|
||||
import { CollectionView } from "@bitwarden/common/admin-console/models/collections";
|
||||
import { CipherViewLike } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import { CollectionPermission } from "@bitwarden/web-vault/app/admin-console/organizations/shared/components/access-selector";
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user