authTokenDetails.tsx 6.3 KB

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