index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. window.location.assign(generateOrgSlugUrl(orgSlug));
  116. return;
  117. }
  118. // otherwise proceed as normal
  119. this.setState({selectedOrgSlug: orgSlug, reloading: true, organization: undefined});
  120. try {
  121. const [organization, {providers}]: [
  122. Organization,
  123. {providers: IntegrationProvider[]},
  124. ] = await Promise.all([
  125. this.controlSiloApi.requestPromise(`/organizations/${orgSlug}/`),
  126. this.controlSiloApi.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.controlSiloApi.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 the integration detail
  162. onInstallWithInstallationId = (data: Integration) => {
  163. const {organization} = this.state;
  164. const orgId = organization && 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. <h3>{t('Finish integration installation')}</h3>
  340. {this.renderCallout()}
  341. <p>
  342. {tct(
  343. `Please pick a specific [organization:organization] to link with
  344. your integration installation of [integation].`,
  345. {
  346. organization: <strong />,
  347. integation: <strong>{this.integrationSlug}</strong>,
  348. }
  349. )}
  350. </p>
  351. <FieldGroup label={t('Organization')} inline={false} stacked required>
  352. <SelectControl
  353. onChange={({value: orgSlug}) => this.onSelectOrg(orgSlug)}
  354. value={selectedOrgSlug}
  355. placeholder={t('Select an organization')}
  356. options={options}
  357. />
  358. </FieldGroup>
  359. {this.renderBottom()}
  360. </NarrowLayout>
  361. );
  362. }
  363. }
  364. const InstallLink = styled('pre')`
  365. margin-bottom: 0;
  366. background: #fbe3e1;
  367. `;
  368. const FeatureListItem = styled('span')`
  369. line-height: 24px;
  370. `;
  371. const ButtonWrapper = styled('div')`
  372. margin-left: auto;
  373. align-self: center;
  374. display: flex;
  375. flex-direction: column;
  376. align-items: center;
  377. `;