organizationContext.tsx 5.9 KB

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