All files / apps/host/src/contexts AuthContext.tsx

92.85% Statements 39/42
58.33% Branches 14/24
87.5% Functions 7/8
94.87% Lines 37/39

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                                            1x 5x 5x 2x 2x 2x 2x     5x 2x 2x   2x   2x                         5x   4x 4x 1x 1x 1x     3x     2x 2x   2x                   2x                           2x     2x 2x 2x   1x 1x 1x 1x 1x                                     1x 1x 1x             5x     1x  
import { useCallback } from 'react';
import type { FirebaseAuthTypes } from '@react-native-firebase/auth';
import { getAuth, reload } from '@react-native-firebase/auth';
 
import { FIREBASE_ERROR_CODES } from '@repo/constants/error';
 
import { CoreAuthProvider, useCoreAuth } from '@repo/core/auth/CoreAuthProvider';
 
import { safeLaunchDarklyOperation } from '@/utils/launchdarklyHelpers';
 
import { launchdarklyService } from '@/services/launchdarklyService';
import {
  createTokenRegistrationPayload,
  registerNotificationToken,
  resetTokenRegistrationCache,
} from '@/services/notification/notificationApi';
import { getNotificationPreference } from '@/services/notification/notificationPreference';
import { notificationService } from '@/services/notification/notificationService';
import { sentryService } from '@/services/sentryService';
 
import { useChat } from './ChatContext';
 
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
  const { clearChat } = useChat();
  const clearUserData = useCallback(async () => {
    notificationService.clearTokenCache();
    resetTokenRegistrationCache();
    sentryService.clearAuthenticatedUser();
    await safeLaunchDarklyOperation(() => launchdarklyService.clearUser(), 'clear_user');
  }, []);
 
  const identifyLaunchDarklyUser = useCallback((firebaseUser: FirebaseAuthTypes.User) => {
    const providerData = firebaseUser.providerData[0];
    const provider = providerData?.providerId?.replace('.com', '') || 'unknown';
 
    safeLaunchDarklyOperation(
      () =>
        launchdarklyService.identify({
          key: firebaseUser.uid,
          email: firebaseUser.email || undefined,
          name: firebaseUser.displayName || undefined,
          custom: {
            provider: provider === 'google' ? 'google' : provider,
            emailVerified: firebaseUser.emailVerified ? 'true' : 'false',
          },
        }),
      'identify',
    );
  }, []);
 
  const handleAuthStateChange = useCallback(
    async (firebaseUser: FirebaseAuthTypes.User | null) => {
      try {
        if (!firebaseUser) {
          clearChat();
          await clearUserData();
          return;
        }
 
        await reload(firebaseUser);
 
        // Set Sentry user context
        const providerData = firebaseUser.providerData[0];
        const provider = providerData?.providerId?.replace('.com', '') || 'unknown';
 
        sentryService.setAuthenticatedUser({
          id: firebaseUser.uid,
          email: firebaseUser.email,
          username: firebaseUser.displayName,
          provider: provider === 'google' ? 'google' : provider,
          feature: 'auth_state_change',
          additionalContext: {
            google: {
              photoUrl: firebaseUser.photoURL || null,
              emailVerified: firebaseUser.emailVerified,
              providerData: firebaseUser.providerData.map(p => ({
                providerId: p.providerId,
                uid: p.uid,
              })),
            },
            user: {
              creationTime: firebaseUser.metadata.creationTime,
              lastSignInTime: firebaseUser.metadata.lastSignInTime,
              isEmailVerified: firebaseUser.emailVerified,
            },
          },
        });
 
        // Identify user with LaunchDarkly
        identifyLaunchDarklyUser(firebaseUser);
 
        // Setup notifications after login
        try {
          const isNotificationEnabled = await getNotificationPreference();
          if (!isNotificationEnabled) return;
 
          const fcmToken = await notificationService.setupAfterLogin();
          Eif (fcmToken) {
            try {
              const payload = createTokenRegistrationPayload(fcmToken);
              await registerNotificationToken(payload);
            } catch (error) {
              sentryService.captureException(error, {
                tags: {
                  component: 'notification',
                  action: 'register_token_on_login',
                },
              });
            }
          }
        } catch (error) {
          sentryService.captureException(error, {
            tags: {
              component: 'notification',
              action: 'setup_after_login',
            },
          });
        }
      } catch (error: any) {
        Eif (error.code === FIREBASE_ERROR_CODES.AUTH_DISABLED) {
          await getAuth().signOut();
          await clearUserData();
        }
      }
    },
    [clearChat, clearUserData, identifyLaunchDarklyUser],
  );
 
  return <CoreAuthProvider onAuthStateChange={handleAuthStateChange}>{children}</CoreAuthProvider>;
};
 
export const useAuth = () => useCoreAuth();