1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-04-19 01:17:18 +02:00
unleash.unleash/frontend/src/component/admin/api-token/hooks/useApiTokenForm.ts
olav 2ca88b019a refactor: restrict API tokens to enabled environments (#809)
* refactor: add missing Tooltip wrapper elements

* refactor: rewrite useEnvironments

* refactor: disable environments in select box

* refactor: make sure initial environment is enabled
2022-03-23 12:55:00 +01:00

67 lines
1.7 KiB
TypeScript

import { useEffect, useState } from 'react';
import { useEnvironments } from 'hooks/api/getters/useEnvironments/useEnvironments';
export const useApiTokenForm = () => {
const { environments } = useEnvironments();
const initialEnvironment = environments?.find(e => e.enabled)?.name;
const [username, setUsername] = useState('');
const [type, setType] = useState('CLIENT');
const [project, setProject] = useState('*');
const [environment, setEnvironment] = useState<string>();
const [errors, setErrors] = useState({});
useEffect(() => {
setEnvironment(type === 'ADMIN' ? '*' : initialEnvironment);
}, [type, initialEnvironment]);
const setTokenType = (value: string) => {
if (value === 'ADMIN') {
setType(value);
setProject('*');
setEnvironment('*');
} else {
setType(value);
setEnvironment(initialEnvironment);
}
};
const getApiTokenPayload = () => {
return {
username: username,
type: type,
project: project,
environment: environment,
};
};
const isValid = () => {
if (!username) {
setErrors({ username: 'Username is required.' });
return false;
} else {
setErrors({});
return true;
}
};
const clearErrors = () => {
setErrors({});
};
return {
username,
type,
project,
environment,
setUsername,
setTokenType,
setProject,
setEnvironment,
getApiTokenPayload,
isValid,
clearErrors,
errors,
};
};