organizationContext.tsx 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import {createContext, useCallback, useContext, useEffect, useRef} from 'react';
  2. import {fetchOrganizationDetails} from 'sentry/actionCreators/organization';
  3. import {switchOrganization} from 'sentry/actionCreators/organizations';
  4. import {openSudo} from 'sentry/actionCreators/sudoModal';
  5. import {DEPLOY_PREVIEW_CONFIG} from 'sentry/constants';
  6. import ConfigStore from 'sentry/stores/configStore';
  7. import OrganizationsStore from 'sentry/stores/organizationsStore';
  8. import OrganizationStore from 'sentry/stores/organizationStore';
  9. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  10. import type {Organization, User} from 'sentry/types';
  11. import {metric} from 'sentry/utils/analytics';
  12. import getRouteStringFromRoutes from 'sentry/utils/getRouteStringFromRoutes';
  13. import useApi from 'sentry/utils/useApi';
  14. import {useParams} from 'sentry/utils/useParams';
  15. import {useRoutes} from 'sentry/utils/useRoutes';
  16. /**
  17. * Holds the current organization if loaded.
  18. */
  19. export const OrganizationContext = createContext<Organization | null>(null);
  20. /**
  21. * Holds a function to load the organization.
  22. */
  23. const OrganizationLoaderContext = createContext<null | (() => void)>(null);
  24. interface Props {
  25. children: React.ReactNode;
  26. }
  27. /**
  28. * Ensures that an organization is loaded when the hook is used. This will only
  29. * be done on first render and if an organization is not already loaded.
  30. */
  31. export function useEnsureOrganization() {
  32. const loadOrganization = useContext(OrganizationLoaderContext);
  33. // XXX(epurkhiser): The loadOrganization function is stable as long as the
  34. // organization slug is stable. A change to the organization slug will cause
  35. // the organization to be reloaded.
  36. useEffect(() => loadOrganization?.(), [loadOrganization]);
  37. }
  38. /**
  39. * Context provider responsible for loading the organization into the
  40. * OrganizationStore if it is not already present.
  41. *
  42. * This provider *does not* immediately attempt to load the organization. A
  43. * child component must be responsible for calling `useEnsureOrganization` to
  44. * have the organization loaded.
  45. */
  46. export function OrganizationContextProvider({children}: Props) {
  47. const api = useApi();
  48. const configStore = useLegacyStore(ConfigStore);
  49. const {organizations} = useLegacyStore(OrganizationsStore);
  50. const {organization, error} = useLegacyStore(OrganizationStore);
  51. const lastOrganizationSlug: string | null =
  52. configStore.lastOrganization ?? organizations[0]?.slug ?? null;
  53. const routes = useRoutes();
  54. const params = useParams<{orgId?: string}>();
  55. // XXX(epurkhiser): When running in deploy preview mode customer domains are
  56. // not supported correctly. Do NOT use the customer domain from the params.
  57. const orgSlug = DEPLOY_PREVIEW_CONFIG
  58. ? lastOrganizationSlug
  59. : params.orgId || lastOrganizationSlug;
  60. // Provided to the OrganizationLoaderContext. Loads the organization if it is
  61. // not already present.
  62. const loadOrganization = useCallback(() => {
  63. // Nothing to do if we already have the organization loaded
  64. if (organization && organization.slug === orgSlug) {
  65. return;
  66. }
  67. if (!orgSlug) {
  68. OrganizationStore.setNoOrganization();
  69. return;
  70. }
  71. metric.mark({name: 'organization-details-fetch-start'});
  72. fetchOrganizationDetails(api, orgSlug, false, true);
  73. }, [api, orgSlug, organization]);
  74. // Take a measurement for when organization details are done loading and the
  75. // new state is applied
  76. useEffect(
  77. () => {
  78. if (organization === null) {
  79. return;
  80. }
  81. metric.measure({
  82. name: 'app.component.perf',
  83. start: 'organization-details-fetch-start',
  84. data: {
  85. name: 'org-details',
  86. route: getRouteStringFromRoutes(routes),
  87. organization_id: parseInt(organization.id, 10),
  88. },
  89. });
  90. },
  91. // Ignore the `routes` dependency for the metrics measurement
  92. // eslint-disable-next-line react-hooks/exhaustive-deps
  93. [organization]
  94. );
  95. // XXX(epurkhiser): User may be null in some scenarios at this point in app
  96. // boot. We should fix the types here in the future
  97. const user: User | null = configStore.user;
  98. // It may be possible for the user to use the sudo modal to load the organization.
  99. useEffect(() => {
  100. if (!error) {
  101. // If the user has an active staff session, the response will not return a
  102. // 403 but access scopes will be an empty list.
  103. if (user?.isSuperuser && user?.isStaff && organization?.access?.length === 0) {
  104. openSudo({
  105. isSuperuser: true,
  106. needsReload: true,
  107. closeEvents: 'none',
  108. closeButton: false,
  109. });
  110. }
  111. return;
  112. }
  113. if (user?.isSuperuser && error.status === 403) {
  114. openSudo({
  115. isSuperuser: true,
  116. needsReload: true,
  117. closeEvents: 'none',
  118. closeButton: false,
  119. });
  120. }
  121. // This `catch` can swallow up errors in development (and tests)
  122. // So let's log them. This may create some noise, especially the test case where
  123. // we specifically test this branch
  124. console.error(error); // eslint-disable-line no-console
  125. }, [user, error, organization]);
  126. // Switch organizations when the orgId changes
  127. const lastOrgId = useRef(orgSlug);
  128. useEffect(() => {
  129. if (orgSlug && lastOrgId.current !== orgSlug) {
  130. // Only switch on: org1 -> org2
  131. // Not on: undefined -> org1
  132. // Also avoid: org1 -> undefined -> org1
  133. if (lastOrgId.current) {
  134. switchOrganization();
  135. }
  136. lastOrgId.current = orgSlug;
  137. }
  138. }, [orgSlug]);
  139. return (
  140. <OrganizationLoaderContext.Provider value={loadOrganization}>
  141. <OrganizationContext.Provider value={organization}>
  142. {children}
  143. </OrganizationContext.Provider>
  144. </OrganizationLoaderContext.Provider>
  145. );
  146. }