Skip to content

Commit

Permalink
feat(bulk-import): show bulk-import to authorized users
Browse files Browse the repository at this point in the history
  • Loading branch information
debsmita1 committed Aug 13, 2024
1 parent 789e77a commit 6984a61
Show file tree
Hide file tree
Showing 10 changed files with 269 additions and 85 deletions.
24 changes: 24 additions & 0 deletions plugins/bulk-import/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,30 @@ The plugin work is still work in progress

### Installation

#### Installing as a dynamic plugin?

The sections below are relevant for static plugins. If the plugin is expected to be installed as a dynamic one:

- follow https://github.com/janus-idp/backstage-showcase/blob/main/showcase-docs/dynamic-plugins.md#installing-a-dynamic-plugin-package-in-the-showcase
- add content of `app-config.janus-idp.yaml` into `app-config.local.yaml`.

#### Prerequisites

Follow the Bulk import backend plugin [README](https://github.com/janus-idp/backstage-plugins/blob/main/plugins/bulk-import-backend/README.md) to integrate bulk import in your Backstage instance.

---

**NOTE**

- When RBAC permission framework is enabled, for non-admin users to access bulk import UI, the role associated with your user should have the following permission policies associated with it. Add the following in your permission policies configuration file:

```CSV
p, role:default/team_a, bulk.import, use, allow
p, role:default/team_a, catalog-entity.read, read, allow
p, role:default/team_a, catalog-entity.create, create, allow
g, user:default/<login-id/user-name>, role:default/team_a
```

#### Procedure

1. Install the Bulk import UI plugin using the following command:
Expand Down
18 changes: 17 additions & 1 deletion plugins/bulk-import/dev/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import React from 'react';

import { configApiRef } from '@backstage/core-plugin-api';
import { createDevApp } from '@backstage/dev-utils';
import { catalogApiRef } from '@backstage/plugin-catalog-react';
import { TestApiProvider } from '@backstage/test-utils';
import { permissionApiRef } from '@backstage/plugin-permission-react';
import {
MockConfigApi,
MockPermissionApi,
TestApiProvider,
} from '@backstage/test-utils';

import { createDevAppThemes } from '@redhat-developer/red-hat-developer-hub-theme';

Expand Down Expand Up @@ -100,20 +106,30 @@ class MockBulkImportApi implements BulkImportAPI {
}
}

const mockPermissionApi = new MockPermissionApi();

const mockBulkImportApi = new MockBulkImportApi(
mockGetRepositories.repositories,
mockGetOrganizations.organizations,
);

const mockConfigApi = new MockConfigApi({
permission: {
enabled: true,
},
});

