index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import {urlEncode} from '@sentry/utils';
  4. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  5. import {Alert} from 'sentry/components/alert';
  6. import {Button} from 'sentry/components/button';
  7. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  8. import SelectControl from 'sentry/components/forms/controls/selectControl';
  9. import FieldGroup from 'sentry/components/forms/fieldGroup';
  10. import IdBadge from 'sentry/components/idBadge';
  11. import ExternalLink from 'sentry/components/links/externalLink';
  12. import LoadingIndicator from 'sentry/components/loadingIndicator';
  13. import NarrowLayout from 'sentry/components/narrowLayout';
  14. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  15. import {t, tct} from 'sentry/locale';
  16. import ConfigStore from 'sentry/stores/configStore';
  17. import type {Integration, IntegrationProvider} from 'sentry/types/integrations';
  18. import type {RouteComponentProps} from 'sentry/types/legacyReactRouter';
  19. import type {Organization} from 'sentry/types/organization';
  20. import {generateOrgSlugUrl} from 'sentry/utils';
  21. import type {IntegrationAnalyticsKey} from 'sentry/utils/analytics/integrations';
  22. import {
  23. getIntegrationFeatureGate,
  24. trackIntegrationAnalytics,
  25. } from 'sentry/utils/integrationUtil';
  26. import {singleLineRenderer} from 'sentry/utils/marked';
  27. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  28. import {DisabledNotice} from 'sentry/views/settings/organizationIntegrations/abstractIntegrationDetailedView';
  29. import AddIntegration from 'sentry/views/settings/organizationIntegrations/addIntegration';
  30. // installationId present for Github flow
  31. type Props = RouteComponentProps<{integrationSlug: string; installationId?: string}, {}>;
  32. type State = DeprecatedAsyncComponent['state'] & {
  33. installationData?: GitHubIntegrationInstallation;
  34. installationDataLoading?: boolean;
  35. organization?: Organization;
  36. provider?: IntegrationProvider;
  37. selectedOrgSlug?: string;
  38. };
  39. interface GitHubIntegrationInstallation {
  40. account: {
  41. login: string;
  42. type: string;
  43. };
  44. sender: {
  45. id: number;
  46. login: string;
  47. };
  48. }
  49. export default class IntegrationOrganizationLink extends DeprecatedAsyncComponent<
  50. Props,
  51. State
  52. > {
  53. disableErrorReport = false;
  54. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  55. return [['organizations', '/organizations/?include_feature_flags=1']];
  56. }
  57. trackIntegrationAnalytics = (
  58. eventName: IntegrationAnalyticsKey,
  59. startSession?: boolean
  60. ) => {
  61. const {organization, provider} = this.state;
  62. // should have these set but need to make TS happy
  63. if (!organization || !provider) {
  64. return;
  65. }
  66. trackIntegrationAnalytics(
  67. eventName,
  68. {
  69. integration_type: 'first_party',
  70. integration: provider.key,
  71. // We actually don't know if it's installed but neither does the user in the view and multiple installs is possible
  72. already_installed: false,
  73. view: 'external_install',
  74. organization,
  75. },
  76. {startSession: !!startSession}
  77. );
  78. };
  79. trackOpened() {
  80. this.trackIntegrationAnalytics('integrations.integration_viewed', true);
  81. }
  82. trackInstallationStart() {
  83. this.trackIntegrationAnalytics('integrations.installation_start');
  84. }
  85. get integrationSlug() {
  86. return this.props.params.integrationSlug;
  87. }
  88. get queryParams() {
  89. return this.props.location.query;
  90. }
  91. getOrgBySlug = (orgSlug: string): Organization | undefined => {
  92. return this.state.organizations.find((org: Organization) => org.slug === orgSlug);
  93. };
  94. onLoadAllEndpointsSuccess() {
  95. // auto select the org if there is only one
  96. const {organizations} = this.state;
  97. if (organizations.length === 1) {
  98. this.onSelectOrg(organizations[0].slug);
  99. }
  100. // now check the subomdain and use that org slug if it exists
  101. const customerDomain = ConfigStore.get('customerDomain');
  102. if (customerDomain?.subdomain) {
  103. this.onSelectOrg(customerDomain.subdomain);
  104. }
  105. }
  106. onSelectOrg = async (orgSlug: string) => {
  107. const customerDomain = ConfigStore.get('customerDomain');
  108. // redirect to the org if it's different than the org being selected
  109. if (customerDomain?.subdomain && orgSlug !== customerDomain?.subdomain) {
  110. const urlWithQuery = generateOrgSlugUrl(orgSlug) + this.props.location.search;
  111. window.location.assign(urlWithQuery);
  112. return;
  113. }
  114. // otherwise proceed as normal
  115. this.setState({selectedOrgSlug: orgSlug, reloading: true, organization: undefined});
  116. try {
  117. const [organization, {providers}]: [
  118. Organization,
  119. {providers: IntegrationProvider[]},
  120. ] = await Promise.all([
  121. this.api.requestPromise(`/organizations/${orgSlug}/`, {
  122. query: {
  123. include_feature_flags: 1,
  124. },
  125. }),
  126. this.api.requestPromise(
  127. `/organizations/${orgSlug}/config/integrations/?provider_key=${this.integrationSlug}`
  128. ),
  129. ]);
  130. // should never happen with a valid provider
  131. if (providers.length === 0) {
  132. throw new Error('Invalid provider');
  133. }
  134. let installationData = undefined;
  135. if (this.integrationSlug === 'github') {
  136. const {installationId} = this.props.params;
  137. try {
  138. // The API endpoint /extensions/github/installation is not prefixed with /api/0
  139. // so we have to use this workaround.
  140. installationData = await this.api.requestPromise(
  141. `/../../extensions/github/installation/${installationId}/`
  142. );
  143. } catch (_err) {
  144. addErrorMessage(t('Failed to retrieve GitHub installation details'));
  145. }
  146. this.setState({installationDataLoading: false});
  147. }
  148. this.setState(
  149. {organization, reloading: false, provider: providers[0], installationData},
  150. this.trackOpened
  151. );
  152. } catch (_err) {
  153. addErrorMessage(t('Failed to retrieve organization or integration details'));
  154. this.setState({reloading: false});
  155. }
  156. };
  157. hasAccess = () => {
  158. const {organization} = this.state;
  159. return organization?.access.includes('org:integrations');
  160. };
  161. // used with Github to redirect to the integration detail
  162. onInstallWithInstallationId = (data: Integration) => {
  163. const {organization} = this.state;
  164. const orgId = organization?.slug;
  165. const normalizedUrl = normalizeUrl(
  166. `/settings/${orgId}/integrations/${data.provider.key}/${data.id}/`
  167. );
  168. window.location.assign(
  169. `${organization?.links.organizationUrl || ''}${normalizedUrl}`
  170. );
  171. };
  172. // non-Github redirects to the extension view where the backend will finish the installation
  173. finishInstallation = () => {
  174. // add the selected org to the query parameters and then redirect back to configure
  175. const {selectedOrgSlug, organization} = this.state;
  176. const query = {orgSlug: selectedOrgSlug, ...this.queryParams};
  177. this.trackInstallationStart();
  178. // need to send to control silo to finish the installation
  179. window.location.assign(
  180. `${organization?.links.organizationUrl || ''}/extensions/${
  181. this.integrationSlug
  182. }/configure/?${urlEncode(query)}`
  183. );
  184. };
  185. renderAddButton() {
  186. const {installationId} = this.props.params;
  187. const {organization, provider} = this.state;
  188. // should never happen but we need this check for TS
  189. if (!provider || !organization) {
  190. return null;
  191. }
  192. const {features} = provider.metadata;
  193. // Prepare the features list
  194. const featuresComponents = features.map(f => ({
  195. featureGate: f.featureGate,
  196. description: (
  197. <FeatureListItem
  198. dangerouslySetInnerHTML={{__html: singleLineRenderer(f.description)}}
  199. />
  200. ),
  201. }));
  202. const {IntegrationFeatures} = getIntegrationFeatureGate();
  203. // Github uses a different installation flow with the installationId as a parameter
  204. // We have to wrap our installation button with AddIntegration so we can get the
  205. // addIntegrationWithInstallationId callback.
  206. // if we don't have an installationId, we need to use the finishInstallation callback.
  207. return (
  208. <IntegrationFeatures organization={organization} features={featuresComponents}>
  209. {({disabled, disabledReason}) => (
  210. <AddIntegration
  211. provider={provider}
  212. onInstall={this.onInstallWithInstallationId}
  213. organization={organization}
  214. >
  215. {addIntegrationWithInstallationId => (
  216. <ButtonWrapper>
  217. <Button
  218. priority="primary"
  219. disabled={!this.hasAccess() || disabled}
  220. onClick={() =>
  221. installationId
  222. ? addIntegrationWithInstallationId({
  223. installation_id: installationId,
  224. })
  225. : this.finishInstallation()
  226. }
  227. >
  228. {t('Install %s', provider.name)}
  229. </Button>
  230. {disabled && <DisabledNotice reason={disabledReason} />}
  231. </ButtonWrapper>
  232. )}
  233. </AddIntegration>
  234. )}
  235. </IntegrationFeatures>
  236. );
  237. }
  238. renderBottom() {
  239. const {organization, selectedOrgSlug, provider, reloading} = this.state;
  240. const {FeatureList} = getIntegrationFeatureGate();
  241. if (reloading) {
  242. return <LoadingIndicator />;
  243. }
  244. return (
  245. <Fragment>
  246. {selectedOrgSlug && organization && !this.hasAccess() && (
  247. <Alert type="error" showIcon>
  248. <p>
  249. {tct(
  250. `You do not have permission to install integrations in
  251. [organization]. Ask an organization owner or manager to
  252. visit this page to finish installing this integration.`,
  253. {organization: <strong>{organization.slug}</strong>}
  254. )}
  255. </p>
  256. <InstallLink>{generateOrgSlugUrl(selectedOrgSlug)}</InstallLink>
  257. </Alert>
  258. )}
  259. {provider && organization && this.hasAccess() && FeatureList && (
  260. <Fragment>
  261. <p>
  262. {tct(
  263. 'The following features will be available for [organization] when installed.',
  264. {organization: <strong>{organization.slug}</strong>}
  265. )}
  266. </p>
  267. <FeatureList
  268. organization={organization}
  269. features={provider.metadata.features}
  270. provider={provider}
  271. />
  272. </Fragment>
  273. )}
  274. <div className="form-actions">{this.renderAddButton()}</div>
  275. </Fragment>
  276. );
  277. }
  278. renderCallout() {
  279. const {installationData, installationDataLoading} = this.state;
  280. if (this.integrationSlug !== 'github') {
  281. return null;
  282. }
  283. if (!installationData) {
  284. if (installationDataLoading !== false) {
  285. return null;
  286. }
  287. return (
  288. <Alert type="warning" showIcon>
  289. {t(
  290. 'We could not verify the authenticity of the installation request. We recommend restarting the installation process.'
  291. )}
  292. </Alert>
  293. );
  294. }
  295. const sender_url = `https://github.com/${installationData?.sender.login}`;
  296. const target_url = `https://github.com/${installationData?.account.login}`;
  297. const alertText = tct(
  298. `GitHub user [sender_login] has installed GitHub app to [account_type] [account_login]. Proceed if you want to attach this installation to your Sentry account.`,
  299. {
  300. account_type: <strong>{installationData?.account.type}</strong>,
  301. account_login: (
  302. <strong>
  303. <ExternalLink href={target_url}>
  304. {installationData?.account.login}
  305. </ExternalLink>
  306. </strong>
  307. ),
  308. sender_id: <strong>{installationData?.sender.id}</strong>,
  309. sender_login: (
  310. <strong>
  311. <ExternalLink href={sender_url}>
  312. {installationData?.sender.login}
  313. </ExternalLink>
  314. </strong>
  315. ),
  316. }
  317. );
  318. return (
  319. <Alert type="info" showIcon>
  320. {alertText}
  321. </Alert>
  322. );
  323. }
  324. renderBody() {
  325. const {selectedOrgSlug} = this.state;
  326. const options = this.state.organizations.map((org: Organization) => ({
  327. value: org.slug,
  328. label: (
  329. <IdBadge
  330. organization={org}
  331. avatarSize={20}
  332. displayName={org.name}
  333. avatarProps={{consistentWidth: true}}
  334. />
  335. ),
  336. }));
  337. return (
  338. <NarrowLayout>
  339. <SentryDocumentTitle title={t('Choose Installation Organization')} />
  340. <h3>{t('Finish integration installation')}</h3>
  341. {this.renderCallout()}
  342. <p>
  343. {tct(
  344. `Please pick a specific [organization:organization] to link with
  345. your integration installation of [integation].`,
  346. {
  347. organization: <strong />,
  348. integation: <strong>{this.integrationSlug}</strong>,
  349. }
  350. )}
  351. </p>
  352. <FieldGroup label={t('Organization')} inline={false} stacked required>
  353. <SelectControl
  354. onChange={({value: orgSlug}) => this.onSelectOrg(orgSlug)}
  355. value={selectedOrgSlug}
  356. placeholder={t('Select an organization')}
  357. options={options}
  358. />
  359. </FieldGroup>
  360. {this.renderBottom()}
  361. </NarrowLayout>
  362. );
  363. }
  364. }
  365. const InstallLink = styled('pre')`
  366. margin-bottom: 0;
  367. background: #fbe3e1;
  368. `;
  369. const FeatureListItem = styled('span')`
  370. line-height: 24px;
  371. `;
  372. const ButtonWrapper = styled('div')`
  373. margin-left: auto;
  374. align-self: center;
  375. display: flex;
  376. flex-direction: column;
  377. align-items: center;
  378. `;