All files / src/features/auth/services auth.service.ts

97.61% Statements 41/42
78.57% Branches 11/14
100% Functions 9/9
97.61% Lines 41/42

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                                                                    3x 3x       1x 1x   2x 2x               3x 3x         1x 1x   2x 2x               2x       2x     2x                   2x 2x 1x 1x   1x 1x             2x 2x 1x   1x 1x               2x 2x       1x   1x 1x                   16x 2x       2x       2x 2x       2x       4x 4x 4x       13x  
import { apiClient } from '@/lib/http-client';
import { useAuthStore } from '@/store/auth-store';
import { AUTH_API_ENDPOINTS, AUTH_ERROR_MESSAGES } from '@/constants/auth';
 
export interface AuthResponse {
  jwt: string;
  user: {
    id: number;
    username: string;
    email: string;
    confirmed: boolean;
    blocked: boolean;
    createdAt: string;
    updatedAt: string;
  };
}
 
export interface SigninData {
  email: string;
  password: string;
}
 
export interface SignupData {
  email: string;
  password: string;
  confirmPassword: string;
}
 
/**
 * AuthService - Handles API calls for authentication
 * This service should only handle API communication, not state management
 */
class AuthService {
  async signin(data: SigninData): Promise<AuthResponse> {
    try {
      const response = await apiClient.post(AUTH_API_ENDPOINTS.SIGNIN, {
        identifier: data.email,
        password: data.password,
      });
      console.log('🔐 [AuthService] Signin successful:', { email: data.email });
      return response;
    } catch (error: any) {
      console.error('🔐 [AuthService] Signin failed:', error);
      throw new Error(
        error?.response?.data?.error?.message ||
          AUTH_ERROR_MESSAGES.SIGNIN_FAILED
      );
    }
  }
 
  async signup(data: SignupData): Promise<AuthResponse> {
    try {
      const response = await apiClient.post(AUTH_API_ENDPOINTS.SIGNUP, {
        username: data.email, // Using email as username
        email: data.email,
        password: data.password,
      });
      console.log('🔐 [AuthService] Signup successful:', { email: data.email });
      return response;
    } catch (error: any) {
      console.error('🔐 [AuthService] Signup failed:', error);
      throw new Error(
        error?.response?.data?.error?.message ||
          AUTH_ERROR_MESSAGES.SIGNUP_FAILED
      );
    }
  }
 
  async logout(): Promise<void> {
    console.log('🔐 [AuthService] Logout called');
    // This service should only handle API calls
    // Store clearing is handled by hooks (useLogout)
 
    try {
      // If you have a logout endpoint, call it here
      // await apiClient.post(AUTH_API_ENDPOINTS.LOGOUT);
      console.log(
        '🔐 [AuthService] API logout call completed (no endpoint configured)'
      );
    } catch (error) {
      console.error('🔐 [AuthService] Logout API call failed:', error);
      // Don't throw error for logout API failures
    }
  }
 
  async refreshToken(token: string): Promise<AuthResponse> {
    try {
      const response = await apiClient.post('/auth/refresh', { token });
      console.log('🔐 [AuthService] Token refresh successful');
      return response;
    } catch (error: any) {
      console.error('🔐 [AuthService] Token refresh failed:', error);
      throw new Error(
        error?.response?.data?.error?.message || 'Token refresh failed'
      );
    }
  }
 
  async forgotPassword(email: string): Promise<void> {
    try {
      await apiClient.post(AUTH_API_ENDPOINTS.FORGOT_PASSWORD, { email });
      console.log('🔐 [AuthService] Forgot password email sent:', { email });
    } catch (error: any) {
      console.error('🔐 [AuthService] Forgot password failed:', error);
      throw new Error(
        error?.response?.data?.error?.message ||
          AUTH_ERROR_MESSAGES.FORGOT_PASSWORD_FAILED
      );
    }
  }
 
  async resetPassword(token: string, password: string): Promise<void> {
    try {
      await apiClient.post(AUTH_API_ENDPOINTS.RESET_PASSWORD, {
        token,
        password,
      });
      console.log('🔐 [AuthService] Password reset successful');
    } catch (error: any) {
      console.error('🔐 [AuthService] Password reset failed:', error);
      throw new Error(
        error?.response?.data?.error?.message ||
          AUTH_ERROR_MESSAGES.RESET_PASSWORD_FAILED
      );
    }
  }
 
  // Utility methods for accessing auth state
  // These methods access the Zustand store directly for backward compatibility
  getAuthToken(): string | null {
    const { token } = useAuthStore.getState();
    console.log(
      '🔐 [AuthService] Getting auth token:',
      token ? 'Token found' : 'No token'
    );
    return token;
  }
 
  getUser(): any | null {
    const { user } = useAuthStore.getState();
    console.log(
      '🔐 [AuthService] Getting user:',
      user ? `User: ${user.username}` : 'No user'
    );
    return user;
  }
 
  isAuthenticated(): boolean {
    const { isAuthenticated } = useAuthStore.getState();
    console.log('🔐 [AuthService] Checking authentication:', isAuthenticated);
    return isAuthenticated;
  }
}
 
export const authService = new AuthService();