index.tsx 13 KB

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