All files / apps/web/src/contexts AuthContext.jsx

68.08% Statements 64/94
35% Branches 14/40
58.33% Functions 7/12
68.81% Lines 64/93

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      1x   1x 15x 15x 15x 15x 15x 15x   15x 6x 6x 1x 1x 1x 1x     5x 5x 5x 4x   4x 4x 4x 4x 4x 4x 4x 4x                   1x 1x 1x     5x 5x       15x 6x     15x         15x 3x 3x 3x 3x 3x 3x 3x     15x 1x 1x 1x 1x 1x 1x                   15x                             15x 1x 1x 1x 1x                 15x                         15x                         15x                                 15x             1x 15x 15x     15x  
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import api from '../services/api';
 
const AuthContext = createContext(null);
 
export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [organizations, setOrganizations] = useState([]);
  const [pendingInvitations, setPendingInvitations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [authChecked, setAuthChecked] = useState(false);
 
  const fetchUser = useCallback(async () => {
    const token = localStorage.getItem('accessToken');
    if (!token) {
      console.log('No token found, user not authenticated');
      setLoading(false);
      setAuthChecked(true);
      return;
    }
 
    try {
      console.log('Fetching user with token...');
      const response = await api.get('/auth/me');
      console.log('Auth response:', response.data);
      
      if (response.data && response.data.success) {
        const data = response.data.data;
        if (data?.user) {
          console.log('User authenticated:', data.user.email);
          setUser({ ...data.user, defaultOrganizationId: data.defaultOrganizationId });
          setOrganizations(data.organizations || []);
          setPendingInvitations(data.pendingInvitations || []);
          setIsAuthenticated(true);
        } else E{
          console.log('No user data in response, logging out');
          logout();
        }
      } else E{
        console.log('Auth response not successful');
        logout();
      }
    } catch (error) {
      console.error('Failed to fetch user:', error.response?.data || error.message);
      Eif (error.response?.status === 401) {
        logout();
      }
    } finally {
      setLoading(false);
      setAuthChecked(true);
    }
  }, []);
 
  useEffect(() => {
    fetchUser();
  }, [fetchUser]);
 
  const loginWithGoogle = (plan) => {
    const qs = plan ? `?plan=${encodeURIComponent(plan)}` : '';
    window.location.href = `/api/v1/auth/google${qs}`;
  };
 
  const logout = () => {
    console.log('Logging out user');
    localStorage.removeItem('accessToken');
    localStorage.removeItem('userId');
    setUser(null);
    setOrganizations([]);
    setPendingInvitations([]);
    setIsAuthenticated(false);
  };
 
  const updateSettings = async (settings) => {
    try {
      const response = await api.patch('/auth/settings', settings);
      Eif (response.data.success) {
        const updatedUser = response.data.data?.user || response.data.user;
        setUser(updatedUser);
        return { success: true };
      }
    } catch (error) {
      return { 
        success: false, 
        error: error.response?.data?.message || 'Failed to update settings' 
      };
    }
  };
 
  const updateDefaultOrganization = async (defaultOrganizationId) => {
    try {
      const response = await api.patch('/auth/me', { defaultOrganizationId });
      if (response.data.success) {
        setUser(prev => ({ ...prev, defaultOrganizationId }));
        return { success: true };
      }
    } catch (error) {
      return { 
        success: false, 
        error: error.response?.data?.message || 'Failed to update default organization' 
      };
    }
  };
 
  const deleteAccount = async () => {
    try {
      await api.delete('/auth/me');
      logout();
      return { success: true };
    } catch (error) {
      return { 
        success: false, 
        error: error.response?.data?.message || 'Failed to delete account' 
      };
    }
  };
 
  const acceptInvitation = async (organizationId) => {
    try {
      const response = await api.post(`/organizations/${organizationId}/acceptInvitation`);
      if (response.data.success) {
        await fetchUser();
        return { success: true, organization: response.data.data?.organization };
      }
      return { success: false, error: response.data?.message };
    } catch (error) {
      return { success: false, error: error.response?.data?.message || 'Failed to accept invitation' };
    }
  };
 
  const declineInvitation = async (organizationId) => {
    try {
      const response = await api.post(`/organizations/${organizationId}/declineInvitation`);
      if (response.data.success) {
        await fetchUser();
        return { success: true };
      }
      return { success: false, error: response.data?.message };
    } catch (error) {
      return { success: false, error: error.response?.data?.message || 'Failed to decline invitation' };
    }
  };
 
  const value = {
    user,
    organizations,
    pendingInvitations,
    isAuthenticated,
    loading,
    authChecked,
    loginWithGoogle,
    logout,
    updateSettings,
    updateDefaultOrganization,
    deleteAccount,
    acceptInvitation,
    declineInvitation,
    refreshUser: fetchUser
  };
 
  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};
 
export const useAuth = () => {
  const context = useContext(AuthContext);
  Iif (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};