index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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/url/normalizeUrl';
  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/?include_feature_flags=1']];
  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. query: {
  125. include_feature_flags: 1,
  126. },
  127. }),
  128. this.api.requestPromise(
  129. `/organizations/${orgSlug}/config/integrations/?provider_key=${this.integrationSlug}`
  130. ),
  131. ]);
  132. // should never happen with a valid provider
  133. if (providers.length === 0) {
  134. throw new Error('Invalid provider');
  135. }
  136. let installationData = undefined;
  137. if (this.integrationSlug === 'github') {
  138. const {installationId} = this.props.params;
  139. try {
  140. // The API endpoint /extensions/github/installation is not prefixed with /api/0
  141. // so we have to use this workaround.
  142. installationData = await this.api.requestPromise(
  143. `/../../extensions/github/installation/${installationId}/`
  144. );
  145. } catch (_err) {
  146. addErrorMessage(t('Failed to retrieve GitHub installation details'));
  147. }
  148. this.setState({installationDataLoading: false});
  149. }
  150. this.setState(
  151. {organization, reloading: false, provider: providers[0], installationData},
  152. this.trackOpened
  153. );
  154. } catch (_err) {
  155. addErrorMessage(t('Failed to retrieve organization or integration details'));
  156. this.setState({reloading: false});
  157. }
  158. };
  159. hasAccess = () => {
  160. const {organization} = this.state;
  161. return organization?.access.includes('org:integrations');
  162. };
  163. // used with Github to redirect to the integration detail
  164. onInstallWithInstallationId = (data: Integration) => {
  165. const {organization} = this.state;
  166. const orgId = organization?.slug;
  167. const normalizedUrl = normalizeUrl(
  168. `/settings/${orgId}/integrations/${data.provider.key}/${data.id}/`
  169. );
  170. window.location.assign(
  171. `${organization?.links.organizationUrl || ''}${normalizedUrl}`
  172. );
  173. };
  174. // non-Github redirects to the extension view where the backend will finish the installation
  175. finishInstallation = () => {
  176. // add the selected org to the query parameters and then redirect back to configure
  177. const {selectedOrgSlug, organization} = this.state;
  178. const query = {orgSlug: selectedOrgSlug, ...this.queryParams};
  179. this.trackInstallationStart();
  180. // need to send to control silo to finish the installation
  181. window.location.assign(
  182. `${organization?.links.organizationUrl || ''}/extensions/${
  183. this.integrationSlug
  184. }/configure/?${urlEncode(query)}`
  185. );
  186. };
  187. renderAddButton() {
  188. const {installationId} = this.props.params;
  189. const {organization, provider} = this.state;
  190. // should never happen but we need this check for TS
  191. if (!provider || !organization) {
  192. return null;
  193. }
  194. const {features} = provider.metadata;
  195. // Prepare the features list
  196. const featuresComponents = features.map(f => ({
  197. featureGate: f.featureGate,
  198. description: (
  199. <FeatureListItem
  200. dangerouslySetInnerHTML={{__html: singleLineRenderer(f.description)}}
  201. />
  202. ),
  203. }));
  204. const {IntegrationFeatures} = getIntegrationFeatureGate();
  205. // Github uses a different installation flow with the installationId as a parameter
  206. // We have to wrap our installation button with AddIntegration so we can get the
  207. // addIntegrationWithInstallationId callback.
  208. // if we don't have an installationId, we need to use the finishInstallation callback.
  209. return (
  210. <IntegrationFeatures organization={organization} features={featuresComponents}>
  211. {({disabled, disabledReason}) => (
  212. <AddIntegration
  213. provider={provider}
  214. onInstall={this.onInstallWithInstallationId}
  215. organization={organization}
  216. >
  217. {addIntegrationWithInstallationId => (
  218. <ButtonWrapper>
  219. <Button
  220. priority="primary"
  221. disabled={!this.hasAccess() || disabled}
  222. onClick={() =>
  223. installationId
  224. ? addIntegrationWithInstallationId({
  225. installation_id: installationId,
  226. })
  227. : this.finishInstallation()
  228. }
  229. >
  230. {t('Install %s', provider.name)}
  231. </Button>
  232. {disabled && <DisabledNotice reason={disabledReason} />}
  233. </ButtonWrapper>
  234. )}
  235. </AddIntegration>
  236. )}
  237. </IntegrationFeatures>
  238. );
  239. }
  240. renderBottom() {
  241. const {organization, selectedOrgSlug, provider, reloading} = this.state;
  242. const {FeatureList} = getIntegrationFeatureGate();
  243. if (reloading) {
  244. return <LoadingIndicator />;
  245. }
  246. return (
  247. <Fragment>
  248. {selectedOrgSlug && organization && !this.hasAccess() && (
  249. <Alert type="error" showIcon>
  250. <p>
  251. {tct(
  252. `You do not have permission to install integrations in
  253. [organization]. Ask an organization owner or manager to
  254. visit this page to finish installing this integration.`,
  255. {organization: <strong>{organization.slug}</strong>}
  256. )}
  257. </p>
  258. <InstallLink>{generateOrgSlugUrl(selectedOrgSlug)}</InstallLink>
  259. </Alert>
  260. )}
  261. {provider && organization && this.hasAccess() && FeatureList && (
  262. <Fragment>
  263. <p>
  264. {tct(
  265. 'The following features will be available for [organization] when installed.',
  266. {organization: <strong>{organization.slug}</strong>}
  267. )}
  268. </p>
  269. <FeatureList
  270. organization={organization}
  271. features={provider.metadata.features}
  272. provider={provider}
  273. />
  274. </Fragment>
  275. )}
  276. <div className="form-actions">{this.renderAddButton()}</div>
  277. </Fragment>
  278. );
  279. }
  280. renderCallout() {
  281. const {installationData, installationDataLoading} = this.state;
  282. if (this.integrationSlug !== 'github') {
  283. return null;
  284. }
  285. if (!installationData) {
  286. if (installationDataLoading !== false) {
  287. return null;
  288. }
  289. return (
  290. <Alert type="warning" showIcon>
  291. {t(
  292. 'We could not verify the authenticity of the installation request. We recommend restarting the installation process.'
  293. )}
  294. </Alert>
  295. );
  296. }
  297. const sender_url = `https://github.com/${installationData?.sender.login}`;
  298. const target_url = `https://github.com/${installationData?.account.login}`;
  299. const alertText = tct(
  300. `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.`,
  301. {
  302. account_type: <strong>{installationData?.account.type}</strong>,
  303. account_login: (
  304. <strong>
  305. <ExternalLink href={target_url}>
  306. {installationData?.account.login}
  307. </ExternalLink>
  308. </strong>
  309. ),
  310. sender_id: <strong>{installationData?.sender.id}</strong>,
  311. sender_login: (
  312. <strong>
  313. <ExternalLink href={sender_url}>
  314. {installationData?.sender.login}
  315. </ExternalLink>
  316. </strong>
  317. ),
  318. }
  319. );
  320. return (
  321. <Alert type="info" showIcon>
  322. {alertText}
  323. </Alert>
  324. );
  325. }
  326. renderBody() {
  327. const {selectedOrgSlug} = this.state;
  328. const options = this.state.organizations.map((org: Organization) => ({
  329. value: org.slug,
  330. label: (
  331. <IdBadge
  332. organization={org}
  333. avatarSize={20}
  334. displayName={org.name}
  335. avatarProps={{consistentWidth: true}}
  336. />
  337. ),
  338. }));
  339. return (
  340. <NarrowLayout>
  341. <h3>{t('Finish integration installation')}</h3>
  342. {this.renderCallout()}
  343. <p>
  344. {tct(
  345. `Please pick a specific [organization:organization] to link with
  346. your integration installation of [integation].`,
  347. {
  348. organization: <strong />,
  349. integation: <strong>{this.integrationSlug}</strong>,
  350. }
  351. )}
  352. </p>
  353. <FieldGroup label={t('Organization')} inline={false} stacked required>
  354. <SelectControl
  355. onChange={({value: orgSlug}) => this.onSelectOrg(orgSlug)}
  356. value={selectedOrgSlug}
  357. placeholder={t('Select an organization')}
  358. options={options}
  359. />
  360. </FieldGroup>
  361. {this.renderBottom()}
  362. </NarrowLayout>
  363. );
  364. }
  365. }
  366. const InstallLink = styled('pre')`
  367. margin-bottom: 0;
  368. background: #fbe3e1;
  369. `;
  370. const FeatureListItem = styled('span')`
  371. line-height: 24px;
  372. `;
  373. const ButtonWrapper = styled('div')`
  374. margin-left: auto;
  375. align-self: center;
  376. display: flex;
  377. flex-direction: column;
  378. align-items: center;
  379. `;