index.tsx 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  4. import Access from 'sentry/components/acl/access';
  5. import {Button} from 'sentry/components/button';
  6. import ExternalLink from 'sentry/components/links/externalLink';
  7. import LoadingError from 'sentry/components/loadingError';
  8. import {PanelTable} from 'sentry/components/panels';
  9. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  10. import {t, tct} from 'sentry/locale';
  11. import {Organization, OrgAuthToken, Project} from 'sentry/types';
  12. import {handleXhrErrorResponse} from 'sentry/utils/handleXhrErrorResponse';
  13. import {
  14. setApiQueryData,
  15. useApiQuery,
  16. useMutation,
  17. useQueryClient,
  18. } from 'sentry/utils/queryClient';
  19. import RequestError from 'sentry/utils/requestError/requestError';
  20. import useApi from 'sentry/utils/useApi';
  21. import withOrganization from 'sentry/utils/withOrganization';
  22. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  23. import TextBlock from 'sentry/views/settings/components/text/textBlock';
  24. import {OrganizationAuthTokensAuthTokenRow} from 'sentry/views/settings/organizationAuthTokens/authTokenRow';
  25. type FetchOrgAuthTokensResponse = OrgAuthToken[];
  26. type FetchOrgAuthTokensParameters = {
  27. orgSlug: string;
  28. };
  29. type RevokeTokenQueryVariables = {
  30. token: OrgAuthToken;
  31. };
  32. export const makeFetchOrgAuthTokensForOrgQueryKey = ({
  33. orgSlug,
  34. }: FetchOrgAuthTokensParameters) =>
  35. [`/organizations/${orgSlug}/org-auth-tokens/`] as const;
  36. function TokenList({
  37. organization,
  38. tokenList,
  39. isRevoking,
  40. revokeToken,
  41. }: {
  42. isRevoking: boolean;
  43. organization: Organization;
  44. tokenList: OrgAuthToken[];
  45. revokeToken?: (data: {token: OrgAuthToken}) => void;
  46. }) {
  47. const apiEndpoint = `/organizations/${organization.slug}/projects/`;
  48. const projectIds = tokenList
  49. .map(token => token.projectLastUsedId)
  50. .filter(id => !!id) as string[];
  51. const idQueryParams = projectIds.map(id => `id:${id}`).join(' ');
  52. const {data: projects} = useApiQuery<Project[]>(
  53. [apiEndpoint, {query: {query: idQueryParams}}],
  54. {
  55. staleTime: 0,
  56. enabled: projectIds.length > 0,
  57. }
  58. );
  59. return (
  60. <Fragment>
  61. {tokenList.map(token => {
  62. const projectLastUsed = token.projectLastUsedId
  63. ? projects?.find(p => p.id === token.projectLastUsedId)
  64. : undefined;
  65. return (
  66. <OrganizationAuthTokensAuthTokenRow
  67. key={token.id}
  68. organization={organization}
  69. token={token}
  70. isRevoking={isRevoking}
  71. revokeToken={revokeToken ? () => revokeToken({token}) : undefined}
  72. projectLastUsed={projectLastUsed}
  73. />
  74. );
  75. })}
  76. </Fragment>
  77. );
  78. }
  79. export function OrganizationAuthTokensIndex({
  80. organization,
  81. }: {
  82. organization: Organization;
  83. }) {
  84. const api = useApi();
  85. const queryClient = useQueryClient();
  86. const {
  87. isLoading,
  88. isError,
  89. data: tokenList,
  90. refetch: refetchTokenList,
  91. } = useApiQuery<FetchOrgAuthTokensResponse>(
  92. makeFetchOrgAuthTokensForOrgQueryKey({orgSlug: organization.slug}),
  93. {
  94. staleTime: Infinity,
  95. }
  96. );
  97. const {mutate: handleRevokeToken, isLoading: isRevoking} = useMutation<
  98. {},
  99. RequestError,
  100. RevokeTokenQueryVariables
  101. >({
  102. mutationFn: ({token}) =>
  103. api.requestPromise(
  104. `/organizations/${organization.slug}/org-auth-tokens/${token.id}/`,
  105. {
  106. method: 'DELETE',
  107. }
  108. ),
  109. onSuccess: (_data, {token}) => {
  110. addSuccessMessage(t('Revoked auth token for the organization.'));
  111. setApiQueryData(
  112. queryClient,
  113. makeFetchOrgAuthTokensForOrgQueryKey({orgSlug: organization.slug}),
  114. oldData => {
  115. if (!Array.isArray(oldData)) {
  116. return oldData;
  117. }
  118. return oldData.filter(oldToken => oldToken.id !== token.id);
  119. }
  120. );
  121. },
  122. onError: error => {
  123. const message = t('Failed to revoke the auth token for the organization.');
  124. handleXhrErrorResponse(message, error);
  125. addErrorMessage(message);
  126. },
  127. });
  128. const createNewToken = (
  129. <Button
  130. priority="primary"
  131. size="sm"
  132. to={`/settings/${organization.slug}/auth-tokens/new-token/`}
  133. data-test-id="create-token"
  134. >
  135. {t('Create New Token')}
  136. </Button>
  137. );
  138. return (
  139. <Access access={['org:write']}>
  140. {({hasAccess}) => (
  141. <Fragment>
  142. <SentryDocumentTitle title={t('Auth Tokens')} />
  143. <SettingsPageHeader title={t('Auth Tokens')} action={createNewToken} />
  144. <TextBlock>
  145. {t(
  146. "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."
  147. )}
  148. </TextBlock>
  149. <TextBlock>
  150. {tct(
  151. 'For more information on how to use the web API, see our [link:documentation].',
  152. {
  153. link: <ExternalLink href="https://docs.sentry.io/api/" />,
  154. }
  155. )}
  156. </TextBlock>
  157. <ResponsivePanelTable
  158. isLoading={isLoading || isError}
  159. isEmpty={!isLoading && !tokenList?.length}
  160. loader={
  161. isError ? (
  162. <LoadingError
  163. message={t('Failed to load auth tokens for the organization.')}
  164. onRetry={refetchTokenList}
  165. />
  166. ) : undefined
  167. }
  168. emptyMessage={t("You haven't created any authentication tokens yet.")}
  169. headers={[t('Auth token'), t('Last access'), '']}
  170. >
  171. {!isError && !isLoading && !!tokenList?.length && (
  172. <TokenList
  173. organization={organization}
  174. tokenList={tokenList}
  175. isRevoking={isRevoking}
  176. revokeToken={hasAccess ? handleRevokeToken : undefined}
  177. />
  178. )}
  179. </ResponsivePanelTable>
  180. </Fragment>
  181. )}
  182. </Access>
  183. );
  184. }
  185. export function tokenPreview(tokenLastCharacters: string) {
  186. return `sntrys_************${tokenLastCharacters}`;
  187. }
  188. export default withOrganization(OrganizationAuthTokensIndex);
  189. const ResponsivePanelTable = styled(PanelTable)`
  190. @media (max-width: ${p => p.theme.breakpoints.small}) {
  191. grid-template-columns: 1fr 1fr;
  192. > *:nth-child(3n + 2) {
  193. display: none;
  194. }
  195. }
  196. `;