index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import {RouteComponentProps} from 'react-router';
  2. import styled from '@emotion/styled';
  3. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  4. import {installSentryApp} from 'sentry/actionCreators/sentryAppInstallations';
  5. import {Client} from 'sentry/api';
  6. import {Alert} from 'sentry/components/alert';
  7. import OrganizationAvatar from 'sentry/components/avatar/organizationAvatar';
  8. import SelectControl from 'sentry/components/forms/controls/selectControl';
  9. import FieldGroup from 'sentry/components/forms/fieldGroup';
  10. import SentryAppDetailsModal from 'sentry/components/modals/sentryAppDetailsModal';
  11. import NarrowLayout from 'sentry/components/narrowLayout';
  12. import {t, tct} from 'sentry/locale';
  13. import {Organization, SentryApp, SentryAppInstallation} from 'sentry/types';
  14. import {generateBaseControlSiloUrl} from 'sentry/utils';
  15. import {trackIntegrationAnalytics} from 'sentry/utils/integrationUtil';
  16. import {addQueryParamsToExistingUrl} from 'sentry/utils/queryString';
  17. import AsyncView from 'sentry/views/asyncView';
  18. import {OrganizationContext} from '../organizationContext';
  19. type Props = RouteComponentProps<{sentryAppSlug: string}, {}>;
  20. type State = AsyncView['state'] & {
  21. organization: Organization | null;
  22. organizations: Organization[];
  23. reloading: boolean;
  24. selectedOrgSlug: string | null;
  25. sentryApp: SentryApp;
  26. };
  27. export default class SentryAppExternalInstallation extends AsyncView<Props, State> {
  28. disableErrorReport = false;
  29. controlSiloApi = new Client({baseUrl: generateBaseControlSiloUrl() + '/api/0'});
  30. getDefaultState() {
  31. const state = super.getDefaultState();
  32. return {
  33. ...state,
  34. selectedOrgSlug: null,
  35. organization: null,
  36. organizations: [],
  37. reloading: false,
  38. };
  39. }
  40. getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
  41. return [
  42. ['organizations', '/organizations/'],
  43. ['sentryApp', `/sentry-apps/${this.sentryAppSlug}/`],
  44. ];
  45. }
  46. getTitle() {
  47. return t('Choose Installation Organization');
  48. }
  49. get sentryAppSlug() {
  50. return this.props.params.sentryAppSlug;
  51. }
  52. get isSingleOrg() {
  53. return this.state.organizations.length === 1;
  54. }
  55. get isSentryAppInternal() {
  56. const {sentryApp} = this.state;
  57. return sentryApp && sentryApp.status === 'internal';
  58. }
  59. get isSentryAppUnavailableForOrg() {
  60. const {sentryApp, selectedOrgSlug} = this.state;
  61. // if the app is unpublished for a different org
  62. return (
  63. selectedOrgSlug &&
  64. sentryApp?.owner?.slug !== selectedOrgSlug &&
  65. sentryApp.status === 'unpublished'
  66. );
  67. }
  68. get disableInstall() {
  69. const {reloading, isInstalled} = this.state;
  70. return isInstalled || reloading || this.isSentryAppUnavailableForOrg;
  71. }
  72. hasAccess = (org: Organization) => org.access.includes('org:integrations');
  73. onClose = () => {
  74. // if we came from somewhere, go back there. Otherwise, back to the integrations page
  75. const {selectedOrgSlug} = this.state;
  76. const newUrl = document.referrer || `/settings/${selectedOrgSlug}/integrations/`;
  77. window.location.assign(newUrl);
  78. };
  79. onInstall = async (): Promise<any | undefined> => {
  80. const {organization, sentryApp} = this.state;
  81. if (!organization || !sentryApp) {
  82. return undefined;
  83. }
  84. trackIntegrationAnalytics('integrations.installation_start', {
  85. integration_type: 'sentry_app',
  86. integration: sentryApp.slug,
  87. view: 'external_install',
  88. integration_status: sentryApp.status,
  89. organization,
  90. });
  91. const install = await installSentryApp(
  92. this.controlSiloApi,
  93. organization.slug,
  94. sentryApp
  95. );
  96. // installation is complete if the status is installed
  97. if (install.status === 'installed') {
  98. trackIntegrationAnalytics('integrations.installation_complete', {
  99. integration_type: 'sentry_app',
  100. integration: sentryApp.slug,
  101. view: 'external_install',
  102. integration_status: sentryApp.status,
  103. organization,
  104. });
  105. }
  106. if (sentryApp.redirectUrl) {
  107. const queryParams = {
  108. installationId: install.uuid,
  109. code: install.code,
  110. orgSlug: organization.slug,
  111. };
  112. const redirectUrl = addQueryParamsToExistingUrl(sentryApp.redirectUrl, queryParams);
  113. return window.location.assign(redirectUrl);
  114. }
  115. return this.onClose();
  116. };
  117. onSelectOrg = async (orgSlug: string) => {
  118. this.setState({selectedOrgSlug: orgSlug, reloading: true});
  119. try {
  120. const [organization, installations]: [Organization, SentryAppInstallation[]] =
  121. await Promise.all([
  122. this.controlSiloApi.requestPromise(`/organizations/${orgSlug}/`),
  123. this.controlSiloApi.requestPromise(
  124. `/organizations/${orgSlug}/sentry-app-installations/`
  125. ),
  126. ]);
  127. const isInstalled = installations
  128. .map(install => install.app.slug)
  129. .includes(this.sentryAppSlug);
  130. // all state fields should be set at the same time so analytics in SentryAppDetailsModal works properly
  131. this.setState({organization, isInstalled, reloading: false});
  132. } catch (err) {
  133. addErrorMessage(t('Failed to retrieve organization or integration details'));
  134. this.setState({reloading: false});
  135. }
  136. };
  137. onRequestSuccess = ({stateKey, data}) => {
  138. // if only one org, we can immediately update our selected org
  139. if (stateKey === 'organizations' && data.length === 1) {
  140. this.onSelectOrg(data[0].slug);
  141. }
  142. };
  143. getOptions() {
  144. return this.state.organizations.map(org => ({
  145. value: org.slug,
  146. label: (
  147. <div key={org.slug}>
  148. <OrganizationAvatar organization={org} />
  149. <OrgNameHolder>{org.slug}</OrgNameHolder>
  150. </div>
  151. ),
  152. }));
  153. }
  154. renderInternalAppError() {
  155. const {sentryApp} = this.state;
  156. return (
  157. <Alert type="error" showIcon>
  158. {tct(
  159. 'Integration [sentryAppName] is an internal integration. Internal integrations are automatically installed',
  160. {
  161. sentryAppName: <strong>{sentryApp.name}</strong>,
  162. }
  163. )}
  164. </Alert>
  165. );
  166. }
  167. checkAndRenderError() {
  168. const {organization, selectedOrgSlug, isInstalled, sentryApp} = this.state;
  169. if (selectedOrgSlug && organization && !this.hasAccess(organization)) {
  170. return (
  171. <Alert type="error" showIcon>
  172. <p>
  173. {tct(
  174. `You do not have permission to install integrations in
  175. [organization]. Ask an organization owner or manager to
  176. visit this page to finish installing this integration.`,
  177. {organization: <strong>{organization.slug}</strong>}
  178. )}
  179. </p>
  180. <InstallLink>{window.location.href}</InstallLink>
  181. </Alert>
  182. );
  183. }
  184. if (isInstalled && organization) {
  185. return (
  186. <Alert type="error" showIcon>
  187. {tct('Integration [sentryAppName] already installed for [organization]', {
  188. organization: <strong>{organization.name}</strong>,
  189. sentryAppName: <strong>{sentryApp.name}</strong>,
  190. })}
  191. </Alert>
  192. );
  193. }
  194. if (this.isSentryAppUnavailableForOrg) {
  195. // use the slug of the owner if we have it, otherwise use 'another organization'
  196. const ownerSlug = sentryApp?.owner?.slug ?? 'another organization';
  197. return (
  198. <Alert type="error" showIcon>
  199. {tct(
  200. 'Integration [sentryAppName] is an unpublished integration for [otherOrg]. An unpublished integration can only be installed on the organization which created it.',
  201. {
  202. sentryAppName: <strong>{sentryApp.name}</strong>,
  203. otherOrg: <strong>{ownerSlug}</strong>,
  204. }
  205. )}
  206. </Alert>
  207. );
  208. }
  209. return null;
  210. }
  211. renderMultiOrgView() {
  212. const {selectedOrgSlug, sentryApp} = this.state;
  213. return (
  214. <div>
  215. <p>
  216. {tct(
  217. 'Please pick a specific [organization:organization] to install [sentryAppName]',
  218. {
  219. organization: <strong />,
  220. sentryAppName: <strong>{sentryApp.name}</strong>,
  221. }
  222. )}
  223. </p>
  224. <FieldGroup label={t('Organization')} inline={false} stacked required>
  225. {() => (
  226. <SelectControl
  227. onChange={({value}) => this.onSelectOrg(value)}
  228. value={selectedOrgSlug}
  229. placeholder={t('Select an organization')}
  230. options={this.getOptions()}
  231. />
  232. )}
  233. </FieldGroup>
  234. </div>
  235. );
  236. }
  237. renderSingleOrgView() {
  238. const {organizations, sentryApp} = this.state;
  239. // pull the name out of organizations since state.organization won't be loaded initially
  240. const organizationName = organizations[0].name;
  241. return (
  242. <div>
  243. <p>
  244. {tct('You are installing [sentryAppName] for organization [organization]', {
  245. organization: <strong>{organizationName}</strong>,
  246. sentryAppName: <strong>{sentryApp.name}</strong>,
  247. })}
  248. </p>
  249. </div>
  250. );
  251. }
  252. renderMainContent() {
  253. const {organization, sentryApp} = this.state;
  254. return (
  255. <div>
  256. <OrgViewHolder>
  257. {this.isSingleOrg ? this.renderSingleOrgView() : this.renderMultiOrgView()}
  258. </OrgViewHolder>
  259. {this.checkAndRenderError()}
  260. {organization && (
  261. <OrganizationContext.Provider value={organization}>
  262. <SentryAppDetailsModal
  263. sentryApp={sentryApp}
  264. organization={organization}
  265. onInstall={this.onInstall}
  266. closeModal={this.onClose}
  267. isInstalled={this.disableInstall}
  268. />
  269. </OrganizationContext.Provider>
  270. )}
  271. </div>
  272. );
  273. }
  274. renderBody() {
  275. return (
  276. <NarrowLayout>
  277. <Content>
  278. <h3>{t('Finish integration installation')}</h3>
  279. {this.isSentryAppInternal
  280. ? this.renderInternalAppError()
  281. : this.renderMainContent()}
  282. </Content>
  283. </NarrowLayout>
  284. );
  285. }
  286. }
  287. const InstallLink = styled('pre')`
  288. margin-bottom: 0;
  289. background: #fbe3e1;
  290. `;
  291. const OrgNameHolder = styled('span')`
  292. margin-left: 5px;
  293. `;
  294. const Content = styled('div')`
  295. margin-bottom: 40px;
  296. `;
  297. const OrgViewHolder = styled('div')`
  298. margin-bottom: 20px;
  299. `;