index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import {Fragment} from 'react';
  2. import {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 {Client} from 'sentry/api';
  7. import {Alert} from 'sentry/components/alert';
  8. import {Button} from 'sentry/components/button';
  9. import SelectControl from 'sentry/components/forms/controls/selectControl';
  10. import FieldGroup from 'sentry/components/forms/fieldGroup';
  11. import IdBadge from 'sentry/components/idBadge';
  12. import ExternalLink from 'sentry/components/links/externalLink';
  13. import LoadingIndicator from 'sentry/components/loadingIndicator';
  14. import NarrowLayout from 'sentry/components/narrowLayout';
  15. import {t, tct} from 'sentry/locale';
  16. import ConfigStore from 'sentry/stores/configStore';
  17. import {Integration, IntegrationProvider, Organization} from 'sentry/types';
  18. import {generateBaseControlSiloUrl, generateOrgSlugUrl} from 'sentry/utils';
  19. import {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. // TODO: stop using control silo which is dependent on figuring out how to
  54. // check the Github installation data which is on the control silo
  55. controlSiloApi = new Client({baseUrl: generateBaseControlSiloUrl() + '/api/0'});
  56. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  57. return [['organizations', '/organizations/']];
  58. }
  59. getTitle() {
  60. return t('Choose Installation Organization');
  61. }
  62. trackIntegrationAnalytics = (
  63. eventName: IntegrationAnalyticsKey,
  64. startSession?: boolean
  65. ) => {
  66. const {organization, provider} = this.state;
  67. // should have these set but need to make TS happy
  68. if (!organization || !provider) {
  69. return;
  70. }
  71. trackIntegrationAnalytics(
  72. eventName,
  73. {
  74. integration_type: 'first_party',
  75. integration: provider.key,
  76. // We actually don't know if it's installed but neither does the user in the view and multiple installs is possible
  77. already_installed: false,
  78. view: 'external_install',
  79. organization,
  80. },
  81. {startSession: !!startSession}
  82. );
  83. };
  84. trackOpened() {
  85. this.trackIntegrationAnalytics('integrations.integration_viewed', true);
  86. }
  87. trackInstallationStart() {
  88. this.trackIntegrationAnalytics('integrations.installation_start');
  89. }
  90. get integrationSlug() {
  91. return this.props.params.integrationSlug;
  92. }
  93. get queryParams() {
  94. return this.props.location.query;
  95. }
  96. getOrgBySlug = (orgSlug: string): Organization | undefined => {
  97. return this.state.organizations.find((org: Organization) => org.slug === orgSlug);
  98. };
  99. onLoadAllEndpointsSuccess() {
  100. // auto select the org if there is only one
  101. const {organizations} = this.state;
  102. if (organizations.length === 1) {
  103. this.onSelectOrg(organizations[0].slug);
  104. }
  105. // now check the subomdain and use that org slug if it exists
  106. const customerDomain = ConfigStore.get('customerDomain');
  107. if (customerDomain?.subdomain) {
  108. this.onSelectOrg(customerDomain.subdomain);
  109. }
  110. }
  111. onSelectOrg = async (orgSlug: string) => {
  112. const customerDomain = ConfigStore.get('customerDomain');
  113. // redirect to the org if it's different than the org being selected
  114. if (customerDomain?.subdomain && orgSlug !== customerDomain?.subdomain) {
  115. const urlWithQuery = generateOrgSlugUrl(orgSlug) + this.props.location.search;
  116. window.location.assign(urlWithQuery);
  117. return;
  118. }
  119. // otherwise proceed as normal
  120. this.setState({selectedOrgSlug: orgSlug, reloading: true, organization: undefined});
  121. try {
  122. const [organization, {providers}]: [
  123. Organization,
  124. {providers: IntegrationProvider[]},
  125. ] = await Promise.all([
  126. this.controlSiloApi.requestPromise(`/organizations/${orgSlug}/`),
  127. this.controlSiloApi.requestPromise(
  128. `/organizations/${orgSlug}/config/integrations/?provider_key=${this.integrationSlug}`
  129. ),
  130. ]);
  131. // should never happen with a valid provider
  132. if (providers.length === 0) {
  133. throw new Error('Invalid provider');
  134. }
  135. let installationData = undefined;
  136. if (this.integrationSlug === 'github') {
  137. const {installationId} = this.props.params;
  138. try {
  139. // The API endpoint /extensions/github/installation is not prefixed with /api/0
  140. // so we have to use this workaround.
  141. installationData = await this.controlSiloApi.requestPromise(
  142. `/../../extensions/github/installation/${installationId}/`
  143. );
  144. } catch (_err) {
  145. addErrorMessage(t('Failed to retrieve GitHub installation details'));
  146. }
  147. this.setState({installationDataLoading: false});
  148. }
  149. this.setState(
  150. {organization, reloading: false, provider: providers[0], installationData},
  151. this.trackOpened
  152. );
  153. } catch (_err) {
  154. addErrorMessage(t('Failed to retrieve organization or integration details'));
  155. this.setState({reloading: false});
  156. }
  157. };
  158. hasAccess = () => {
  159. const {organization} = this.state;
  160. return organization?.access.includes('org:integrations');
  161. };
  162. // used with Github to redirect to the the integration detail
  163. onInstallWithInstallationId = (data: Integration) => {
  164. const {organization} = this.state;
  165. const orgId = organization && organization.slug;
  166. const normalizedUrl = normalizeUrl(
  167. `/settings/${orgId}/integrations/${data.provider.key}/${data.id}/`
  168. );
  169. window.location.assign(
  170. `${organization?.links.organizationUrl || ''}${normalizedUrl}`
  171. );
  172. };
  173. // non-Github redirects to the extension view where the backend will finish the installation
  174. finishInstallation = () => {
  175. // add the selected org to the query parameters and then redirect back to configure
  176. const {selectedOrgSlug, organization} = this.state;
  177. const query = {orgSlug: selectedOrgSlug, ...this.queryParams};
  178. this.trackInstallationStart();
  179. // need to send to control silo to finish the installation
  180. window.location.assign(
  181. `${organization?.links.organizationUrl || ''}/extensions/${
  182. this.integrationSlug
  183. }/configure/?${urlEncode(query)}`
  184. );
  185. };
  186. renderAddButton() {
  187. const {installationId} = this.props.params;
  188. const {organization, provider} = this.state;
  189. // should never happen but we need this check for TS
  190. if (!provider || !organization) {
  191. return null;
  192. }
  193. const {features} = provider.metadata;
  194. // Prepare the features list
  195. const featuresComponents = features.map(f => ({
  196. featureGate: f.featureGate,
  197. description: (
  198. <FeatureListItem
  199. dangerouslySetInnerHTML={{__html: singleLineRenderer(f.description)}}
  200. />
  201. ),
  202. }));
  203. const {IntegrationFeatures} = getIntegrationFeatureGate();
  204. // Github uses a different installation flow with the installationId as a parameter
  205. // We have to wrap our installation button with AddIntegration so we can get the
  206. // addIntegrationWithInstallationId callback.
  207. // if we don't have an installationId, we need to use the finishInstallation callback.
  208. return (
  209. <IntegrationFeatures organization={organization} features={featuresComponents}>
  210. {({disabled, disabledReason}) => (
  211. <AddIntegration
  212. provider={provider}
  213. onInstall={this.onInstallWithInstallationId}
  214. organization={organization}
  215. >
  216. {addIntegrationWithInstallationId => (
  217. <ButtonWrapper>
  218. <Button
  219. priority="primary"
  220. disabled={!this.hasAccess() || disabled}
  221. onClick={() =>
  222. installationId
  223. ? addIntegrationWithInstallationId({
  224. installation_id: installationId,
  225. })
  226. : this.finishInstallation()
  227. }
  228. >
  229. {t('Install %s', provider.name)}
  230. </Button>
  231. {disabled && <DisabledNotice reason={disabledReason} />}
  232. </ButtonWrapper>
  233. )}
  234. </AddIntegration>
  235. )}
  236. </IntegrationFeatures>
  237. );
  238. }
  239. renderBottom() {
  240. const {organization, selectedOrgSlug, provider, reloading} = this.state;
  241. const {FeatureList} = getIntegrationFeatureGate();
  242. if (reloading) {
  243. return <LoadingIndicator />;
  244. }
  245. return (
  246. <Fragment>
  247. {selectedOrgSlug && organization && !this.hasAccess() && (
  248. <Alert type="error" showIcon>
  249. <p>
  250. {tct(
  251. `You do not have permission to install integrations in
  252. [organization]. Ask an organization owner or manager to
  253. visit this page to finish installing this integration.`,
  254. {organization: <strong>{organization.slug}</strong>}
  255. )}
  256. </p>
  257. <InstallLink>{generateOrgSlugUrl(selectedOrgSlug)}</InstallLink>
  258. </Alert>
  259. )}
  260. {provider && organization && this.hasAccess() && FeatureList && (
  261. <Fragment>
  262. <p>
  263. {tct(
  264. 'The following features will be available for [organization] when installed.',
  265. {organization: <strong>{organization.slug}</strong>}
  266. )}
  267. </p>
  268. <FeatureList
  269. organization={organization}
  270. features={provider.metadata.features}
  271. provider={provider}
  272. />
  273. </Fragment>
  274. )}
  275. <div className="form-actions">{this.renderAddButton()}</div>
  276. </Fragment>
  277. );
  278. }
  279. renderCallout() {
  280. const {installationData, installationDataLoading} = this.state;
  281. if (this.integrationSlug !== 'github') {
  282. return null;
  283. }
  284. if (!installationData) {
  285. if (installationDataLoading !== false) {
  286. return null;
  287. }
  288. return (
  289. <Alert type="warning" showIcon>
  290. {t(
  291. 'We could not verify the authenticity of the installation request. We recommend restarting the installation process.'
  292. )}
  293. </Alert>
  294. );
  295. }
  296. const sender_url = `https://github.com/${installationData?.sender.login}`;
  297. const target_url = `https://github.com/${installationData?.account.login}`;
  298. const alertText = tct(
  299. `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.`,
  300. {
  301. account_type: <strong>{installationData?.account.type}</strong>,
  302. account_login: (
  303. <strong>
  304. <ExternalLink href={target_url}>
  305. {installationData?.account.login}
  306. </ExternalLink>
  307. </strong>
  308. ),
  309. sender_id: <strong>{installationData?.sender.id}</strong>,
  310. sender_login: (
  311. <strong>
  312. <ExternalLink href={sender_url}>
  313. {installationData?.sender.login}
  314. </ExternalLink>
  315. </strong>
  316. ),
  317. }
  318. );
  319. return (
  320. <Alert type="info" showIcon>
  321. {alertText}
  322. </Alert>
  323. );
  324. }
  325. renderBody() {
  326. const {selectedOrgSlug} = this.state;
  327. const options = this.state.organizations.map((org: Organization) => ({
  328. value: org.slug,
  329. label: (
  330. <IdBadge
  331. organization={org}
  332. avatarSize={20}
  333. displayName={org.name}
  334. avatarProps={{consistentWidth: true}}
  335. />
  336. ),
  337. }));
  338. return (
  339. <NarrowLayout>
  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. `;