organizationContext.tsx 5.7 KB

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