createDevApp()
.registerPlugin(bulkImportPlugin)
.addThemes(createDevAppThemes())
.addPage({
element: (
<TestApiProvider
apis={[
[permissionApiRef, mockPermissionApi],
[catalogApiRef, mockCatalogApi],
[bulkImportApiRef, mockBulkImportApi],
[configApiRef, mockConfigApi],
]}
>
<BulkImportPage />
Expand Down
2 changes: 2 additions & 0 deletions plugins/bulk-import/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@
"@backstage/theme": "^0.5.6",
"@backstage/catalog-model": "^1.5.0",
"@backstage/plugin-catalog-react": "^1.12.2",
"@backstage/plugin-permission-react": "^0.4.24",
"@backstage/plugin-catalog-import": "^0.12.1",
"@janus-idp/backstage-plugin-bulk-import-common": "0.2.0",
"@material-ui/core": "^4.9.13",
"@material-ui/lab": "^4.0.0-alpha.61",
"@material-ui/icons": "^4.11.3",
Expand Down
32 changes: 16 additions & 16 deletions plugins/bulk-import/src/api/BulkImportBackendClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,22 +45,22 @@ export const bulkImportApiRef = createApiRef<BulkImportAPI>({
export class BulkImportBackendClient implements BulkImportAPI {
// @ts-ignore
private readonly configApi: ConfigApi;
// private readonly identityApi: IdentityApi;
private readonly identityApi: IdentityApi;

constructor(options: Options) {
this.configApi = options.configApi;
// this.identityApi = options.identityApi;
this.identityApi = options.identityApi;
}

async getRepositories(page: number, size: number) {
// const { token: idToken } = await this.identityApi.getCredentials();
const { token: idToken } = await this.identityApi.getCredentials();

const backendUrl = this.configApi.getString('backend.baseUrl');
const jsonResponse = await fetch(
`${backendUrl}/api/bulk-import-backend/repositories?pagePerIntegration=${page}&sizePerIntegration=${size}`,
{
headers: {
// ...(idToken && { Authorization: `Bearer ${idToken}` }),
...(idToken && { Authorization: `Bearer ${idToken}` }),
'Content-Type': 'application/json',
},
},
Expand All @@ -72,14 +72,14 @@ export class BulkImportBackendClient implements BulkImportAPI {
}

async getOrganizations(page: number, size: number) {
// const { token: idToken } = await this.identityApi.getCredentials();
const { token: idToken } = await this.identityApi.getCredentials();

const backendUrl = this.configApi.getString('backend.baseUrl');
const jsonResponse = await fetch(
`${backendUrl}/api/bulk-import-backend/organizations?pagePerIntegration=${page}&sizePerIntegration=${size}`,
{
headers: {
// ...(idToken && { Authorization: `Bearer ${idToken}` }),
...(idToken && { Authorization: `Bearer ${idToken}` }),
'Content-Type': 'application/json',
},
},
Expand All @@ -91,14 +91,14 @@ export class BulkImportBackendClient implements BulkImportAPI {
}

async getRepositoriesFromOrg(orgName: string, page: number, size: number) {
// const { token: idToken } = await this.identityApi.getCredentials();
const { token: idToken } = await this.identityApi.getCredentials();

const backendUrl = this.configApi.getString('backend.baseUrl');
const jsonResponse = await fetch(
`${backendUrl}/api/bulk-import-backend/organizations/${orgName}/repositories?pagePerIntegration=${page}&sizePerIntegration=${size}`,
{
headers: {
// ...(idToken && { Authorization: `Bearer ${idToken}` }),
...(idToken && { Authorization: `Bearer ${idToken}` }),
'Content-Type': 'application/json',
},
},
Expand All @@ -113,7 +113,7 @@ export class BulkImportBackendClient implements BulkImportAPI {
importRepositories: CreateImportJobRepository[],
dryRun?: boolean,
) {
// const { token: idToken } = await this.identityApi.getCredentials();
const { token: idToken } = await this.identityApi.getCredentials();

const backendUrl = this.configApi.getString('backend.baseUrl');
const jsonResponse = await fetch(
Expand All @@ -123,7 +123,7 @@ export class BulkImportBackendClient implements BulkImportAPI {
{
method: 'POST',
headers: {
// ...(idToken && { Authorization: `Bearer ${idToken}` }),
...(idToken && { Authorization: `Bearer ${idToken}` }),
'Content-Type': 'application/json',
},
body: JSON.stringify(importRepositories),
Expand All @@ -133,15 +133,15 @@ export class BulkImportBackendClient implements BulkImportAPI {
}

async getImportJobs(page: number, size: number) {
// const { token: idToken } = await this.identityApi.getCredentials();
const { token: idToken } = await this.identityApi.getCredentials();

const backendUrl = this.configApi.getString('backend.baseUrl');
const jsonResponse = await fetch(
`${backendUrl}/api/bulk-import-backend/imports?pagePerIntegration=${page}&sizePerIntegration=${size}`,
{
method: 'GET',
headers: {
// ...(idToken && { Authorization: `Bearer ${idToken}` }),
...(idToken && { Authorization: `Bearer ${idToken}` }),
'Content-Type': 'application/json',
},
},
Expand All @@ -153,15 +153,15 @@ export class BulkImportBackendClient implements BulkImportAPI {
}

async checkImportStatus(repo: string, defaultBranch: string) {
// const { token: idToken } = await this.identityApi.getCredentials();
const { token: idToken } = await this.identityApi.getCredentials();

const backendUrl = this.configApi.getString('backend.baseUrl');
const jsonResponse = await fetch(
`${backendUrl}/api/bulk-import-backend/import/by-repo?repo=${repo}&defaultBranch=${defaultBranch}`,
{
method: 'GET',
headers: {
// ...(idToken && { Authorization: `Bearer ${idToken}` }),
...(idToken && { Authorization: `Bearer ${idToken}` }),
'Content-Type': 'application/json',
},
},
Expand All @@ -171,15 +171,15 @@ export class BulkImportBackendClient implements BulkImportAPI {
}

async removeRepository(repo: string, defaultBranch: string) {
// const { token: idToken } = await this.identityApi.getCredentials();
const { token: idToken } = await this.identityApi.getCredentials();

const backendUrl = this.configApi.getString('backend.baseUrl');
const jsonResponse = await fetch(
`${backendUrl}/api/bulk-import-backend/import/by-repo?repo=${repo}&defaultBranch=${defaultBranch}`,
{
method: 'DELETE',
headers: {
// ...(idToken && { Authorization: `Bearer ${idToken}` }),
...(idToken && { Authorization: `Bearer ${idToken}` }),
'Content-Type': 'application/json',
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -394,12 +394,6 @@ export const RepositoriesTable = ({
}
return 'repositories-table';
};
if (loading)
return (
<div data-testid={`${ariaLabel()}-loading`}>
<Progress />
</div>
);

const tableBodyContent = () => {
if (loading) {
Expand Down
79 changes: 79 additions & 0 deletions plugins/bulk-import/src/components/BulkImportIcon.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import React from 'react';

import { SidebarItem } from '@backstage/core-components';
import { usePermission } from '@backstage/plugin-permission-react';

import { render, screen } from '@testing-library/react';

import { BulkImportIcon } from './BulkImportIcon';

jest.mock('@backstage/plugin-permission-react', () => ({
usePermission: jest.fn(),
}));

const mockUsePermission = usePermission as jest.MockedFunction<
typeof usePermission
>;

const configMock = {
getOptionalBoolean: jest.fn(() => true),
};

jest.mock('@backstage/core-plugin-api', () => ({
...jest.requireActual('@backstage/core-plugin-api'),
useApi: jest.fn(() => {
return configMock;
}),
}));

jest.mock('@backstage/core-components', () => ({
SidebarItem: jest
.fn()
.mockImplementation(() => (
<div data-testid="mockSidebarItem">Bulk import</div>
)),
}));

const mockedSidebarItem = SidebarItem as jest.MockedFunction<
typeof SidebarItem
>;

const mockBulkImportApiRef = jest.fn();

describe('Administration component', () => {
beforeEach(() => {
mockBulkImportApiRef.mockClear();
mockedSidebarItem.mockClear();
});

it('renders Bulk import sidebar item if user is authorized', async () => {
mockUsePermission.mockReturnValue({ loading: false, allowed: true });
render(<BulkImportIcon />);
expect(mockedSidebarItem).toHaveBeenCalled();
expect(screen.queryByText('Bulk import')).toBeInTheDocument();
});

it('does not render Bulk import sidebar item if user is not authorized', async () => {
mockUsePermission.mockReturnValue({ loading: false, allowed: false });

render(<BulkImportIcon />);
expect(screen.queryByText('Bulk import')).toBeNull();
});

it('does not render Bulk import sidebar item if user loading state is true', async () => {
mockUsePermission.mockReturnValue({ loading: true, allowed: false });

render(<BulkImportIcon />);
expect(mockedSidebarItem).not.toHaveBeenCalled();
expect(screen.queryByText('Bulk import')).toBeNull();
});

it('renders the Bulk import sidebar item if RBAC is disabled in the configuration', async () => {
mockUsePermission.mockReturnValue({ loading: true, allowed: true });
configMock.getOptionalBoolean.mockReturnValueOnce(false);

render(<BulkImportIcon />);
expect(mockedSidebarItem).toHaveBeenCalled();
expect(screen.queryByText('Bulk import')).toBeInTheDocument();
});
});
36 changes: 32 additions & 4 deletions plugins/bulk-import/src/components/BulkImportIcon.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import React from 'react';

import { SidebarItem } from '@backstage/core-components';
import { configApiRef, useApi } from '@backstage/core-plugin-api';
import { usePermission } from '@backstage/plugin-permission-react';

import { bulkImportPermission } from '@janus-idp/backstage-plugin-bulk-import-common';

import { getImageForIconClass } from '../utils/icons';

Expand All @@ -15,9 +19,33 @@ export const icon = () => {
};

export const BulkImportIcon = () => {
// permission logic
const { loading: isUserLoading, allowed } = usePermission({
permission: bulkImportPermission,
resourceRef: bulkImportPermission.resourceType,
});

return (
<SidebarItem text="Bulk import" to="bulk-import/repositories" icon={icon} />
);
const config = useApi(configApiRef);
const isPermissionFrameworkEnabled =
config.getOptionalBoolean('permission.enabled');

if (!isUserLoading && isPermissionFrameworkEnabled) {
return allowed ? (
<SidebarItem
text="Bulk import"
to="bulk-import/repositories"
icon={icon}
/>
) : null;
}

if (!isPermissionFrameworkEnabled) {
return (
<SidebarItem
text="Bulk import"
to="bulk-import/repositories"
icon={icon}
/>
);
}
return null;
};
Loading

0 comments on commit 6984a61

Please sign in to comment.