index.tsx 13 KB

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