The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
grafana/public/app/features/serviceaccounts/ServiceAccountCreatePage.tsx

147 lines
5.0 KiB

import React, { useCallback, useEffect, useState } from 'react';
import { getBackendSrv, locationService } from '@grafana/runtime';
import { Form, Button, Input, Field, FieldSet } from '@grafana/ui';
import { Page } from 'app/core/components/Page/Page';
import { UserRolePicker } from 'app/core/components/RolePicker/UserRolePicker';
import { fetchRoleOptions, updateUserRoles } from 'app/core/components/RolePicker/api';
import { contextSrv } from 'app/core/core';
import { AccessControlAction, OrgRole, Role, ServiceAccountCreateApiResponse, ServiceAccountDTO } from 'app/types';
ServiceAccounts: refactor UI (#49508) * ServiceAccounts: refactor ServiceAccountRoleRow * Refactor ServiceAccountRoleRow * Refactor ServiceAccountProfile * Refactor components * Change service accounts icon * Refine service accounts page header * Improve service accounts filtering * Change delete button style * Tweak account id * Auto focus name field when create service account * Add disable/enable button * Enable/disable service accounts * Optimize updating service account (do not fetch all) * Remove status column (replace by enable/disable button) * Add banner with service accounts description * Add tokens from main page * Update tokens count when add token from main page * Fix action buttons column * Fix tokens count when change role * Refine table row classes * Fix buttons * Simplify working with state * Show message when service account updated * Able to filter disabled accounts * Mark disabled accounts in a table * Refine disabled account view * Move non-critical components to separate folder * Remove confusing focusing * Fix date picker position when creating new token * DatePicker: able to set minimum date that can be selected * Don't allow to select expiration dates prior today * Set tomorrow as a default token expiration date * Fix displaying expiration period * Rename Add token button * Refine page styles * Show modal when disabling SA from main page * Arrange role picker * Refine SA page styles * Generate default token name * More smooth navigation between SA pages * Stop loading indicator in case of error * Remove legacy styles usage * Tweaks after code review Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Get rid of useDisapatch in favor of mapDispatchToProps * Tests for ServiceAccountsListPage * Tests for service account page * Show new role picker only with license * Get rid of deprecated css classes * Apply suggestion from code review Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Fix service accounts icon * Tests for service account create page * Return service account info when update * Add behaviour tests for ServiceAccountsListPage * Fix disabled cursor on confirm button * More behavior tests for service account page * Temporary disable service account migration banner * Use safe where condition Co-authored-by: Jguer <joao.guerreiro@grafana.com> * Apply review suggestions Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Remove autofocus from search Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> Co-authored-by: Jguer <joao.guerreiro@grafana.com>
4 years ago
import { OrgRolePicker } from '../admin/OrgRolePicker';
export interface Props {}
ServiceAccounts: refactor UI (#49508) * ServiceAccounts: refactor ServiceAccountRoleRow * Refactor ServiceAccountRoleRow * Refactor ServiceAccountProfile * Refactor components * Change service accounts icon * Refine service accounts page header * Improve service accounts filtering * Change delete button style * Tweak account id * Auto focus name field when create service account * Add disable/enable button * Enable/disable service accounts * Optimize updating service account (do not fetch all) * Remove status column (replace by enable/disable button) * Add banner with service accounts description * Add tokens from main page * Update tokens count when add token from main page * Fix action buttons column * Fix tokens count when change role * Refine table row classes * Fix buttons * Simplify working with state * Show message when service account updated * Able to filter disabled accounts * Mark disabled accounts in a table * Refine disabled account view * Move non-critical components to separate folder * Remove confusing focusing * Fix date picker position when creating new token * DatePicker: able to set minimum date that can be selected * Don't allow to select expiration dates prior today * Set tomorrow as a default token expiration date * Fix displaying expiration period * Rename Add token button * Refine page styles * Show modal when disabling SA from main page * Arrange role picker * Refine SA page styles * Generate default token name * More smooth navigation between SA pages * Stop loading indicator in case of error * Remove legacy styles usage * Tweaks after code review Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Get rid of useDisapatch in favor of mapDispatchToProps * Tests for ServiceAccountsListPage * Tests for service account page * Show new role picker only with license * Get rid of deprecated css classes * Apply suggestion from code review Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Fix service accounts icon * Tests for service account create page * Return service account info when update * Add behaviour tests for ServiceAccountsListPage * Fix disabled cursor on confirm button * More behavior tests for service account page * Temporary disable service account migration banner * Use safe where condition Co-authored-by: Jguer <joao.guerreiro@grafana.com> * Apply review suggestions Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Remove autofocus from search Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> Co-authored-by: Jguer <joao.guerreiro@grafana.com>
4 years ago
const createServiceAccount = async (sa: ServiceAccountDTO) => {
const result = await getBackendSrv().post('/api/serviceaccounts/', sa);
await contextSrv.fetchUserPermissions();
return result;
};
ServiceAccounts: refactor UI (#49508) * ServiceAccounts: refactor ServiceAccountRoleRow * Refactor ServiceAccountRoleRow * Refactor ServiceAccountProfile * Refactor components * Change service accounts icon * Refine service accounts page header * Improve service accounts filtering * Change delete button style * Tweak account id * Auto focus name field when create service account * Add disable/enable button * Enable/disable service accounts * Optimize updating service account (do not fetch all) * Remove status column (replace by enable/disable button) * Add banner with service accounts description * Add tokens from main page * Update tokens count when add token from main page * Fix action buttons column * Fix tokens count when change role * Refine table row classes * Fix buttons * Simplify working with state * Show message when service account updated * Able to filter disabled accounts * Mark disabled accounts in a table * Refine disabled account view * Move non-critical components to separate folder * Remove confusing focusing * Fix date picker position when creating new token * DatePicker: able to set minimum date that can be selected * Don't allow to select expiration dates prior today * Set tomorrow as a default token expiration date * Fix displaying expiration period * Rename Add token button * Refine page styles * Show modal when disabling SA from main page * Arrange role picker * Refine SA page styles * Generate default token name * More smooth navigation between SA pages * Stop loading indicator in case of error * Remove legacy styles usage * Tweaks after code review Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Get rid of useDisapatch in favor of mapDispatchToProps * Tests for ServiceAccountsListPage * Tests for service account page * Show new role picker only with license * Get rid of deprecated css classes * Apply suggestion from code review Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Fix service accounts icon * Tests for service account create page * Return service account info when update * Add behaviour tests for ServiceAccountsListPage * Fix disabled cursor on confirm button * More behavior tests for service account page * Temporary disable service account migration banner * Use safe where condition Co-authored-by: Jguer <joao.guerreiro@grafana.com> * Apply review suggestions Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Remove autofocus from search Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> Co-authored-by: Jguer <joao.guerreiro@grafana.com>
4 years ago
const updateServiceAccount = async (id: number, sa: ServiceAccountDTO) =>
getBackendSrv().patch(`/api/serviceaccounts/${id}`, sa);
export const ServiceAccountCreatePage = ({}: Props): JSX.Element => {
const [roleOptions, setRoleOptions] = useState<Role[]>([]);
const [pendingRoles, setPendingRoles] = useState<Role[]>([]);
const currentOrgId = contextSrv.user.orgId;
const [serviceAccount, setServiceAccount] = useState<ServiceAccountDTO>({
id: 0,
orgId: contextSrv.user.orgId,
role: OrgRole.Viewer,
tokens: 0,
name: '',
login: '',
isDisabled: false,
createdAt: '',
teams: [],
});
useEffect(() => {
async function fetchOptions() {
try {
if (contextSrv.hasPermission(AccessControlAction.ActionRolesList)) {
let options = await fetchRoleOptions(currentOrgId);
setRoleOptions(options);
}
} catch (e) {
console.error('Error loading options', e);
}
}
if (contextSrv.licensedAccessControlEnabled()) {
fetchOptions();
}
}, [currentOrgId]);
const onSubmit = useCallback(
async (data: ServiceAccountDTO) => {
data.role = serviceAccount.role;
const response = await createServiceAccount(data);
try {
const newAccount: ServiceAccountCreateApiResponse = {
avatarUrl: response.avatarUrl,
id: response.id,
isDisabled: response.isDisabled,
login: response.login,
name: response.name,
orgId: response.orgId,
role: response.role,
tokens: response.tokens,
};
await updateServiceAccount(response.id, data);
if (
contextSrv.licensedAccessControlEnabled() &&
contextSrv.hasPermission(AccessControlAction.ActionUserRolesAdd) &&
contextSrv.hasPermission(AccessControlAction.ActionUserRolesRemove)
) {
await updateUserRoles(pendingRoles, newAccount.id, newAccount.orgId);
}
} catch (e) {
console.error(e);
}
locationService.push(`/org/serviceaccounts/${response.id}`);
},
[serviceAccount.role, pendingRoles]
);
const onRoleChange = (role: OrgRole) => {
setServiceAccount({
...serviceAccount,
role: role,
});
};
const onPendingRolesUpdate = (roles: Role[], userId: number, orgId: number | undefined) => {
// keep the new role assignments for user
setPendingRoles(roles);
};
return (
<Page navId="serviceaccounts" pageNav={{ text: 'Create service account' }}>
<Page.Contents>
<Page.OldNavOnly>
<h3 className="page-sub-heading">Create service account</h3>
</Page.OldNavOnly>
ServiceAccounts: refactor UI (#49508) * ServiceAccounts: refactor ServiceAccountRoleRow * Refactor ServiceAccountRoleRow * Refactor ServiceAccountProfile * Refactor components * Change service accounts icon * Refine service accounts page header * Improve service accounts filtering * Change delete button style * Tweak account id * Auto focus name field when create service account * Add disable/enable button * Enable/disable service accounts * Optimize updating service account (do not fetch all) * Remove status column (replace by enable/disable button) * Add banner with service accounts description * Add tokens from main page * Update tokens count when add token from main page * Fix action buttons column * Fix tokens count when change role * Refine table row classes * Fix buttons * Simplify working with state * Show message when service account updated * Able to filter disabled accounts * Mark disabled accounts in a table * Refine disabled account view * Move non-critical components to separate folder * Remove confusing focusing * Fix date picker position when creating new token * DatePicker: able to set minimum date that can be selected * Don't allow to select expiration dates prior today * Set tomorrow as a default token expiration date * Fix displaying expiration period * Rename Add token button * Refine page styles * Show modal when disabling SA from main page * Arrange role picker * Refine SA page styles * Generate default token name * More smooth navigation between SA pages * Stop loading indicator in case of error * Remove legacy styles usage * Tweaks after code review Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Get rid of useDisapatch in favor of mapDispatchToProps * Tests for ServiceAccountsListPage * Tests for service account page * Show new role picker only with license * Get rid of deprecated css classes * Apply suggestion from code review Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Fix service accounts icon * Tests for service account create page * Return service account info when update * Add behaviour tests for ServiceAccountsListPage * Fix disabled cursor on confirm button * More behavior tests for service account page * Temporary disable service account migration banner * Use safe where condition Co-authored-by: Jguer <joao.guerreiro@grafana.com> * Apply review suggestions Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> * Remove autofocus from search Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com> Co-authored-by: Jguer <joao.guerreiro@grafana.com>
4 years ago
<Form onSubmit={onSubmit} validateOn="onSubmit">
{({ register, errors }) => {
return (
<>
<FieldSet>
<Field
label="Display name"
required
invalid={!!errors.name}
error={errors.name ? 'Display name is required' : undefined}
>
<Input id="display-name-input" {...register('name', { required: true })} autoFocus />
</Field>
<Field label="Role">
{contextSrv.licensedAccessControlEnabled() ? (
<UserRolePicker
apply
userId={serviceAccount.id || 0}
orgId={serviceAccount.orgId}
basicRole={serviceAccount.role}
onBasicRoleChange={onRoleChange}
roleOptions={roleOptions}
onApplyRoles={onPendingRolesUpdate}
pendingRoles={pendingRoles}
/>
) : (
<OrgRolePicker aria-label="Role" value={serviceAccount.role} onChange={onRoleChange} />
)}
</Field>
</FieldSet>
<Button type="submit">Create</Button>
</>
);
}}
</Form>
</Page.Contents>
</Page>
);
};
export default ServiceAccountCreatePage;