2024-02-26 09:39:09 -05:00
|
|
|
import { useUserStore } from '../store/user-store';
|
|
|
|
|
import { Body_login_login_access_token as AccessToken, LoginService } from '../client';
|
|
|
|
|
import { useUsersStore } from '../store/users-store';
|
|
|
|
|
import { useItemsStore } from '../store/items-store';
|
2024-02-27 15:47:42 -05:00
|
|
|
import { useNavigate } from 'react-router-dom';
|
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-29 09:47:13 -05:00
|
|
|
const { getUser, resetUser } = useUserStore();
|
2024-02-26 09:39:09 -05:00
|
|
|
const { resetUsers } = useUsersStore();
|
|
|
|
|
const { resetItems } = useItemsStore();
|
2024-02-27 15:47:42 -05:00
|
|
|
const navigate = useNavigate();
|
|
|
|
|
|
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);
|
|
|
|
|
await getUser();
|
2024-02-29 09:47:13 -05:00
|
|
|
navigate('/');
|
2024-02-26 09:39:09 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const logout = () => {
|
|
|
|
|
localStorage.removeItem('access_token');
|
|
|
|
|
resetUser();
|
|
|
|
|
resetUsers();
|
|
|
|
|
resetItems();
|
2024-02-27 15:47:42 -05:00
|
|
|
navigate('/login');
|
2024-02-26 09:39:09 -05:00
|
|
|
};
|
|
|
|
|
|
2024-02-29 09:47:13 -05:00
|
|
|
return { login, logout };
|
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;
|