grafana/public/app/features/api-keys/ApiKeysPage.tsx

240 lines
6.5 KiB
TypeScript
Raw Normal View History

import React, { PureComponent } from 'react';
import { connect, ConnectedProps } from 'react-redux';
// Utils
import { InlineField, InlineSwitch, VerticalGroup, Modal, Button } from '@grafana/ui';
import { Page } from 'app/core/components/Page/Page';
import { contextSrv } from 'app/core/core';
Auth: Allow expiration of API keys (#17678) * Modify backend to allow expiration of API Keys * Add middleware test for expired api keys * Modify frontend to enable expiration of API Keys * Fix frontend tests * Fix migration and add index for `expires` field * Add api key tests for database access * Substitude time.Now() by a mock for test usage * Front-end modifications * Change input label to `Time to live` * Change input behavior to comply with the other similar * Add tooltip * Modify AddApiKey api call response Expiration should be *time.Time instead of string * Present expiration date in the selected timezone * Use kbn for transforming intervals to seconds * Use `assert` library for tests * Frontend fixes Add checks for empty/undefined/null values * Change expires column from datetime to integer * Restrict api key duration input It should be interval not number * AddApiKey must complain if SecondsToLive is negative * Declare ErrInvalidApiKeyExpiration * Move configuration to auth section * Update docs * Eliminate alias for models in modified files * Omit expiration from api response if empty * Eliminate Goconvey from test file * Fix test Do not sleep, use mocked timeNow() instead * Remove index for expires from api_key table The index should be anyway on both org_id and expires fields. However this commit eliminates completely the index for now since not many rows are expected to be in this table. * Use getTimeZone function * Minor change in api key listing The frontend should display a message instead of empty string if the key does not expire.
2019-06-26 01:47:03 -05:00
import { getTimeZone } from 'app/features/profile/state/selectors';
import { AccessControlAction, ApiKey, ApikeyMigrationResult, StoreState } from 'app/types';
import { ApiKeysActionBar } from './ApiKeysActionBar';
import { ApiKeysTable } from './ApiKeysTable';
import { MigrateToServiceAccountsCard } from './MigrateToServiceAccountsCard';
import { deleteApiKey, migrateApiKey, migrateAll, loadApiKeys, toggleIncludeExpired } from './state/actions';
import { setSearchQuery } from './state/reducers';
import { getApiKeys, getApiKeysCount, getIncludeExpired, getIncludeExpiredDisabled } from './state/selectors';
Auth: Allow expiration of API keys (#17678) * Modify backend to allow expiration of API Keys * Add middleware test for expired api keys * Modify frontend to enable expiration of API Keys * Fix frontend tests * Fix migration and add index for `expires` field * Add api key tests for database access * Substitude time.Now() by a mock for test usage * Front-end modifications * Change input label to `Time to live` * Change input behavior to comply with the other similar * Add tooltip * Modify AddApiKey api call response Expiration should be *time.Time instead of string * Present expiration date in the selected timezone * Use kbn for transforming intervals to seconds * Use `assert` library for tests * Frontend fixes Add checks for empty/undefined/null values * Change expires column from datetime to integer * Restrict api key duration input It should be interval not number * AddApiKey must complain if SecondsToLive is negative * Declare ErrInvalidApiKeyExpiration * Move configuration to auth section * Update docs * Eliminate alias for models in modified files * Omit expiration from api response if empty * Eliminate Goconvey from test file * Fix test Do not sleep, use mocked timeNow() instead * Remove index for expires from api_key table The index should be anyway on both org_id and expires fields. However this commit eliminates completely the index for now since not many rows are expected to be in this table. * Use getTimeZone function * Minor change in api key listing The frontend should display a message instead of empty string if the key does not expire.
2019-06-26 01:47:03 -05:00
function mapStateToProps(state: StoreState) {
const canCreate = contextSrv.hasAccess(AccessControlAction.ActionAPIKeysCreate, true);
return {
apiKeys: getApiKeys(state.apiKeys),
searchQuery: state.apiKeys.searchQuery,
apiKeysCount: getApiKeysCount(state.apiKeys),
hasFetched: state.apiKeys.hasFetched,
timeZone: getTimeZone(state.user),
includeExpired: getIncludeExpired(state.apiKeys),
includeExpiredDisabled: getIncludeExpiredDisabled(state.apiKeys),
canCreate: canCreate,
migrationResult: state.apiKeys.migrationResult,
};
2018-09-25 09:23:43 -05:00
}
const defaultPageProps = {
navId: 'apikeys',
};
const mapDispatchToProps = {
loadApiKeys,
deleteApiKey,
migrateApiKey,
migrateAll,
setSearchQuery,
toggleIncludeExpired,
};
const connector = connect(mapStateToProps, mapDispatchToProps);
interface OwnProps {}
export type Props = OwnProps & ConnectedProps<typeof connector>;
interface State {
showMigrationResult: boolean;
}
Auth: Allow expiration of API keys (#17678) * Modify backend to allow expiration of API Keys * Add middleware test for expired api keys * Modify frontend to enable expiration of API Keys * Fix frontend tests * Fix migration and add index for `expires` field * Add api key tests for database access * Substitude time.Now() by a mock for test usage * Front-end modifications * Change input label to `Time to live` * Change input behavior to comply with the other similar * Add tooltip * Modify AddApiKey api call response Expiration should be *time.Time instead of string * Present expiration date in the selected timezone * Use kbn for transforming intervals to seconds * Use `assert` library for tests * Frontend fixes Add checks for empty/undefined/null values * Change expires column from datetime to integer * Restrict api key duration input It should be interval not number * AddApiKey must complain if SecondsToLive is negative * Declare ErrInvalidApiKeyExpiration * Move configuration to auth section * Update docs * Eliminate alias for models in modified files * Omit expiration from api response if empty * Eliminate Goconvey from test file * Fix test Do not sleep, use mocked timeNow() instead * Remove index for expires from api_key table The index should be anyway on both org_id and expires fields. However this commit eliminates completely the index for now since not many rows are expected to be in this table. * Use getTimeZone function * Minor change in api key listing The frontend should display a message instead of empty string if the key does not expire.
2019-06-26 01:47:03 -05:00
export class ApiKeysPageUnconnected extends PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
showMigrationResult: false,
};
}
2018-09-25 09:23:43 -05:00
componentDidMount() {
this.fetchApiKeys();
}
async fetchApiKeys() {
await this.props.loadApiKeys();
2018-09-25 09:23:43 -05:00
}
onDeleteApiKey = (key: ApiKey) => {
this.props.deleteApiKey(key.id!);
};
2018-09-25 09:23:43 -05:00
onMigrateApiKey = (key: ApiKey) => {
this.props.migrateApiKey(key.id!);
};
onSearchQueryChange = (value: string) => {
this.props.setSearchQuery(value);
};
onIncludeExpiredChange = (event: React.SyntheticEvent<HTMLInputElement>) => {
this.props.toggleIncludeExpired();
};
onMigrateApiKeys = async () => {
try {
await this.props.migrateAll();
this.setState({
showMigrationResult: true,
});
} catch (err) {
console.error(err);
}
};
dismissModal = async () => {
this.setState({ showMigrationResult: false });
};
render() {
const {
hasFetched,
apiKeysCount,
apiKeys,
searchQuery,
timeZone,
includeExpired,
includeExpiredDisabled,
canCreate,
migrationResult,
} = this.props;
if (!hasFetched) {
return (
<Page {...defaultPageProps}>
<Page.Contents isLoading={true}>{}</Page.Contents>
</Page>
);
}
const showTable = apiKeysCount > 0;
return (
<Page {...defaultPageProps}>
<Page.Contents isLoading={false}>
<>
<MigrateToServiceAccountsCard onMigrate={this.onMigrateApiKeys} apikeysCount={apiKeysCount} />
{showTable ? (
<ApiKeysActionBar
searchQuery={searchQuery}
disabled={!canCreate}
onSearchChange={this.onSearchQueryChange}
/>
) : null}
{showTable ? (
<VerticalGroup>
<InlineField disabled={includeExpiredDisabled} label="Include expired keys">
<InlineSwitch id="showExpired" value={includeExpired} onChange={this.onIncludeExpiredChange} />
</InlineField>
<ApiKeysTable
apiKeys={apiKeys}
timeZone={timeZone}
onMigrate={this.onMigrateApiKey}
onDelete={this.onDeleteApiKey}
/>
</VerticalGroup>
) : null}
</>
</Page.Contents>
{migrationResult && (
<MigrationSummary
visible={this.state.showMigrationResult}
data={migrationResult}
onDismiss={this.dismissModal}
/>
)}
</Page>
2018-09-25 09:23:43 -05:00
);
}
}
export type MigrationSummaryProps = {
visible: boolean;
data: ApikeyMigrationResult;
onDismiss: () => void;
};
const styles: { [key: string]: React.CSSProperties } = {
migrationSummary: {
padding: '20px',
},
infoText: {
color: '#007bff',
},
summaryDetails: {
marginTop: '20px',
},
summaryParagraph: {
margin: '10px 0',
},
};
export const MigrationSummary: React.FC<MigrationSummaryProps> = ({ visible, data, onDismiss }) => {
return (
<Modal title="Migration summary" isOpen={visible} closeOnBackdropClick={true} onDismiss={onDismiss}>
{data.failedApikeyIDs.length === 0 && (
<div style={styles.migrationSummary}>
<p>Migration Successful!</p>
<p>
<strong>Total: </strong>
{data.total}
</p>
<p>
<strong>Migrated: </strong>
{data.migrated}
</p>
</div>
)}
{data.failedApikeyIDs.length !== 0 && (
<div style={styles.migrationSummary}>
<p>
Migration Complete! Please note, while there might be a few API keys flagged as `failed migrations`, rest
assured, all of your API keys are fully functional and operational. Please try again or contact support.
</p>
<hr />
<p>
<strong>Total: </strong>
{data.total}
</p>
<p>
<strong>Migrated: </strong>
{data.migrated}
</p>
<p>
<strong>Failed: </strong>
{data.failed}
</p>
<p>
<strong>Failed Api Key IDs: </strong>
{data.failedApikeyIDs.join(', ')}
</p>
<p>
<strong>Failed Details: </strong>
{data.failedDetails.join(', ')}
</p>
</div>
)}
<Modal.ButtonRow>
<Button variant="secondary" onClick={onDismiss}>
Close
</Button>
</Modal.ButtonRow>
</Modal>
);
};
2018-09-25 09:23:43 -05:00
const ApiKeysPage = connector(ApiKeysPageUnconnected);
Build: Upgrade Webpack 5 (#36444) * build(webpack): bump to v5 and successful yarn start compilation * build(webpack): update postcss dependencies * build(webpack): silence warnings about hash renamed to fullhash * build(webpack): enable persistent cache to store generated webpack modules / chunks * build(webpack): prefer eslintWebpackPlugin over tschecker so eslint doesn't block typechecking * chore(yarn): run yarn-deduplicate to clean up dependencies * chore(yarn): refresh lock file after clean install * build(webpack): prefer output.clean over CleanWebpackPlugin * build(webpack): prefer esbuild over babel-loader for dev config * build(babel): turn off cache compression to improve build performance * build(webpack): get production builds working * build(webpack): remove phantomJS (removed from grafana in v7) specific loader * build(webpack): put back babel for dev builds no performance gain in using esbuild in webpack * build(webpack): prefer terser and optimise css plugins for prod. slower but smaller bundles * build(webpack): clean up redundant code. inform postcss about node_modules * build(webpack): remove deprecation warnings flag * build(webpack): bump packages, dev performance optimisations, attempt to get hot working * chore(storybook): use webpack 5 for dev and production builds * build(storybook): speed up dev build * chore(yarn): refresh lock file * chore(webpack): bump webpack and related deps to latest * refactor(webpack): put back inline-source-map, move start scripts out of grafana toolkit * feat(webpack): prefer react-refresh over react-hot-loader * build(webpack): update webpack.hot to use react-refresh * chore: remove react-hot-loader from codebase * refactor(queryeditorrow): fix circular dependency causing react-fast-refresh errors * revert(webpack): remove stats.errorDetails from common config * build(webpack): bump to v5 and successful yarn start compilation * build(webpack): update postcss dependencies * build(webpack): silence warnings about hash renamed to fullhash * build(webpack): enable persistent cache to store generated webpack modules / chunks * build(webpack): prefer eslintWebpackPlugin over tschecker so eslint doesn't block typechecking * chore(yarn): run yarn-deduplicate to clean up dependencies * chore(yarn): refresh lock file after clean install * build(webpack): prefer output.clean over CleanWebpackPlugin * build(webpack): prefer esbuild over babel-loader for dev config * build(babel): turn off cache compression to improve build performance * build(webpack): get production builds working * build(webpack): remove phantomJS (removed from grafana in v7) specific loader * build(webpack): put back babel for dev builds no performance gain in using esbuild in webpack * build(webpack): prefer terser and optimise css plugins for prod. slower but smaller bundles * build(webpack): clean up redundant code. inform postcss about node_modules * build(webpack): remove deprecation warnings flag * build(webpack): bump packages, dev performance optimisations, attempt to get hot working * chore(storybook): use webpack 5 for dev and production builds * build(storybook): speed up dev build * chore(yarn): refresh lock file * chore(webpack): bump webpack and related deps to latest * refactor(webpack): put back inline-source-map, move start scripts out of grafana toolkit * feat(webpack): prefer react-refresh over react-hot-loader * build(webpack): update webpack.hot to use react-refresh * chore: remove react-hot-loader from codebase * refactor(queryeditorrow): fix circular dependency causing react-fast-refresh errors * revert(webpack): remove stats.errorDetails from common config * revert(webpack): remove include from babel-loader so symlinks (enterprise) work as before * refactor(webpack): fix deprecation warnings in prod builds * fix(storybook): fix failing builds due to replacing css-optimise webpack plugin * fix(storybook): use raw-loader for svg icons * build(webpack): fix dev script colors error * chore(webpack): bump css-loader and react-refresh-webpack-plugin to latest versions Co-authored-by: Torkel Ödegaard <torkel@grafana.com>
2021-08-31 05:55:05 -05:00
export default ApiKeysPage;