2024-03-07 19:16:23 +01:00
|
|
|
import { useQuery } from 'react-query';
|
|
|
|
|
import { useNavigate } from '@tanstack/react-router';
|
|
|
|
|
|
|
|
|
|
import { Body_login_login_access_token as AccessToken, LoginService, UserOut, UsersService } from '../client';
|
2024-02-26 09:39:09 -05:00
|
|
|
|
2024-02-29 09:47:13 -05:00
|
|
|
const isLoggedIn = () => {
|
|
|
|
|
return localStorage.getItem('access_token') !== null;
|
|
|
|
|
};
|
|
|
|
|
|
2024-02-26 09:39:09 -05:00
|
|
|
const useAuth = () => {
|
2024-02-27 15:47:42 -05:00
|
|
|
const navigate = useNavigate();
|
2024-03-07 19:16:23 +01:00
|
|
|
const { data: user, isLoading } = useQuery<UserOut | null, Error>('currentUser', UsersService.readUserMe, {
|
|
|
|
|
enabled: isLoggedIn(),
|
|
|
|
|
});
|
2024-02-27 15:47:42 -05:00
|
|
|
|
2024-02-26 09:39:09 -05:00
|
|
|
const login = async (data: AccessToken) => {
|
|
|
|
|
const response = await LoginService.loginAccessToken({
|
|
|
|
|
formData: data,
|
|
|
|
|
});
|
|
|
|
|
localStorage.setItem('access_token', response.access_token);
|
2024-03-07 19:16:23 +01:00
|
|
|
navigate({ to: '/' });
|
2024-02-26 09:39:09 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const logout = () => {
|
|
|
|
|
localStorage.removeItem('access_token');
|
2024-03-07 19:16:23 +01:00
|
|
|
navigate({ to: '/login' });
|
2024-02-26 09:39:09 -05:00
|
|
|
};
|
|
|
|
|
|
2024-03-07 19:16:23 +01:00
|
|
|
return { login, logout, user, isLoading };
|
2024-02-26 09:39:09 -05:00
|
|
|
}
|
|
|
|
|
|
2024-02-29 09:47:13 -05:00
|
|
|
export { isLoggedIn };
|
2024-02-26 09:39:09 -05:00
|
|
|
export default useAuth;
|