refactor(account): migrate access tokens table to react [EE-4701] (#10669)

pull/10792/head
Chaim Lev-Ari 2024-04-09 08:17:43 +03:00 committed by GitHub
parent 48aab77058
commit 3f3db75d85
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 219 additions and 249 deletions

View File

@ -1,39 +0,0 @@
export default class AccessTokensDatatableController {
/* @ngInject*/
constructor($scope, $state, $controller, DatatableService) {
angular.extend(this, $controller('GenericDatatableController', { $scope: $scope }));
this.onClickAdd = () => {
if (this.uiCanExit()) {
$state.go('portainer.account.new-access-token');
}
};
this.$onInit = function () {
this.setDefaults();
this.prepareTableFromDataset();
const storedOrder = DatatableService.getDataTableOrder(this.tableKey);
if (storedOrder !== null) {
this.state.reverseOrder = storedOrder.reverse;
this.state.orderBy = storedOrder.orderBy;
}
const textFilter = DatatableService.getDataTableTextFilters(this.tableKey);
if (textFilter !== null) {
this.state.textFilter = textFilter;
this.onTextFilterChange();
}
const storedFilters = DatatableService.getDataTableFilters(this.tableKey);
if (storedFilters !== null) {
this.filters = storedFilters;
}
if (this.filters && this.filters.state) {
this.filters.state.open = false;
}
this.onSettingsRepeaterChange();
};
}
}

View File

@ -1,135 +0,0 @@
<div class="datatable">
<rd-widget>
<rd-widget-body classes="no-padding">
<div class="toolBar vertical-center">
<div class="toolBarTitle vertical-center">
<div class="widget-icon space-right">
<pr-icon icon="$ctrl.titleIcon"></pr-icon>
</div>
<span>{{ $ctrl.titleText }}</span>
</div>
<div class="searchBar vertical-center">
<pr-icon icon="'search'" class="searchIcon"></pr-icon>
<input
type="text"
class="searchInput"
ng-model="$ctrl.state.textFilter"
ng-change="$ctrl.onTextFilterChange()"
placeholder="Search..."
ng-model-options="{ debounce: 300 }"
/>
</div>
<div class="actionBar">
<button
ng-if="!$ctrl.endpointType"
type="button"
class="btn btn-sm btn-dangerlight vertical-center"
ng-disabled="$ctrl.state.selectedItemCount === 0"
ng-click="$ctrl.removeAction($ctrl.state.selectedItems)"
>
<pr-icon icon="'trash-2'" class-name="'icon-white'"></pr-icon>
<span>Remove</span>
</button>
<button type="button" class="btn btn-sm btn-primary vertical-center" ng-click="$ctrl.onClickAdd()">
<pr-icon icon="'plus'" class-name="'icon-white'"></pr-icon>
<span>Add access token</span>
</button>
</div>
</div>
<div class="table-responsive">
<table class="table-hover nowrap-cells table">
<thead>
<tr>
<th>
<div class="vertical-center">
<span class="md-checkbox">
<input id="select_all" type="checkbox" ng-model="$ctrl.state.selectAll" ng-change="$ctrl.selectAll()" />
<label for="select_all"></label>
</span>
<table-column-header
col-title="'Description'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'description'"
is-sorted-desc="$ctrl.state.orderBy === 'description' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('description')"
></table-column-header>
</div>
</th>
<th>
<table-column-header
col-title="'Prefix'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'prefix'"
is-sorted-desc="$ctrl.state.orderBy === 'prefix' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('prefix')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Created'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'dateCreated'"
is-sorted-desc="$ctrl.state.orderBy === 'dateCreated' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('dateCreated')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Last Used'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'lastUsed'"
is-sorted-desc="$ctrl.state.orderBy === 'lastUsed' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('lastUsed')"
></table-column-header>
</th>
</tr>
</thead>
<tbody>
<tr
dir-paginate="item in ($ctrl.state.filteredDataSet = ($ctrl.dataset | filter:$ctrl.state.textFilter | orderBy:$ctrl.state.orderBy:$ctrl.state.reverseOrder | itemsPerPage: $ctrl.state.paginatedItemLimit))"
ng-class="{ active: item.Checked }"
>
<td>
<span class="md-checkbox">
<input id="select_{{ $index }}" type="checkbox" ng-model="item.Checked" ng-click="$ctrl.selectItem(item, $event)" />
<label for="select_{{ $index }}"></label>
</span>
{{ item.description }}
</td>
<td>
{{ item.prefix }}
</td>
<td>
{{ item.dateCreated | getisodatefromtimestamp }}
</td>
<td>
<span ng-if="item.lastUsed > 0">{{ item.lastUsed | getisodatefromtimestamp }}</span>
</td>
</tr>
<tr ng-if="!$ctrl.dataset">
<td colspan="3" class="text-muted text-center">Loading...</td>
</tr>
</tbody>
</table>
</div>
<div class="footer" ng-if="$ctrl.dataset">
<div class="infoBar" ng-if="$ctrl.state.selectedItemCount !== 0"> {{ $ctrl.state.selectedItemCount }} item(s) selected </div>
<div class="paginationControls">
<form class="form-inline">
<span class="limitSelector">
<span style="margin-right: 5px"> Items per page </span>
<select class="form-control" ng-model="$ctrl.state.paginatedItemLimit" ng-change="$ctrl.changePaginationLimit()" data-cy="component-paginationSelect">
<option value="0">All</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</span>
<dir-pagination-controls max-size="5"></dir-pagination-controls>
</form>
</div>
</div>
</rd-widget-body>
</rd-widget>
</div>

View File

@ -1,16 +0,0 @@
import angular from 'angular';
import controller from './access-tokens-datatable.controller';
angular.module('portainer.app').component('accessTokensDatatable', {
templateUrl: './access-tokens-datatable.html',
controller,
bindings: {
titleText: '@',
titleIcon: '@',
dataset: '<',
tableKey: '@',
orderBy: '@',
removeAction: '<',
uiCanExit: '<',
},
});

View File

@ -4,6 +4,8 @@ import { r2a } from '@/react-tools/react2angular';
import { withCurrentUser } from '@/react-tools/withCurrentUser';
import { withUIRouter } from '@/react-tools/withUIRouter';
import { withReactQuery } from '@/react-tools/withReactQuery';
import { HelmRepositoryDatatable } from '@/react/portainer/account/AccountView/HelmRepositoryDatatable';
import { AccessTokensDatatable } from '@/react/portainer/account/AccountView/AccessTokensDatatable';
import { ApplicationSettingsWidget } from '@/react/portainer/account/AccountView/ApplicationSettings';
export const accountModule = angular
@ -14,4 +16,17 @@ export const accountModule = angular
withUIRouter(withReactQuery(withCurrentUser(ApplicationSettingsWidget))),
[]
)
)
.component(
'helmRepositoryDatatable',
r2a(
withUIRouter(withReactQuery(withCurrentUser(HelmRepositoryDatatable))),
[]
)
)
.component(
'accessTokensDatatable',
r2a(withUIRouter(withReactQuery(withCurrentUser(AccessTokensDatatable))), [
'canExit',
])
).name;

