frontend_nyla/src/hooks/useAuth.ts
idittrich-valueon 9e8d34a7ac changed routes
2025-05-14 12:51:17 +02:00

92 lines
No EOL
3.1 KiB
TypeScript

import { useState } from 'react';
import axios from 'axios';
interface LoginResponse {
accessToken: string;
tokenType: string;
label?: any;
fieldLabels?: any;
}
interface UseAuthReturn {
login: (username: string, password: string) => Promise<LoginResponse>;
error: string | null;
isLoading: boolean;
}
export function useAuth(): UseAuthReturn {
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const login = async (username: string, password: string): Promise<LoginResponse> => {
setIsLoading(true);
setError(null);
try {
// Create the form data in the exact format FastAPI expects
const params = new URLSearchParams();
params.append('username', username);
params.append('password', password);
params.append('grant_type', 'password');
params.append('scope', '');
params.append('client_id', '');
params.append('client_secret', '');
// Create a custom axios instance for this request
const instance = axios.create({
baseURL: 'https://gateway.poweron-center.net',
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const response = await instance.post('/api/token', params);
console.log('Login response:', response.data);
// Store the entire auth response
if (response.data.accessToken) {
localStorage.setItem('auth_data', JSON.stringify(response.data));
}
return response.data;
} catch (error: any) {
let errorMessage = 'An error occurred during login';
if (error.response) {
// Log the complete error details including the request that was sent
console.error('Login error details:', {
status: error.response.status,
statusText: error.response.statusText,
data: error.response.data,
headers: error.response.headers,
request: {
url: error.config?.url,
method: error.config?.method,
data: error.config?.data,
params: error.config?.params
}
});
errorMessage = error.response.data?.detail || 'Invalid username or password';
} else if (error.request) {
console.error('No response received:', error.request);
errorMessage = 'No response received from server';
} else {
console.error('Error:', error.message);
errorMessage = error.message;
}
setError(errorMessage);
throw error;
} finally {
setIsLoading(false);
}
};
return {
login,
error,
isLoading
};
}