organizationContext.tsx 5.7 KB

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