authTokenDetails.tsx 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import {useCallback} from 'react';
  2. import {
  3. addErrorMessage,
  4. addLoadingMessage,
  5. addSuccessMessage,
  6. } from 'sentry/actionCreators/indicator';
  7. import FieldGroup from 'sentry/components/forms/fieldGroup';
  8. import TextField from 'sentry/components/forms/fields/textField';
  9. import Form from 'sentry/components/forms/form';
  10. import ExternalLink from 'sentry/components/links/externalLink';
  11. import LoadingError from 'sentry/components/loadingError';
  12. import LoadingIndicator from 'sentry/components/loadingIndicator';
  13. import Panel from 'sentry/components/panels/panel';
  14. import PanelBody from 'sentry/components/panels/panelBody';
  15. import PanelHeader from 'sentry/components/panels/panelHeader';
  16. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  17. import {t, tct} from 'sentry/locale';
  18. import type {Organization, OrgAuthToken} from 'sentry/types';
  19. import {browserHistory} from 'sentry/utils/browserHistory';
  20. import {handleXhrErrorResponse} from 'sentry/utils/handleXhrErrorResponse';
  21. import {
  22. getApiQueryData,
  23. setApiQueryData,
  24. useApiQuery,
  25. useMutation,
  26. useQueryClient,
  27. } from 'sentry/utils/queryClient';
  28. import type RequestError from 'sentry/utils/requestError/requestError';
  29. import useApi from 'sentry/utils/useApi';
  30. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  31. import withOrganization from 'sentry/utils/withOrganization';
  32. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  33. import TextBlock from 'sentry/views/settings/components/text/textBlock';
  34. import {
  35. makeFetchOrgAuthTokensForOrgQueryKey,
  36. tokenPreview,
  37. } from 'sentry/views/settings/organizationAuthTokens';
  38. type Props = {
  39. organization: Organization;
  40. params: {tokenId: string};
  41. };
  42. type FetchOrgAuthTokenParameters = {
  43. orgSlug: string;
  44. tokenId: string;
  45. };
  46. type FetchOrgAuthTokenResponse = OrgAuthToken;
  47. type UpdateTokenQueryVariables = {
  48. name: string;
  49. };
  50. export const makeFetchOrgAuthTokenKey = ({
  51. orgSlug,
  52. tokenId,
  53. }: FetchOrgAuthTokenParameters) =>
  54. [`/organizations/${orgSlug}/org-auth-tokens/${tokenId}/`] as const;
  55. function AuthTokenDetailsForm({
  56. token,
  57. organization,
  58. }: {
  59. organization: Organization;
  60. token: OrgAuthToken;
  61. }) {
  62. const initialData = {
  63. name: token.name,
  64. tokenPreview: tokenPreview(token.tokenLastCharacters || '****'),
  65. };
  66. const api = useApi();
  67. const queryClient = useQueryClient();
  68. const handleGoBack = useCallback(() => {
  69. browserHistory.push(normalizeUrl(`/settings/${organization.slug}/auth-tokens/`));
  70. }, [organization.slug]);
  71. const {mutate: submitToken} = useMutation<{}, RequestError, UpdateTokenQueryVariables>({
  72. mutationFn: ({name}) =>
  73. api.requestPromise(
  74. `/organizations/${organization.slug}/org-auth-tokens/${token.id}/`,
  75. {
  76. method: 'PUT',
  77. data: {
  78. name,
  79. },
  80. }
  81. ),
  82. onSuccess: (_data, {name}) => {
  83. addSuccessMessage(t('Updated auth token.'));
  84. // Update get by id query
  85. setApiQueryData(
  86. queryClient,
  87. makeFetchOrgAuthTokenKey({orgSlug: organization.slug, tokenId: token.id}),
  88. (oldData: OrgAuthToken | undefined) => {
  89. if (!oldData) {
  90. return oldData;
  91. }
  92. oldData.name = name;
  93. return oldData;
  94. }
  95. );
  96. // Update get list query
  97. if (
  98. getApiQueryData(
  99. queryClient,
  100. makeFetchOrgAuthTokensForOrgQueryKey({orgSlug: organization.slug})
  101. )
  102. ) {
  103. setApiQueryData(
  104. queryClient,
  105. makeFetchOrgAuthTokensForOrgQueryKey({orgSlug: organization.slug}),
  106. (oldData: OrgAuthToken[] | undefined) => {
  107. if (!Array.isArray(oldData)) {
  108. return oldData;
  109. }
  110. const existingToken = oldData.find(oldToken => oldToken.id === token.id);
  111. if (existingToken) {
  112. existingToken.name = name;
  113. }
  114. return oldData;
  115. }
  116. );
  117. }
  118. handleGoBack();
  119. },
  120. onError: error => {
  121. const message = t('Failed to update the auth token.');
  122. handleXhrErrorResponse(message, error);
  123. addErrorMessage(message);
  124. },
  125. });
  126. return (
  127. <Form
  128. apiMethod="PUT"
  129. initialData={initialData}
  130. apiEndpoint={`/organizations/${organization.slug}/org-auth-tokens/${token.id}/`}
  131. onSubmit={({name}) => {
  132. addLoadingMessage();
  133. return submitToken({
  134. name,
  135. });
  136. }}
  137. onCancel={handleGoBack}
  138. >
  139. <TextField
  140. name="name"
  141. label={t('Name')}
  142. required
  143. help={t('A name to help you identify this token.')}
  144. />
  145. <TextField
  146. name="tokenPreview"
  147. label={t('Token')}
  148. disabled
  149. help={t('You can only view the token once after creation.')}
  150. />
  151. <FieldGroup
  152. label={t('Scopes')}
  153. help={t('You cannot change the scopes of an existing token.')}
  154. >
  155. <div>{token.scopes.slice().sort().join(', ')}</div>
  156. </FieldGroup>
  157. </Form>
  158. );
  159. }
  160. export function OrganizationAuthTokensDetails({params, organization}: Props) {
  161. const {tokenId} = params;
  162. const {
  163. isLoading,
  164. isError,
  165. data: token,
  166. refetch: refetchToken,
  167. } = useApiQuery<FetchOrgAuthTokenResponse>(
  168. makeFetchOrgAuthTokenKey({orgSlug: organization.slug, tokenId}),
  169. {
  170. staleTime: Infinity,
  171. }
  172. );
  173. return (
  174. <div>
  175. <SentryDocumentTitle title={t('Edit Auth Token')} />
  176. <SettingsPageHeader title={t('Edit Auth Token')} />
  177. <TextBlock>
  178. {t(
  179. "Authentication tokens allow you to perform actions against the Sentry API on behalf of your organization. They're the easiest way to get started using the API."
  180. )}
  181. </TextBlock>
  182. <TextBlock>
  183. {tct(
  184. 'For more information on how to use the web API, see our [link:documentation].',
  185. {
  186. link: <ExternalLink href="https://docs.sentry.io/api/" />,
  187. }
  188. )}
  189. </TextBlock>
  190. <Panel>
  191. <PanelHeader>{t('Auth Token Details')}</PanelHeader>
  192. <PanelBody>
  193. {isError && (
  194. <LoadingError
  195. message={t('Failed to load auth token.')}
  196. onRetry={refetchToken}
  197. />
  198. )}
  199. {isLoading && <LoadingIndicator />}
  200. {!isLoading && !isError && token && (
  201. <AuthTokenDetailsForm token={token} organization={organization} />
  202. )}
  203. </PanelBody>
  204. </Panel>
  205. </div>
  206. );
  207. }
  208. export default withOrganization(OrganizationAuthTokensDetails);