MCPcopy Index your code
hub / github.com/coder/coder / RequireAuth

Function RequireAuth

site/src/contexts/auth/RequireAuth.tsx:24–83  ·  view source on GitHub ↗
({
	DashboardProvider = ProductionDashboardProvider,
	ProxyProvider = ProductionProxyProvider,
})

Source from the content-addressed store, hash-verified

22 * specific providers to mock them out.
23 */
24export const RequireAuth: FC<RequireAuthProps> = ({
25 DashboardProvider = ProductionDashboardProvider,
26 ProxyProvider = ProductionProxyProvider,
27}) => {
28 const location = useLocation();
29 const { signOut, isSigningOut, isSignedOut, isSignedIn, isLoading } =
30 useAuthContext();
31
32 useEffect(() => {
33 if (isLoading || isSigningOut || !isSignedIn) {
34 return;
35 }
36
37 const axiosInstance = API.getAxiosInstance();
38 const interceptorHandle = axiosInstance.interceptors.response.use(
39 (okResponse) => okResponse,
40 (error: unknown) => {
41 // 401 Unauthorized
42 // If we encountered an authentication error, then our token is probably
43 // invalid and we should update the auth state to reflect that.
44 if (isApiError(error) && error.response.status === 401) {
45 signOut();
46 }
47
48 // Otherwise, pass the response through so that it can be displayed in
49 // the UI
50 return Promise.reject(error);
51 },
52 );
53
54 return () => {
55 axiosInstance.interceptors.response.eject(interceptorHandle);
56 };
57 }, [isLoading, isSigningOut, isSignedIn, signOut]);
58
59 if (isLoading || isSigningOut) {
60 return <Loader fullscreen />;
61 }
62
63 if (isSignedOut) {
64 const isHomePage = location.pathname === "/";
65 const navigateTo = isHomePage
66 ? "/login"
67 : embedRedirect(`${location.pathname}${location.search}`);
68
69 return (
70 <Navigate to={navigateTo} state={{ isRedirect: !isHomePage }} replace />
71 );
72 }
73
74 // Authenticated pages have access to some contexts for knowing enabled experiments
75 // and where to route workspace connections.
76 return (
77 <DashboardProvider>
78 <ProxyProvider>
79 <Outlet />
80 </ProxyProvider>
81 </DashboardProvider>

Callers

nothing calls this directly

Calls 3

useAuthContextFunction · 0.90
isApiErrorFunction · 0.90
embedRedirectFunction · 0.90

Tested by

no test coverage detected