All files / app/features/auth useAuthStore.ts

91.76% Statements 78/85
52.94% Branches 9/17
100% Functions 11/11
91.76% Lines 78/85

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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 22991x 91x 91x 91x 91x 91x 91x   91x 91x 91x           10x 10x 9x     6x     4x         4x         3x       6x                 598x 597x       597x 597x       597x 597x   597x       597x   597x 597x 597x 534x   2x     29x     3x 3x 3x 3x 3x 3x 3x     3x                           3x 3x                     8x 8x 8x 8x         5x 5x         5x     5x   5x     5x                   3x           3x   8x     14x 14x 2x 2x 2x       5x 5x 5x 5x     5x   5x         5x                     3x 3x 3x 3x 3x 1x 1x 1x   3x                   3x               597x                            
import { useQueryClient } from "@tanstack/react-query";
import { userKey } from "features/queryKeys";
import { useTranslation } from "i18n";
import { allLanguages } from "i18n/allLanguages";
import { GLOBAL } from "i18n/namespaces";
import Sentry from "platform/sentry";
import { clearStorage, usePersistedState } from "platform/usePersistedState";
import { AuthRes, SignupFlowRes } from "proto/auth_pb";
import { useMemo, useRef, useState } from "react";
import { service } from "service";
import isGrpcError from "service/utils/isGrpcError";
 
/**
 * Sync the NEXT_LOCALE cookie with the user's language preference from the backend
 */
async function syncLanguagePreference() {
  try {
    const accountInfo = await service.account.getAccountInfo();
    const userLanguage = accountInfo.uiLanguagePreference;
 
    const currentCookieLocale =
      typeof document !== "undefined"
        ? document.cookie
            .split("; ")
            .find((row) => row.startsWith("NEXT_LOCALE="))
            ?.split("=")[1]
        : null;
 
    // Only update cookie if user has a valid language preference and it differs from current cookie
    if (
      userLanguage &&
      allLanguages.includes(userLanguage) &&
      userLanguage !== currentCookieLocale
    ) {
      document.cookie = `NEXT_LOCALE=${userLanguage}; path=/; max-age=31536000; samesite=lax`;
    }
  } catch (e) {
    // Don't fail login if language sync fails, just log the error
    Sentry.captureException(e, {
      tags: {
        component: "auth/useAuthStore",
        action: "syncLanguagePreference",
      },
    });
  }
}
 
export default function useAuthStore() {
  const [authenticated, setAuthenticated] = usePersistedState(
    "auth.authenticated",
    false,
  );
  const [jailed, setJailed] = usePersistedState("auth.jailed", false);
  const [userId, setUserId] = usePersistedState<number | null>(
    "auth.userId",
    null,
  );
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [flowState, setFlowState] =
    usePersistedState<SignupFlowRes.AsObject | null>("auth.flowState", null);
 
  //this is used to set the current user in the user cache
  //may as well not waste the api call since it is needed for userId
  const queryClient = useQueryClient();
 
  const { t } = useTranslation(GLOBAL);
  const fatalErrorMessage = useRef(t("error.fatal_message"));
  const authActions = useMemo(
    () => ({
      authError(message: string) {
        setError(message);
      },
      clearError() {
        setError(null);
      },
      async logout() {
        setError(null);
        setLoading(true);
        try {
          await service.user.logout();
          setAuthenticated(false);
          setUserId(null);
          Sentry.setUser({ id: undefined });
 
          // Notify mobile app if running in embed
          Iif (window.ReactNativeWebView) {
            window.ReactNativeWebView.postMessage(
              JSON.stringify({ type: "LOGOUT" }),
            );
          }
        } catch (e) {
          Sentry.captureException(e, {
            tags: {
              component: "auth/useAuthStore",
              action: "logout",
            },
          });
          setError(isGrpcError(e) ? e.message : fatalErrorMessage.current);
        }
        clearStorage();
        setLoading(false);
      },
      async passwordLogin({
        username,
        password,
        rememberDevice,
      }: {
        username: string;
        password: string;
        rememberDevice: boolean;
      }) {
        setError(null);
        setLoading(true);
        try {
          const auth = await service.user.passwordLogin(
            username,
            password,
            rememberDevice,
          );
          setUserId(auth.userId);
          Sentry.setUser({ id: auth.userId.toString() });
 
          //this must come after setting the userId, because calling setQueryData
          //will also cause that query to be background fetched, and it needs
          //userId to be set.
          setJailed(auth.jailed);
 
          // Sync user's language preference with NEXT_LOCALE cookie
          await syncLanguagePreference();
 
          setAuthenticated(true);
 
          // Notify mobile app that login succeeded
          Iif (window.ReactNativeWebView) {
            window.ReactNativeWebView.postMessage(
              JSON.stringify({
                type: "LOGIN_SUCCESS",
                userId: auth.userId,
                jailed: auth.jailed,
              }),
            );
          }
        } catch (e) {
          Sentry.captureException(e, {
            tags: {
              component: "auth/useAuthStore",
              action: "passwordLogin",
            },
          });
          setError(isGrpcError(e) ? e.message : fatalErrorMessage.current);
        }
        setLoading(false);
      },
      async updateSignupState(state: SignupFlowRes.AsObject) {
        setFlowState(state);
        if (state.authRes) {
          setFlowState(null);
          authActions.firstLogin(state.authRes!);
          return;
        }
      },
      async firstLogin(res: AuthRes.AsObject) {
        setError(null);
        setUserId(res.userId);
        Sentry.setUser({ id: res.userId.toString() });
        setJailed(res.jailed);
 
        // Sync user's language preference with NEXT_LOCALE cookie
        await syncLanguagePreference();
 
        setAuthenticated(true);
 
        // Notify mobile app that signup/login succeeded
        // Note: No credentials sent here since firstLogin is called after signup flow
        // where we don't have access to the original password
        Iif (window.ReactNativeWebView) {
          window.ReactNativeWebView.postMessage(
            JSON.stringify({
              type: "LOGIN_SUCCESS",
              userId: res.userId,
              jailed: res.jailed,
            }),
          );
        }
      },
      async updateJailStatus() {
        setError(null);
        setLoading(true);
        try {
          const res = await service.jail.getIsJailed();
          if (!res.isJailed) {
            setUserId(res.user.userId);
            Sentry.setUser({ id: res.user.userId.toString() });
            queryClient.setQueryData(userKey(res.user.userId), res.user);
          }
          setJailed(res.isJailed);
        } catch (e) {
          Sentry.captureException(e, {
            tags: {
              component: "auth/useAuthStore",
              action: "updateJailStatus",
            },
          });
          setError(isGrpcError(e) ? e.message : fatalErrorMessage.current);
        }
        setLoading(false);
      },
    }),
    //note: there should be no dependenices on the state or t, or
    //some useEffects will break. Eg. the token login in Login.tsx
    [setAuthenticated, setJailed, setUserId, setFlowState, queryClient],
  );
 
  return {
    authActions,
    authState: {
      authenticated,
      error,
      jailed,
      loading,
      userId,
      flowState,
    },
  };
}
 
export type AuthStoreType = ReturnType<typeof useAuthStore>;