organizationContext.tsx 7.0 KB

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