View File

@ -8,7 +8,6 @@ import { AnnotationsBeTeaser } from '@/react/kubernetes/annotations/AnnotationsB
import { withFormValidation } from '@/react-tools/withFormValidation';
import { GroupAssociationTable } from '@/react/portainer/environments/environment-groups/components/GroupAssociationTable';
import { AssociatedEnvironmentsSelector } from '@/react/portainer/environments/environment-groups/components/AssociatedEnvironmentsSelector';
import { HelmRepositoryDatatable } from '@/react/portainer/account/AccountView/HelmRepositoryDatatable';
import { withControlledInput } from '@/react-tools/withControlledInput';
import {
@ -241,13 +240,6 @@ export const ngModule = angular
.component(
'associatedEndpointsSelector',
r2a(withReactQuery(AssociatedEnvironmentsSelector), ['onChange', 'value'])
)
.component(
'helmRepositoryDatatable',
r2a(
withUIRouter(withReactQuery(withCurrentUser(HelmRepositoryDatatable))),
[]
)
);
export const componentsModule = ngModule.name;

View File

@ -88,18 +88,6 @@
<application-settings-widget></application-settings-widget>
<div class="row">
<div class="col-lg-12 col-md-12 col-xs-12">
<access-tokens-datatable
title-text="Access tokens"
title-icon="key"
dataset="tokens"
table-key="tokens"
order-by="Description"
remove-action="removeAction"
ui-can-exit="uiCanExit"
></access-tokens-datatable>
</div>
</div>
<access-tokens-datatable ui-can-exit="uiCanExit()"></access-tokens-datatable>
<helm-repository-datatable></helm-repository-datatable>

View File

@ -1,4 +1,4 @@
import { confirmChangePassword, confirmDelete } from '@@/modals/confirm';
import { confirmChangePassword } from '@@/modals/confirm';
import { openDialog } from '@@/modals/Dialog';
import { buildConfirmButton } from '@@/modals/utils';
@ -68,35 +68,7 @@ angular.module('portainer.app').controller('AccountController', [
return this.uiCanExit();
};
$scope.removeAction = (selectedTokens) => {
const msg = 'Do you want to remove the selected access token(s)? Any script or application using these tokens will no longer be able to invoke the Portainer API.';
confirmDelete(msg).then((confirmed) => {
if (!confirmed) {
return;
}
let actionCount = selectedTokens.length;
selectedTokens.forEach((token) => {
UserService.deleteAccessToken($scope.userID, token.id)
.then(() => {
Notifications.success('Success', 'Token successfully removed');
var index = $scope.tokens.indexOf(token);
$scope.tokens.splice(index, 1);
})
.catch((err) => {
Notifications.error('Failure', err, 'Unable to remove token');
})
.finally(() => {
--actionCount;
if (actionCount === 0) {
$state.reload();
}
});
});
});
};
async function initView() {
function initView() {
const state = StateManager.getState();
const userDetails = Authentication.getUserDetails();
$scope.userID = userDetails.ID;
@ -127,14 +99,6 @@ angular.module('portainer.app').controller('AccountController', [
.catch(function error(err) {
Notifications.error('Failure', err, 'Unable to retrieve application settings');
});
UserService.getAccessTokens($scope.userID)
.then(function success(data) {
$scope.tokens = data;
})
.catch(function error(err) {
Notifications.error('Failure', err, 'Unable to retrieve user tokens');
});
}
initView();

View File

@ -0,0 +1,32 @@
import { Key } from 'lucide-react';
import { Datatable } from '@@/datatables';
import { createPersistedStore } from '@@/datatables/types';
import { useTableState } from '@@/datatables/useTableState';
import { useAccessTokens } from '../../access-tokens/queries/useAccessTokens';
import { columns } from './columns';
import { TableActions } from './TableActions';
const tableKey = 'access-tokens';
const store = createPersistedStore(tableKey);
export function AccessTokensDatatable({ canExit }: { canExit?: boolean }) {
const query = useAccessTokens();
const tableState = useTableState(store, tableKey);
return (
<Datatable
columns={columns}
isLoading={query.isLoading}
dataset={query.data || []}
settingsManager={tableState}
title="Access tokens"
titleIcon={Key}
renderTableActions={(selectedItems) => (
<TableActions selectedItems={selectedItems} canExit={canExit} />
)}
/>
);
}

View File

@ -0,0 +1,41 @@
import { notifySuccess } from '@/portainer/services/notifications';
import { DeleteButton } from '@@/buttons/DeleteButton';
import { AddButton } from '@@/buttons';
import { AccessToken } from '../../access-tokens/types';
import { useDeleteAccessTokensMutation } from './useDeleteAccessTokensMutation';
export function TableActions({
selectedItems,
canExit,
}: {
selectedItems: AccessToken[];
canExit?: boolean;
}) {
const deleteMutation = useDeleteAccessTokensMutation();
return (
<>
<DeleteButton
disabled={selectedItems.length === 0}
confirmMessage="Do you want to remove the selected access token(s)? Any script or application using these tokens will no longer be able to invoke the Portainer API."
onConfirmed={handleRemove}
/>
<AddButton to=".new-access-token" disabled={!canExit}>
Add access token
</AddButton>
</>
);
function handleRemove() {
const ids = selectedItems.map((item) => item.id);
deleteMutation.mutate(ids, {
onSuccess() {
notifySuccess('Success', 'Access token(s) removed');
},
});
}
}

View File

@ -0,0 +1,24 @@
import { createColumnHelper } from '@tanstack/react-table';
import { isoDateFromTimestamp } from '@/portainer/filters/filters';
import { AccessToken } from '../../access-tokens/types';
const columnHelper = createColumnHelper<AccessToken>();
export const columns = [
columnHelper.accessor('description', {
header: 'Description',
}),
columnHelper.accessor('prefix', {
header: 'Prefix',
}),
columnHelper.accessor('dateCreated', {
header: 'Created',
cell: ({ getValue }) => isoDateFromTimestamp(getValue()),
}),
columnHelper.accessor('lastUsed', {
header: 'Last Used',
cell: ({ getValue }) => isoDateFromTimestamp(getValue()),
}),
];

View File

@ -0,0 +1 @@
export { AccessTokensDatatable } from './AccessTokensDatatable';

View File

@ -0,0 +1,40 @@
import { useMutation, useQueryClient } from 'react-query';
import { withError, withInvalidate } from '@/react-tools/react-query';
import { useCurrentUser } from '@/react/hooks/useUser';
import { promiseSequence } from '@/portainer/helpers/promise-utils';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { AccessToken } from '../../access-tokens/types';
import { buildUrl } from '../../access-tokens/queries/build-url';
import { queryKeys } from '../../access-tokens/queries/query-keys';
export function useDeleteAccessTokensMutation() {
const { user } = useCurrentUser();
const queryClient = useQueryClient();
return useMutation({
mutationFn: (ids: Array<AccessToken['id']>) =>
deleteAccessTokens(user.Id, ids),
...withError('Failed to delete access tokens'),
...withInvalidate(queryClient, [queryKeys.base(user.Id)]),
});
}
async function deleteAccessTokens(
userId: number,
tokenIds: Array<AccessToken['id']>
) {
return promiseSequence(
tokenIds.map((tokenId) => () => deleteAccessToken(userId, tokenId))
);
}
async function deleteAccessToken(userId: number, id: AccessToken['id']) {
try {
await axios.delete(buildUrl(userId, id));
} catch (e) {
throw parseAxiosError(e, 'Unable to delete access token');
}
}

View File

@ -0,0 +1,8 @@
import { UserId } from '@/portainer/users/types';
import { AccessToken } from '../types';
export function buildUrl(userId: UserId, id?: AccessToken['id']) {
const baseUrl = `/users/${userId}/tokens`;
return id ? `${baseUrl}/${id}` : baseUrl;
}

View File

@ -0,0 +1,6 @@
import { userQueryKeys } from '@/portainer/users/queries/queryKeys';
import { UserId } from '@/portainer/users/types';
export const queryKeys = {
base: (userId: UserId) => [...userQueryKeys.user(userId), 'tokens'] as const,
};

View File

@ -0,0 +1,27 @@
import { useQuery } from 'react-query';
import { useCurrentUser } from '@/react/hooks/useUser';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { AccessToken } from '../types';
import { queryKeys } from './query-keys';
import { buildUrl } from './build-url';
export function useAccessTokens() {
const { user } = useCurrentUser();
return useQuery({
queryKey: queryKeys.base(user.Id),
queryFn: () => getAccessTokens(user.Id),
});
}
async function getAccessTokens(userId: number) {
try {
const { data } = await axios.get<Array<AccessToken>>(buildUrl(userId));
return data;
} catch (e) {
throw parseAxiosError(e, 'Unable to get access tokens');
}
}

View File

@ -0,0 +1,22 @@
/**
* AccessToken represents an API key
*/
export interface AccessToken {
id: number;
userId: number;
description: string;
/** API key identifier (7 char prefix) */
prefix: string;
/** Unix timestamp (UTC) when the API key was created */
dateCreated: number;
/** Unix timestamp (UTC) when the API key was last used */
lastUsed: number;
/** Digest represents SHA256 hash of the raw API key */
digest?: string;
}