All files / stores auth.store.ts

100% Statements 21/21
83.33% Branches 5/6
100% Functions 7/7
100% Lines 21/21

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                                                        9x   9x                       20x   20x 20x   13x                   7x   7x                   7x           6x   6x                         2x         15x     15x 8x   8x     5x     3x 3x             9x                         229x                    
/**
 * Authentication store using Zustand
 * Manages authentication state, login, logout, and session persistence
 */
 
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import * as authService from '@/services/auth.service';
import type { AuthResponse, UserInfo, AccountInfo } from '@/types/auth.types';
 
interface AuthState {
  // State
  user: UserInfo | null;
  account: AccountInfo | null;
  token: string | null;
  refreshToken: string | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
 
  // Actions
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  clearError: () => void;
  restoreSession: () => Promise<void>;
  setAuth: (response: AuthResponse) => void;
}
 
export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      // Initial state
      user: null,
      account: null,
      token: null,
      refreshToken: null,
      isAuthenticated: false,
      isLoading: false,
      error: null,
 
      // Login action
      login: async (email: string, password: string) => {
        set({ isLoading: true, error: null });
 
        try {
          const response = await authService.login(email, password);
 
          set({
            user: response.user,
            account: response.account,
            token: response.token,
            refreshToken: response.refresh_token,
            isAuthenticated: true,
            isLoading: false,
            error: null,
          });
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : 'Login failed';
          
          set({
            user: null,
            account: null,
            token: null,
            refreshToken: null,
            isAuthenticated: false,
            isLoading: false,
            error: errorMessage,
          });
 
          throw error;
        }
      },
 
      // Logout action
      logout: () => {
        authService.logout();
        
        set({
          user: null,
          account: null,
          token: null,
          refreshToken: null,
          isAuthenticated: false,
          isLoading: false,
          error: null,
        });
      },
 
      // Clear error
      clearError: () => {
        set({ error: null });
      },
 
      // Restore session (called on app load)
      restoreSession: async () => {
        const { token, isAuthenticated } = get();
 
        // If we have a token, verify it's still valid
        if (token && isAuthenticated) {
          try {
            // Try to get current user info to verify token
            await authService.getCurrentUser();
            
            // Token is valid, session restored
            set({ isLoading: false });
          } catch (error) {
            // Token is invalid, clear session
            console.error('Session restoration failed:', error);
            get().logout();
          }
        }
      },
 
      // Set auth state manually (e.g. after registration or invitation acceptance)
      setAuth: (response: AuthResponse) => {
        set({
          user: response.user,
          account: response.account,
          token: response.token,
          refreshToken: response.refresh_token,
          isAuthenticated: true,
          isLoading: false,
          error: null,
        });
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        user: state.user,
        account: state.account,
        token: state.token,
        refreshToken: state.refreshToken,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
);