All files / app/features/auth AuthProvider.tsx

97.29% Statements 36/37
75% Branches 6/8
87.5% Functions 7/8
97.14% Lines 34/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66  127x 127x 127x 127x 127x 127x 127x 127x   127x 127x   127x     1600x 1600x     1600x     777x 858x 858x 858x   858x       858x 858x 774x     858x 827x   2x 1x   1x   1x   1x       1x 1x       827x 827x             1600x  
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { AUTH } from "i18n/namespaces";
import { useRouter } from "next/router";
import Sentry from "platform/sentry";
import React, { Context, ReactNode, useContext, useEffect } from "react";
import { jailRoute, loginRoute } from "routes";
import { setUnauthenticatedErrorHandler } from "service/client";
import useStablePush from "utils/useStablePush";
 
import { JAILED_ERROR_MESSAGE } from "./constants";
import useAuthStore, { AuthStoreType } from "./useAuthStore";
 
const AuthContext = React.createContext<null | AuthStoreType>(null);
 
function useAppContext<T>(context: Context<T | null>) {
  const contextValue = useContext(context);
  Iif (contextValue === null) {
    throw Error("No context provided!");
  }
  return contextValue;
}
 
export default function AuthProvider({ children }: { children: ReactNode }) {
  const { t } = useTranslation(AUTH);
  const store = useAuthStore();
  const router = useRouter();
 
  const push = useStablePush();
 
  // A page reload restores auth from localStorage without going through the auth
  // actions that set the Sentry user, so sync it here too.
  const userId = store.authState.userId;
  useEffect(() => {
    Sentry.setUser(userId ? { id: userId.toString() } : null);
  }, [userId]);
 
  useEffect(() => {
    setUnauthenticatedErrorHandler(async (e: RpcError) => {
      // the backend will return "Permission denied" if you're just jailed, and "Unauthorized" otherwise
      if (e.message === JAILED_ERROR_MESSAGE) {
        const isJailRouteException = router.pathname.includes("delete-account");
 
        await store.authActions.updateJailStatus();
 
        Eif (!isJailRouteException) {
          // if the user is jailed, redirect them to the jail route
          push(jailRoute);
        }
      } else {
        // completely logged out
        await store.authActions.logout();
        push(loginRoute);
      }
    });
 
    return () => {
      setUnauthenticatedErrorHandler(async () => {});
    };
  }, [store.authActions, push, t, router.pathname]);
 
  return <AuthContext.Provider value={store}>{children}</AuthContext.Provider>;
}
 
export const useAuthContext = () => useAppContext(AuthContext);