mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-17 21:30:31 +00:00
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* @param { import("knex").Knex } knex
|
||||
* @returns { Promise<void> }
|
||||
*/
|
||||
exports.up = function (knex) {
|
||||
return knex.schema.createTable('api_keys', (table) => {
|
||||
table.increments();
|
||||
table.string('key').notNullable().unique().index();
|
||||
table.string('name');
|
||||
table
|
||||
.integer('user_id')
|
||||
.unsigned()
|
||||
.notNullable()
|
||||
.index()
|
||||
.references('id')
|
||||
.inTable('users');
|
||||
table
|
||||
.bigInteger('tenant_id')
|
||||
.unsigned()
|
||||
.notNullable()
|
||||
.index()
|
||||
.references('id')
|
||||
.inTable('tenants');
|
||||
table.dateTime('expires_at').nullable().index();
|
||||
table.dateTime('revoked_at').nullable().index();
|
||||
table.timestamps();
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @param { import("knex").Knex } knex
|
||||
* @returns { Promise<void> }
|
||||
*/
|
||||
exports.down = function (knex) {
|
||||
return knex.schema.dropTableIfExists('api_keys');
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Controller, Post, Param, Get, Put } from '@nestjs/common';
|
||||
import { Controller, Post, Param, Get, Put, Body } from '@nestjs/common';
|
||||
import { GenerateApiKey } from './commands/GenerateApiKey.service';
|
||||
import { GetApiKeysService } from './queries/GetApiKeys.service';
|
||||
import {
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
ApiParam,
|
||||
ApiExtraModels,
|
||||
getSchemaPath,
|
||||
ApiBody,
|
||||
ApiProperty,
|
||||
} from '@nestjs/swagger';
|
||||
import { ApiCommonHeaders } from '@/common/decorators/ApiCommonHeaders';
|
||||
import {
|
||||
@@ -16,6 +18,20 @@ import {
|
||||
ApiKeyListResponseDto,
|
||||
ApiKeyListItemDto,
|
||||
} from './dtos/ApiKey.dto';
|
||||
import { IsString, MaxLength } from 'class-validator';
|
||||
import { IsOptional } from '@/common/decorators/Validators';
|
||||
|
||||
class GenerateApiKeyDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
@ApiProperty({
|
||||
description: 'Optional name for the API key',
|
||||
required: false,
|
||||
example: 'My API Key',
|
||||
})
|
||||
name?: string;
|
||||
}
|
||||
|
||||
@Controller('api-keys')
|
||||
@ApiTags('Api keys')
|
||||
@@ -29,17 +45,18 @@ export class AuthApiKeysController {
|
||||
constructor(
|
||||
private readonly getApiKeysService: GetApiKeysService,
|
||||
private readonly generateApiKeyService: GenerateApiKey,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
@Post('generate')
|
||||
@ApiOperation({ summary: 'Generate a new API key' })
|
||||
@ApiBody({ type: GenerateApiKeyDto })
|
||||
@ApiResponse({
|
||||
status: 201,
|
||||
description: 'The generated API key',
|
||||
type: ApiKeyResponseDto,
|
||||
})
|
||||
async generate() {
|
||||
return this.generateApiKeyService.generate();
|
||||
async generate(@Body() body: GenerateApiKeyDto) {
|
||||
return this.generateApiKeyService.generate(body.name);
|
||||
}
|
||||
|
||||
@Put(':id/revoke')
|
||||
|
||||
@@ -10,14 +10,15 @@ export class GenerateApiKey {
|
||||
private readonly tenancyContext: TenancyContext,
|
||||
@Inject(ApiKeyModel.name)
|
||||
private readonly apiKeyModel: typeof ApiKeyModel,
|
||||
) {}
|
||||
) { }
|
||||
|
||||
/**
|
||||
* Generates a new secure API key for the current tenant and system user.
|
||||
* The key is saved in the database and returned (only the key and id for security).
|
||||
* @param {string} name - Optional name for the API key.
|
||||
* @returns {Promise<{ key: string; id: number }>} The generated API key and its database id.
|
||||
*/
|
||||
async generate() {
|
||||
async generate(name?: string) {
|
||||
const tenant = await this.tenancyContext.getTenant();
|
||||
const user = await this.tenancyContext.getSystemUser();
|
||||
|
||||
@@ -26,6 +27,7 @@ export class GenerateApiKey {
|
||||
// Save the API key to the database
|
||||
const apiKeyRecord = await this.apiKeyModel.query().insert({
|
||||
key,
|
||||
name,
|
||||
tenantId: tenant.id,
|
||||
userId: user.id,
|
||||
createdAt: new Date(),
|
||||
|
||||
@@ -29,6 +29,12 @@ export class ApiKeyListItemDto {
|
||||
@ApiProperty({ example: 'My API Key', description: 'API key name' })
|
||||
name?: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: 'bc_1234...',
|
||||
description: 'First 8 characters of the API key token',
|
||||
})
|
||||
token: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: '2024-01-01T00:00:00.000Z',
|
||||
description: 'Creation date',
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { Transformer } from '@/modules/Transformer/Transformer';
|
||||
|
||||
export class GetApiKeysTransformer extends Transformer {
|
||||
|
||||
public includeAttributes = (): string[] => {
|
||||
return ['token'];
|
||||
};
|
||||
|
||||
public excludeAttributes = (): string[] => {
|
||||
return ['tenantId'];
|
||||
};
|
||||
|
||||
public token(apiKey) {
|
||||
return apiKey.key ? `${apiKey.key.substring(0, 8)}...` : '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ import { RuleFormDialog } from '@/containers/Banking/Rules/RuleFormDialog/RuleFo
|
||||
import { DisconnectBankAccountDialog } from '@/containers/CashFlow/AccountTransactions/dialogs/DisconnectBankAccountDialog/DisconnectBankAccountDialog';
|
||||
import { SharePaymentLinkDialog } from '@/containers/PaymentLink/dialogs/SharePaymentLinkDialog/SharePaymentLinkDialog';
|
||||
import { SelectPaymentMethodsDialog } from '@/containers/PaymentLink/dialogs/SelectPaymentMethodsDialog/SelectPaymentMethodsDialog';
|
||||
import ApiKeysGenerateDialog from '@/containers/Dialogs/ApiKeysGenerateDialog';
|
||||
|
||||
/**
|
||||
* Dialogs container.
|
||||
@@ -147,6 +148,9 @@ export default function DialogsContainer() {
|
||||
<SelectPaymentMethodsDialog
|
||||
dialogName={DialogsName.SelectPaymentMethod}
|
||||
/>
|
||||
<ApiKeysGenerateDialog
|
||||
dialogName={DialogsName.ApiKeysGenerate}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -80,5 +80,6 @@ export enum DialogsName {
|
||||
SharePaymentLink = 'SharePaymentLink',
|
||||
SelectPaymentMethod = 'SelectPaymentMethodsDialog',
|
||||
|
||||
StripeSetup = 'StripeSetup'
|
||||
StripeSetup = 'StripeSetup',
|
||||
ApiKeysGenerate = 'api-keys-generate'
|
||||
}
|
||||
|
||||
@@ -68,6 +68,11 @@ export default [
|
||||
disabled: false,
|
||||
href: '/preferences/integrations'
|
||||
},
|
||||
{
|
||||
text: 'API Keys',
|
||||
disabled: false,
|
||||
href: '/preferences/api-keys',
|
||||
},
|
||||
// {
|
||||
// text: <T id={'sms_integration.label'} />,
|
||||
// disabled: false,
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import {
|
||||
Classes,
|
||||
Button,
|
||||
InputGroup,
|
||||
FormGroup,
|
||||
Intent,
|
||||
Position,
|
||||
Tooltip,
|
||||
} from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
import { FormattedMessage as T, Icon, Alert } from '@/components';
|
||||
import { useClipboard } from '@/hooks/utils/useClipboard';
|
||||
import { AppToaster } from '@/components';
|
||||
|
||||
/**
|
||||
* API Key Display view component (used within the generate dialog).
|
||||
*/
|
||||
function ApiKeyDisplayView({
|
||||
dialogName,
|
||||
apiKey,
|
||||
onClose,
|
||||
}) {
|
||||
const clipboard = useClipboard();
|
||||
|
||||
const handleCopy = () => {
|
||||
if (apiKey) {
|
||||
clipboard.copy(apiKey);
|
||||
AppToaster.show({
|
||||
message: intl.get('api_key.copied_to_clipboard'),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={Classes.DIALOG_BODY}>
|
||||
<Alert intent="primary">
|
||||
<strong>{intl.get('api_key.important')}:</strong> {intl.get('api_key.display_warning')}
|
||||
</Alert>
|
||||
<FormGroup label={intl.get('api_key.label')}>
|
||||
<InputGroup
|
||||
value={apiKey || ''}
|
||||
readOnly
|
||||
rightElement={
|
||||
<Tooltip content={intl.get('api_key.copy_to_clipboard')} position={Position.TOP}>
|
||||
<Button
|
||||
onClick={handleCopy}
|
||||
minimal
|
||||
icon={<Icon icon={'clipboard'} iconSize={16} />}
|
||||
/>
|
||||
</Tooltip>
|
||||
}
|
||||
/>
|
||||
</FormGroup>
|
||||
</div>
|
||||
|
||||
<div className={Classes.DIALOG_FOOTER}>
|
||||
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
|
||||
<Button intent={Intent.PRIMARY} onClick={onClose} style={{ width: '85px' }}>
|
||||
<T id={'done'} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default ApiKeyDisplayView;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
// @ts-nocheck
|
||||
import React, { useState } from 'react';
|
||||
import { Dialog, DialogSuspense, FormattedMessage as T } from '@/components';
|
||||
import withDialogRedux from '@/components/DialogReduxConnect';
|
||||
import { compose } from '@/utils';
|
||||
|
||||
const ApiKeysGenerateDialogContent = React.lazy(
|
||||
() => import('./ApiKeysGenerateDialogContent'),
|
||||
);
|
||||
|
||||
/**
|
||||
* API Keys Generate dialog.
|
||||
*/
|
||||
function ApiKeysGenerateDialog({ dialogName, payload, isOpen }) {
|
||||
return (
|
||||
<Dialog
|
||||
name={dialogName}
|
||||
title={
|
||||
<T id={'api_key.dialog.generate_title'} />
|
||||
}
|
||||
isOpen={isOpen}
|
||||
canEscapeJeyClose={true}
|
||||
autoFocus={true}
|
||||
className={'dialog--api-keys-generate'}
|
||||
style={{ width: '500px' }}
|
||||
>
|
||||
<DialogSuspense>
|
||||
<ApiKeysGenerateDialogContent
|
||||
dialogName={dialogName}
|
||||
/>
|
||||
</DialogSuspense>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
export default compose(withDialogRedux())(ApiKeysGenerateDialog);
|
||||
@@ -0,0 +1,86 @@
|
||||
// @ts-nocheck
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Formik } from 'formik';
|
||||
import intl from 'react-intl-universal';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import { AppToaster } from '@/components';
|
||||
import { useGenerateApiKey } from '@/hooks/query';
|
||||
import ApiKeysGenerateFormContent from './ApiKeysGenerateFormContent';
|
||||
import ApiKeysGenerateFormSchema from './ApiKeysGenerateForm.schema';
|
||||
import ApiKeyDisplayView from './ApiKeyDisplayView';
|
||||
import withDialogActions from '@/containers/Dialog/withDialogActions';
|
||||
import { compose } from '@/utils';
|
||||
|
||||
const defaultInitialValues = {
|
||||
name: '',
|
||||
};
|
||||
|
||||
/**
|
||||
* API Keys Generate form dialog content.
|
||||
*/
|
||||
function ApiKeysGenerateDialogContent({
|
||||
// #withDialogActions
|
||||
closeDialog,
|
||||
dialogName,
|
||||
}) {
|
||||
const [generatedApiKey, setGeneratedApiKey] = useState(null);
|
||||
const generateApiKeyMutate = useGenerateApiKey();
|
||||
|
||||
// Handles the form submit.
|
||||
const handleFormSubmit = (values, { setSubmitting, setErrors }) => {
|
||||
const form = { name: values.name || undefined };
|
||||
|
||||
// Handle request response errors.
|
||||
const handleError = (error) => {
|
||||
const errors = error?.response?.data?.errors;
|
||||
if (errors) {
|
||||
const errorsTransformed = Object.keys(errors).reduce((acc, key) => {
|
||||
acc[key] = errors[key][0];
|
||||
return acc;
|
||||
}, {});
|
||||
setErrors(errorsTransformed);
|
||||
}
|
||||
setSubmitting(false);
|
||||
};
|
||||
|
||||
generateApiKeyMutate.mutate(form, {
|
||||
onSuccess: (response) => {
|
||||
// The API returns { key, id }, which might be wrapped in response.data
|
||||
const apiKey = response?.data?.key || response?.key;
|
||||
if (apiKey) {
|
||||
setGeneratedApiKey(apiKey);
|
||||
} else {
|
||||
setSubmitting(false);
|
||||
}
|
||||
},
|
||||
onError: handleError,
|
||||
});
|
||||
};
|
||||
|
||||
// If API key has been generated, show the display view
|
||||
if (generatedApiKey) {
|
||||
return (
|
||||
<ApiKeyDisplayView
|
||||
dialogName={dialogName}
|
||||
apiKey={generatedApiKey}
|
||||
onClose={() => {
|
||||
setGeneratedApiKey(null);
|
||||
closeDialog(dialogName);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Otherwise, show the generate form
|
||||
return (
|
||||
<Formik
|
||||
validationSchema={ApiKeysGenerateFormSchema}
|
||||
initialValues={defaultInitialValues}
|
||||
onSubmit={handleFormSubmit}
|
||||
>
|
||||
<ApiKeysGenerateFormContent dialogName={dialogName} />
|
||||
</Formik>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withDialogActions)(ApiKeysGenerateDialogContent);
|
||||
@@ -0,0 +1,10 @@
|
||||
// @ts-nocheck
|
||||
import * as Yup from 'yup';
|
||||
|
||||
export const CreateApiKeyFormSchema = Yup.object().shape({
|
||||
name: Yup.string()
|
||||
.required('Name is required')
|
||||
.max(255, 'Name must be at most 255 characters'),
|
||||
});
|
||||
|
||||
export default CreateApiKeyFormSchema;
|
||||
@@ -0,0 +1,67 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { Form, useFormikContext } from 'formik';
|
||||
import {
|
||||
Classes,
|
||||
Button,
|
||||
Intent,
|
||||
} from '@blueprintjs/core';
|
||||
import { FastField, ErrorMessage } from 'formik';
|
||||
import {
|
||||
FormGroup,
|
||||
InputGroup,
|
||||
} from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
import { inputIntent } from '@/utils';
|
||||
import { FFormGroup, FInputGroup, FormattedMessage as T } from '@/components';
|
||||
import withDialogActions from '@/containers/Dialog/withDialogActions';
|
||||
import { compose } from '@/utils';
|
||||
|
||||
/**
|
||||
* API Keys Generate form content.
|
||||
*/
|
||||
function ApiKeysGenerateFormContent({
|
||||
dialogName,
|
||||
// #withDialogActions
|
||||
closeDialog,
|
||||
}) {
|
||||
const { isSubmitting } = useFormikContext();
|
||||
|
||||
const handleClose = () => {
|
||||
closeDialog(dialogName);
|
||||
};
|
||||
|
||||
return (
|
||||
<Form>
|
||||
<div className={Classes.DIALOG_BODY}>
|
||||
{/* ----------- Name ----------- */}
|
||||
<FFormGroup
|
||||
name={'name'}
|
||||
label={<T id={'api_key.name'} />}
|
||||
>
|
||||
<FInputGroup name={'name'} placeholder={intl.get('api_key.name_placeholder')} />
|
||||
</FFormGroup>
|
||||
</div>
|
||||
|
||||
<div className={Classes.DIALOG_FOOTER}>
|
||||
<div className={Classes.DIALOG_FOOTER_ACTIONS}>
|
||||
<Button onClick={handleClose} disabled={isSubmitting}>
|
||||
<T id={'cancel'} />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
intent={Intent.PRIMARY}
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
style={{ minWidth: '100px' }}
|
||||
>
|
||||
<T id={'api_key.generate'} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withDialogActions)(ApiKeysGenerateFormContent);
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from './ApiKeysGenerateDialog';
|
||||
@@ -0,0 +1,42 @@
|
||||
// @ts-nocheck
|
||||
import React, { useEffect } from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import classNames from 'classnames';
|
||||
import styled from 'styled-components';
|
||||
|
||||
import { Card } from '@/components';
|
||||
import { CLASSES } from '@/constants/classes';
|
||||
import withDashboardActions from '@/containers/Dashboard/withDashboardActions';
|
||||
import ApiKeysDataTable from './ApiKeysDataTable';
|
||||
import { compose } from '@/utils';
|
||||
|
||||
/**
|
||||
* API Keys preferences page.
|
||||
*/
|
||||
function ApiKeysPreferences({
|
||||
// #withDashboardActions
|
||||
changePreferencesPageTitle,
|
||||
}) {
|
||||
useEffect(() => {
|
||||
changePreferencesPageTitle(intl.get('api_key.title'));
|
||||
}, [changePreferencesPageTitle]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
CLASSES.PREFERENCES_PAGE_INSIDE_CONTENT,
|
||||
CLASSES.PREFERENCES_PAGE_INSIDE_CONTENT_USERS,
|
||||
)}
|
||||
>
|
||||
<ApiKeysPreferencesCard>
|
||||
<ApiKeysDataTable />
|
||||
</ApiKeysPreferencesCard>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ApiKeysPreferencesCard = styled(Card)`
|
||||
padding: 0;
|
||||
`;
|
||||
|
||||
export default compose(withDashboardActions)(ApiKeysPreferences);
|
||||
@@ -0,0 +1,29 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
|
||||
import { Button, Intent } from '@blueprintjs/core';
|
||||
import { Icon, FormattedMessage as T } from '@/components';
|
||||
|
||||
import withDialogActions from '@/containers/Dialog/withDialogActions';
|
||||
import { compose } from '@/utils';
|
||||
|
||||
function ApiKeysActions({ openDialog, closeDialog }) {
|
||||
const onClickGenerateApiKey = () => {
|
||||
openDialog('api-keys-generate');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="preferences-actions">
|
||||
<Button
|
||||
icon={<Icon icon="plus" iconSize={12} />}
|
||||
onClick={onClickGenerateApiKey}
|
||||
intent={Intent.PRIMARY}
|
||||
>
|
||||
<T id={'api_key.generate_button'} />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withDialogActions)(ApiKeysActions);
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// @ts-nocheck
|
||||
import React, { useCallback } from 'react';
|
||||
import { compose } from '@/utils';
|
||||
import { DataTable, TableSkeletonRows, AppToaster } from '@/components';
|
||||
import { useApiKeys, useRevokeApiKey } from '@/hooks/query';
|
||||
import withDialogActions from '@/containers/Dialog/withDialogActions';
|
||||
import withAlertActions from '@/containers/Alert/withAlertActions';
|
||||
import { ActionsMenu, useApiKeysTableColumns } from './components';
|
||||
import { Intent } from '@blueprintjs/core';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
/**
|
||||
* API Keys datatable.
|
||||
*/
|
||||
function ApiKeysDataTable({
|
||||
// #withDialogActions
|
||||
openDialog,
|
||||
|
||||
// #withAlertActions
|
||||
openAlert,
|
||||
}) {
|
||||
const { data: apiKeys, isLoading, isFetching } = useApiKeys();
|
||||
const { mutateAsync: revokeApiKey } = useRevokeApiKey();
|
||||
|
||||
// API Keys list columns.
|
||||
const columns = useApiKeysTableColumns();
|
||||
|
||||
// Handle revoke API key action.
|
||||
const handleRevokeApiKey = useCallback(
|
||||
(apiKey) => {
|
||||
revokeApiKey(apiKey.id)
|
||||
.then(() => {
|
||||
AppToaster.show({
|
||||
message: intl.get('api_key.revoke_success'),
|
||||
intent: Intent.SUCCESS,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
AppToaster.show({
|
||||
message: error?.response?.data?.message || intl.get('something_went_wrong'),
|
||||
intent: Intent.DANGER,
|
||||
});
|
||||
});
|
||||
},
|
||||
[revokeApiKey],
|
||||
);
|
||||
|
||||
return (
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={apiKeys || []}
|
||||
loading={isLoading}
|
||||
headerLoading={isLoading}
|
||||
progressBarLoading={isFetching}
|
||||
TableLoadingRenderer={TableSkeletonRows}
|
||||
noInitialFetch={true}
|
||||
ContextMenu={ActionsMenu}
|
||||
payload={{
|
||||
onRevoke: handleRevokeApiKey,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default compose(withDialogActions, withAlertActions)(ApiKeysDataTable);
|
||||
@@ -0,0 +1,135 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import { FormattedMessage as T, Icon } from '@/components';
|
||||
import {
|
||||
Intent,
|
||||
Button,
|
||||
Popover,
|
||||
Menu,
|
||||
MenuItem,
|
||||
Position,
|
||||
Tag,
|
||||
} from '@blueprintjs/core';
|
||||
import { safeCallback } from '@/utils';
|
||||
import { FormatDateCell } from '@/components/Utils/FormatDate';
|
||||
|
||||
/**
|
||||
* API Keys table actions menu.
|
||||
*/
|
||||
export function ActionsMenu({
|
||||
row: { original },
|
||||
payload: { onRevoke },
|
||||
}) {
|
||||
return (
|
||||
<Menu>
|
||||
<MenuItem
|
||||
icon={<Icon icon="trash-16" iconSize={16} />}
|
||||
text={intl.get('api_key.revoke')}
|
||||
onClick={safeCallback(onRevoke, original)}
|
||||
intent={Intent.DANGER}
|
||||
/>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Token accessor.
|
||||
* Displays the token value in a Tag component.
|
||||
*/
|
||||
function TokenAccessor(apiKey) {
|
||||
return (
|
||||
<Tag minimal={true}>
|
||||
{apiKey.token || ''}
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Permissions accessor.
|
||||
* Since permissions aren't currently stored, we show a default message.
|
||||
*/
|
||||
function PermissionsAccessor(apiKey) {
|
||||
return (
|
||||
<Tag>
|
||||
<T id={'api_key.full_access'} />
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Last Used accessor.
|
||||
* Since lastUsed isn't currently tracked, we show "Never".
|
||||
*/
|
||||
function LastUsedAccessor(apiKey) {
|
||||
return <span>{intl.get('api_key.never')}</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Actions cell.
|
||||
*/
|
||||
function ActionsCell(props) {
|
||||
return (
|
||||
<Popover
|
||||
content={<ActionsMenu {...props} />}
|
||||
position={Position.RIGHT_BOTTOM}
|
||||
>
|
||||
<Button icon={<Icon icon="more-h-16" iconSize={16} />} />
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve API Keys table columns.
|
||||
*/
|
||||
export function useApiKeysTableColumns() {
|
||||
return React.useMemo(
|
||||
() => [
|
||||
{
|
||||
id: 'name',
|
||||
Header: intl.get('api_key.name'),
|
||||
accessor: (row) => row.name || intl.get('api_key.unnamed'),
|
||||
width: 200,
|
||||
className: 'name',
|
||||
},
|
||||
{
|
||||
id: 'token',
|
||||
Header: intl.get('api_key.token'),
|
||||
accessor: TokenAccessor,
|
||||
width: 100,
|
||||
className: 'token',
|
||||
},
|
||||
{
|
||||
id: 'permissions',
|
||||
Header: intl.get('api_key.permissions'),
|
||||
accessor: PermissionsAccessor,
|
||||
width: 150,
|
||||
className: 'permissions',
|
||||
},
|
||||
{
|
||||
id: 'last_used',
|
||||
Header: intl.get('api_key.last_used'),
|
||||
accessor: LastUsedAccessor,
|
||||
width: 150,
|
||||
className: 'last_used',
|
||||
},
|
||||
{
|
||||
id: 'created_at',
|
||||
Header: intl.get('api_key.generated_at'),
|
||||
accessor: 'createdAt',
|
||||
Cell: FormatDateCell,
|
||||
width: 150,
|
||||
className: 'created_at',
|
||||
},
|
||||
{
|
||||
id: 'actions',
|
||||
Header: '',
|
||||
Cell: ActionsCell,
|
||||
className: 'actions',
|
||||
width: 50,
|
||||
disableResizing: true,
|
||||
},
|
||||
],
|
||||
[],
|
||||
);
|
||||
}
|
||||
57
packages/webapp/src/hooks/query/apiKeys.tsx
Normal file
57
packages/webapp/src/hooks/query/apiKeys.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
// @ts-nocheck
|
||||
import { useMutation, useQueryClient } from 'react-query';
|
||||
import { useRequestQuery } from '../useQueryRequest';
|
||||
import useApiRequest from '../useRequest';
|
||||
import t from './types';
|
||||
|
||||
const commonInvalidateQueries = (query) => {
|
||||
query.invalidateQueries(t.API_KEYS);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve API keys list.
|
||||
*/
|
||||
export function useApiKeys(props) {
|
||||
return useRequestQuery(
|
||||
[t.API_KEYS],
|
||||
{ method: 'get', url: 'api-keys' },
|
||||
{
|
||||
select: (res) => res.data || [],
|
||||
defaultData: [],
|
||||
...props,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a new API key.
|
||||
*/
|
||||
export function useGenerateApiKey(props) {
|
||||
const client = useQueryClient();
|
||||
const apiRequest = useApiRequest();
|
||||
|
||||
return useMutation((values) => apiRequest.post('api-keys/generate', values), {
|
||||
onSuccess: () => {
|
||||
commonInvalidateQueries(client);
|
||||
},
|
||||
...props,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Revokes the given API key.
|
||||
*/
|
||||
export function useRevokeApiKey(props) {
|
||||
const client = useQueryClient();
|
||||
const apiRequest = useApiRequest();
|
||||
|
||||
return useMutation(
|
||||
(id) => apiRequest.put(`api-keys/${id}/revoke`),
|
||||
{
|
||||
onSuccess: () => {
|
||||
commonInvalidateQueries(client);
|
||||
},
|
||||
...props,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -38,3 +38,4 @@ export * from './branches';
|
||||
export * from './warehousesTransfers';
|
||||
export * from './plaid';
|
||||
export * from './FinancialReports';
|
||||
export * from './apiKeys';
|
||||
|
||||
@@ -241,6 +241,10 @@ export const EXCHANGE_RATE = {
|
||||
EXCHANGE_RATE: 'EXCHANGE_RATE',
|
||||
};
|
||||
|
||||
export const API_KEYS = {
|
||||
API_KEYS: 'API_KEYS',
|
||||
};
|
||||
|
||||
export default {
|
||||
...Authentication,
|
||||
...ACCOUNTS,
|
||||
@@ -276,4 +280,5 @@ export default {
|
||||
...ORGANIZATION,
|
||||
...TAX_RATES,
|
||||
...EXCHANGE_RATE,
|
||||
...API_KEYS,
|
||||
};
|
||||
|
||||
@@ -62,6 +62,7 @@
|
||||
"edit": "Edit",
|
||||
"submit": "Submit",
|
||||
"close": "Close",
|
||||
"done": "Done",
|
||||
"edit_account": "Edit Account",
|
||||
"new_account": "New Account",
|
||||
"edit_currency": "Edit Currency",
|
||||
@@ -2240,8 +2241,29 @@
|
||||
"preferences.estimates": "Estimates",
|
||||
"preferences.creditNotes": "Credit Notes",
|
||||
"preferences.receipts": "Receipts",
|
||||
"preferences.estimates.success_message": "The preferences have been saved successfully.",
|
||||
"preferences.credit_notes.success_message": "The preferences have been saved successfully.",
|
||||
"preferences.receipts.success_message": "The preferences have been saved successfully.",
|
||||
"preferences.invoices.success_message": "The preferences have been saved successfully."
|
||||
"preferences.estimates.success_message": "The preferences have been saved successfully.",
|
||||
"preferences.credit_notes.success_message": "The preferences have been saved successfully.",
|
||||
"preferences.receipts.success_message": "The preferences have been saved successfully.",
|
||||
"preferences.invoices.success_message": "The preferences have been saved successfully.",
|
||||
"api_key.title": "API Keys",
|
||||
"api_key.name": "Name",
|
||||
"api_key.unnamed": "Unnamed",
|
||||
"api_key.token": "Token",
|
||||
"api_key.permissions": "Permissions",
|
||||
"api_key.last_used": "Last Used",
|
||||
"api_key.generated_at": "Generated At",
|
||||
"api_key.never": "Never",
|
||||
"api_key.revoke": "Revoke",
|
||||
"api_key.revoke_success": "API key revoked successfully",
|
||||
"api_key.full_access": "Full Access",
|
||||
"api_key.generate_button": "Generate API Key",
|
||||
"api_key.generate": "Generate",
|
||||
"api_key.name_placeholder": "Enter API key name",
|
||||
"api_key.dialog.generate_title": "Generate API Key",
|
||||
"api_key.dialog.display_title": "API Key Generated",
|
||||
"api_key.copied_to_clipboard": "API key copied to clipboard",
|
||||
"api_key.important": "Important",
|
||||
"api_key.display_warning": "This API key will only be shown once. Please copy and save it securely.",
|
||||
"api_key.label": "API Key",
|
||||
"api_key.copy_to_clipboard": "Copy to clipboard"
|
||||
}
|
||||
@@ -122,6 +122,11 @@ export const getPreferenceRoutes = () => [
|
||||
component: lazy(() => import('@/containers/Subscriptions/BillingPage')),
|
||||
exact: true,
|
||||
},
|
||||
{
|
||||
path: `${BASE_URL}/api-keys`,
|
||||
component: lazy(() => import('@/containers/Preferences/ApiKeys/ApiKeys')),
|
||||
exact: true,
|
||||
},
|
||||
{
|
||||
path: `${BASE_URL}/`,
|
||||
component: lazy(() => import('../containers/Preferences/DefaultRoute')),
|
||||
|
||||
Reference in New Issue
Block a user