organizationContext.tsx 5.8 KB

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