fix login check and urls

This commit is contained in:
Patryk
2025-06-07 23:08:21 +02:00
parent 472dcfc96a
commit c19333ad8b
10 changed files with 424 additions and 374 deletions

View File

@@ -1,17 +1,16 @@
import axios from "axios"; import axios from "axios";
import {useAuthStore} from "@/store/authStore"; import { useAuthStore } from "@/store/authStore";
const API_URL = "https://testowe.zikor.pl/api/v1"; const API_URL = "https://hopp.zikor.pl/api/v1";
export async function listCategories() { export async function listCategories() {
const { token } = useAuthStore.getState();
const { token } = useAuthStore.getState(); const headers = token ? { Authorization: `Bearer ${token}` } : {};
const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
try {
try { const response = await axios.get(`${API_URL}/vars/categories`, { headers });
const response = await axios.get(`${API_URL}/vars/categories`, { headers }); return response.data;
return response.data; } catch (err) {
} catch (err) { console.error("Nie udało się pobrać listy kategorii.", err.response.status);
console.error("Nie udało się pobrać listy kategorii.", err.response.status); }
} }
}

View File

@@ -1,13 +1,16 @@
import axios from "axios"; import axios from "axios";
const API_URL = "https://testowe.zikor.pl/api/v1"; const API_URL = "https://hopp.zikor.pl/api/v1";
export async function getUserById(userId) { export async function getUserById(userId) {
try { try {
const response = await axios.get(`${API_URL}/clients/get/${userId}`); const response = await axios.get(`${API_URL}/clients/get/${userId}`);
return response.data; return response.data;
} catch (err) { } catch (err) {
console.error(`Nie udało się pobrać danych użytkownika o ID ${userId}.`, err.response.status); console.error(
throw err; `Nie udało się pobrać danych użytkownika o ID ${userId}.`,
} err.response.status
);
throw err;
}
} }

View File

@@ -1,129 +1,133 @@
import axios from "axios"; import axios from "axios";
import FormData from 'form-data' import FormData from "form-data";
import {useAuthStore} from "@/store/authStore"; import { useAuthStore } from "@/store/authStore";
const API_URL = "https://testowe.zikor.pl/api/v1"; const API_URL = "https://hopp.zikor.pl/api/v1";
//const API_URL = "http://10.0.2.2:8080/api/v1"; //const API_URL = "http://10.0.2.2:8080/api/v1";
export async function listNotices() { export async function listNotices() {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
const headers = token ? { 'Authorization': `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
console.log(token); console.log(token);
const response = await fetch(`${API_URL}/notices/get/all`, { const response = await fetch(`${API_URL}/notices/get/all`, {
headers: headers headers: headers,
}); });
console.log(response); // console.log(response);r
const data = await response.json(); const data = await response.json();
if (!response.ok) { if (!response.ok) {
throw new Error(response.toString()); throw new Error(response.toString());
} }
return data; return data;
} }
export async function getNoticeById(noticeId) { export async function getNoticeById(noticeId) {
const response = await fetch(`${API_URL}/notices/get/${noticeId}`); const response = await fetch(`${API_URL}/notices/get/${noticeId}`);
const data = await response.json(); const data = await response.json();
if (!response.ok) { if (!response.ok) {
throw new Error("Error"); throw new Error("Error");
} }
return data; return data;
} }
export async function createNotice(notice) { export async function createNotice(notice) {
try { try {
const response = await axios.post(`${API_URL}/notices/add`, notice, { const response = await axios.post(`${API_URL}/notices/add`, notice, {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
}); });
if (response.data.noticeId !== null) { if (response.data.noticeId !== null) {
for (const imageUri of notice.image) { for (const imageUri of notice.image) {
await uploadImage(response.data.noticeId, imageUri); await uploadImage(response.data.noticeId, imageUri);
} }
}
return response.data;
} catch (error) {
console.log("Error", error.response.data, error.response.status);
return null;
} }
return response.data;
} catch (error) {
console.log("Error", error.response.data, error.response.status);
return null;
}
} }
export async function getImageByNoticeId(noticeId) { export async function getImageByNoticeId(noticeId) {
let imageUrl; let imageUrl;
try { try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`); const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`);
const imageName = listResponse.data[0]; const imageName = listResponse.data[0];
imageUrl = `${API_URL}/images/get/${imageName}`; imageUrl = `${API_URL}/images/get/${imageName}`;
console.log(`Pobrano zdjęcie o nazwie: ${imageName}`); console.log(`Pobrano zdjęcie o nazwie: ${imageName}`);
return imageUrl; return imageUrl;
} catch (err) { } catch (err) {
console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`); console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`);
imageUrl = "https://http.cat/404.jpg"; imageUrl = "https://http.cat/404.jpg";
return imageUrl; return imageUrl;
} }
} }
export async function getAllImagesByNoticeId(noticeId) { export async function getAllImagesByNoticeId(noticeId) {
try { try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`); const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`);
if (listResponse.data && listResponse.data.length > 0) { if (listResponse.data && listResponse.data.length > 0) {
const imageUrls = listResponse.data.map(imageName => const imageUrls = listResponse.data.map(
`${API_URL}/images/get/${imageName}` (imageName) => `${API_URL}/images/get/${imageName}`
); );
// console.log(`Pobrano ${imageUrls.length} zdjęć dla ogłoszenia o id: ${noticeId}`); // console.log(`Pobrano ${imageUrls.length} zdjęć dla ogłoszenia o id: ${noticeId}`);
return imageUrls; return imageUrls;
}
// console.log(`Brak zdjęć dla ogłoszenia o id: ${noticeId}`);
return ["https://http.cat/404.jpg"];
} catch (err) {
// console.log(`Błąd podczas pobierania listy zdjęć dla ogłoszenia o id: ${noticeId}`, err);
return ["https://http.cat/404.jpg"];
} }
// console.log(`Brak zdjęć dla ogłoszenia o id: ${noticeId}`);
return ["https://http.cat/404.jpg"];
} catch (err) {
// console.log(`Błąd podczas pobierania listy zdjęć dla ogłoszenia o id: ${noticeId}`, err);
return ["https://http.cat/404.jpg"];
}
} }
export const uploadImage = async (noticeId, imageUri) => { export const uploadImage = async (noticeId, imageUri) => {
console.log(imageUri); console.log(imageUri);
const formData = new FormData(); const formData = new FormData();
const filename = imageUri.split('/').pop(); const filename = imageUri.split("/").pop();
const match = /\.(\w+)$/.exec(filename); const match = /\.(\w+)$/.exec(filename);
const type = match ? `image/${match[1]}` : 'image/jpeg'; const type = match ? `image/${match[1]}` : "image/jpeg";
formData.append('file', { formData.append("file", {
uri: imageUri, uri: imageUri,
name: filename, name: filename,
type: type, type: type,
}); });
try { try {
const response = await axios.post( const response = await axios.post(
`${API_URL}/images/upload/${noticeId}`, `${API_URL}/images/upload/${noticeId}`,
formData, formData,
{ {
headers: { headers: {
'Content-Type': 'multipart/form-data', "Content-Type": "multipart/form-data",
}, },
} }
); );
console.info('Upload successful:', response.data); console.info("Upload successful:", response.data);
return response.data; return response.data;
} catch (error) { } catch (error) {
console.log("imageURI:", imageUri); console.log("imageURI:", imageUri);
console.error('Error uploading image:', error.response.data, error.response.status); console.error(
throw error; "Error uploading image:",
} error.response.data,
} error.response.status
);
throw error;
}
};

View File

@@ -1,34 +1,38 @@
import axios from "axios"; import axios from "axios";
import {useAuthStore} from "@/store/authStore"; import { useAuthStore } from "@/store/authStore";
// import FormData from 'form-data' // import FormData from 'form-data'
const API_URL = "https://testowe.zikor.pl/api/v1/wishlist"; const API_URL = "https://hopp.zikor.pl/api/v1/wishlist";
export async function toggleNoticeStatus(noticeId) { export async function toggleNoticeStatus(noticeId) {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
const headers = token ? { 'Authorization': `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
try { try {
const response = await axios.post(`${API_URL}/toggle/${noticeId}`, {}, { const response = await axios.post(
headers `${API_URL}/toggle/${noticeId}`,
}); {},
return response.data; {
} catch (error) { headers,
console.error("Error toggling wishlist item:", error); }
throw error; );
} return response.data;
} catch (error) {
console.error("Error toggling wishlist item:", error);
throw error;
}
} }
export async function getWishlist() { export async function getWishlist() {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
const headers = token ? { 'Authorization': `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
try { try {
const response = await axios.get(`${API_URL}/`, {headers}); const response = await axios.get(`${API_URL}/`, { headers });
console.log("Wishlist response:", response.data); console.log("Wishlist response:", response.data);
return response.data; return response.data;
} catch (error) { } catch (error) {
console.error("Error fetching wishlist:", error); console.error("Error fetching wishlist:", error);
throw error; throw error;
} }
} }

View File

@@ -1,64 +1,70 @@
import {Tabs} from "expo-router"; import { Tabs, Redirect } from "expo-router";
import {Ionicons} from "@expo/vector-icons"; import { Ionicons } from "@expo/vector-icons";
import { useAuthStore } from "@/store/authStore";
export default function TabLayout() { export default function TabLayout() {
return ( const token = useAuthStore((state) => state.token);
<Tabs
screenOptions={{ if (!token) {
tabBarActiveTintColor: "rgb(var(--color-primary-500))", return <Redirect href="/login" />;
}} }
> return (
<Tabs.Screen <Tabs
name="index" screenOptions={{
options={{ tabBarActiveTintColor: "rgb(var(--color-primary-500))",
title: "Home", }}
tabBarLabel: "Home", >
tabBarIcon: ({color, size}) => ( <Tabs.Screen
<Ionicons name="home-outline" size={size} color={color}/> name="index"
), options={{
}} title: "Home",
/> tabBarLabel: "Home",
<Tabs.Screen tabBarIcon: ({ color, size }) => (
name="notices" <Ionicons name="home-outline" size={size} color={color} />
options={{ ),
title: "Ogłoszenia", }}
tabBarLabel: "Ogłoszenia", />
tabBarIcon: ({color, size}) => ( <Tabs.Screen
<Ionicons name="list-outline" size={size} color={color}/> name="notices"
), options={{
}} title: "Ogłoszenia",
/> tabBarLabel: "Ogłoszenia",
<Tabs.Screen tabBarIcon: ({ color, size }) => (
name="notice/create" <Ionicons name="list-outline" size={size} color={color} />
options={{ ),
title: "Dodaj", }}
tabBarLabel: "Dodaj", />
tabBarIcon: ({color, size}) => ( <Tabs.Screen
<Ionicons name="add-circle-outline" size={size} color={color}/> name="notice/create"
), options={{
}} title: "Dodaj",
/> tabBarLabel: "Dodaj",
<Tabs.Screen tabBarIcon: ({ color, size }) => (
name="wishlist" <Ionicons name="add-circle-outline" size={size} color={color} />
options={{ ),
title: "Ulubione", }}
tabBarLabel: "Ulubione", />
tabBarIcon: ({color, size}) => ( <Tabs.Screen
<Ionicons name="heart-outline" size={size} color={color}/> name="wishlist"
), options={{
}} title: "Ulubione",
/> tabBarLabel: "Ulubione",
<Tabs.Screen tabBarIcon: ({ color, size }) => (
name="dashboard" <Ionicons name="heart-outline" size={size} color={color} />
options={{ ),
headerShown: false, }}
title: "Konto", />
tabBarLabel: "Konto", <Tabs.Screen
tabBarIcon: ({color, size}) => ( name="dashboard"
<Ionicons name="person-outline" size={size} color={color}/> options={{
), headerShown: false,
}} title: "Konto",
/> tabBarLabel: "Konto",
</Tabs> tabBarIcon: ({ color, size }) => (
); <Ionicons name="person-outline" size={size} color={color} />
),
}}
/>
</Tabs>
);
} }

View File

@@ -1,6 +1,15 @@
import { DrawerItem } from "@react-navigation/drawer";
import { Drawer } from "expo-router/drawer"; import { Drawer } from "expo-router/drawer";
import { useAuthStore } from "@/store/authStore";
import {
DrawerContentScrollView,
DrawerItemList,
} from "@react-navigation/drawer";
export default function AccountDrawerLayout() { export default function AccountDrawerLayout() {
const signOut = useAuthStore((state) => state.signOut);
return ( return (
<Drawer <Drawer
screenOptions={{ screenOptions={{
@@ -9,10 +18,19 @@ export default function AccountDrawerLayout() {
drawerActiveBackgroundColor: "#f0f0f0", drawerActiveBackgroundColor: "#f0f0f0",
drawerItemStyle: { drawerItemStyle: {
borderRadius: 8, borderRadius: 8,
// backgroundColor: "transparent",
}, },
headerTintColor: "#1c1c1e", headerTintColor: "#1c1c1e",
}} }}
drawerContent={(props) => (
<DrawerContentScrollView {...props}>
<DrawerItemList {...props} />
<DrawerItem
label="Wyloguj"
onPress={signOut}
labelStyle={{ color: "red" }}
/>
</DrawerContentScrollView>
)}
> >
<Drawer.Screen name="account" options={{ title: "Konto" }} /> <Drawer.Screen name="account" options={{ title: "Konto" }} />
<Drawer.Screen <Drawer.Screen

View File

@@ -1,21 +1,20 @@
import { ScrollView, View } from "react-native"; import { ScrollView, View } from "react-native";
import { useNoticesStore } from '@/store/noticesStore'; import { useNoticesStore } from "@/store/noticesStore";
import { CategorySection } from "@/components/CategorySection"; import { CategorySection } from "@/components/CategorySection";
import { NoticeSection } from "@/components/NoticeSection"; import { NoticeSection } from "@/components/NoticeSection";
import { UserSection } from "@/components/UserSection"; import { UserSection } from "@/components/UserSection";
import { SearchSection } from "@/components/SearchSection"; import { SearchSection } from "@/components/SearchSection";
import { FlatList } from 'react-native'; import { FlatList } from "react-native";
import { useAuthStore } from "@/store/authStore"; import { useAuthStore } from "@/store/authStore";
import { useRouter } from "expo-router"; import { useRouter } from "expo-router";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
// import { SafeAreaView } from "react-native-safe-area-context";
import { SafeAreaView } from "react-native"; import { SafeAreaView } from "react-native";
export default function Home() { export default function Home() {
const token = useAuthStore((state) => state.token); const token = useAuthStore((state) => state.token);
const router = useRouter(); const router = useRouter();
const [isReady, setIsReady] = useState(false); const [isReady, setIsReady] = useState(false);
const fetchNotices = useNoticesStore((state) => state.fetchNotices); const fetchNotices = useNoticesStore((state) => state.fetchNotices);
useEffect(() => { useEffect(() => {
setIsReady(true); setIsReady(true);
@@ -27,36 +26,41 @@ const token = useAuthStore((state) => state.token);
} }
}, [isReady, token, router]); }, [isReady, token, router]);
useEffect(() => { useEffect(() => {
if (token) { if (token) {
fetchNotices(); fetchNotices();
} }
}, [token, fetchNotices]); }, [token, fetchNotices]);
const notices = useNoticesStore((state) => state.notices); const notices = useNoticesStore((state) => state.notices);
// console.log("Notices:", notices); // console.log("Notices:", notices);
const latestNotices = [...notices] const latestNotices = [...notices]
.sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate)) .sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate))
.slice(0, 6); .slice(0, 6);
const recomendedNotices = [...notices] const recomendedNotices = [...notices]
.sort(() => Math.random() - 0.5) .sort(() => Math.random() - 0.5)
.slice(0, 6); .slice(0, 6);
return ( return (
<SafeAreaView className="flex-1 m-2"> <SafeAreaView className="flex-1 m-2">
{/* <View> */} {/* <View> */}
<SearchSection/> <SearchSection />
<ScrollView showsVerticalScrollIndicator={false} > <ScrollView showsVerticalScrollIndicator={false}>
<CategorySection title="Polecane kategorie" notices={notices} /> <CategorySection title="Polecane kategorie" notices={notices} />
<NoticeSection title="Najnowsze ogłoszenia" notices={latestNotices} ctaLink="/notices?sort=latest"/> <NoticeSection
title="Najnowsze ogłoszenia"
notices={latestNotices}
ctaLink="/notices?sort=latest"
/>
<UserSection title="Popularni sprzedawcy" notices={notices} /> <UserSection title="Popularni sprzedawcy" notices={notices} />
<NoticeSection title="Proponowane ogłoszenia" notices={recomendedNotices} ctaLink="/notices"/> <NoticeSection
</ScrollView> title="Proponowane ogłoszenia"
{/* </View> */} notices={recomendedNotices}
</SafeAreaView> ctaLink="/notices"
/>
</ScrollView>
{/* </View> */}
</SafeAreaView>
); );
} }

View File

@@ -1,32 +1,25 @@
import { View, FlatList} from 'react-native'; import { View, FlatList } from "react-native";
import { useEffect, useState } from 'react' import { useEffect, useState } from "react";
import { useAuthStore } from "@/store/authStore"; import { useAuthStore } from "@/store/authStore";
import { Heading } from '@/components/ui/heading'; import { Heading } from "@/components/ui/heading";
import { Text } from '@/components/ui/text'; import { Text } from "@/components/ui/text";
import { Link } from 'expo-router'; import { Link } from "expo-router";
import { Pressable } from '@/components/ui/pressable'; import { Pressable } from "@/components/ui/pressable";
// import axios from 'axios'; import { listCategories } from "@/api/categories";
import {listCategories} from "@/api/categories";
export function CategorySection({ notices, title }) {
export function CategorySection({notices, title}) {
const token = useAuthStore((state) => state.token);
const [categoryMap, setCategoryMap] = useState({}); const [categoryMap, setCategoryMap] = useState({});
useEffect(() => { useEffect(() => {
if(token){
const fetchCategories = async () => { const fetchCategories = async () => {
let data = await listCategories(); let data = await listCategories();
if (Array.isArray(data)) { if (Array.isArray(data)) {
setCategoryMap(data); setCategoryMap(data);
} }
} };
fetchCategories(); fetchCategories();
} });
}, [token]);
const categories = Array.from( const categories = Array.from(
new Set(notices.map((notice) => notice.category)) new Set(notices.map((notice) => notice.category))
@@ -35,13 +28,11 @@ export function CategorySection({notices, title}) {
const getCount = (category) => const getCount = (category) =>
notices.filter((notice) => notice.category === category).length; notices.filter((notice) => notice.category === category).length;
console.log("CategoryMap:", categoryMap); if (!categoryMap || Object.keys(categoryMap).length === 0) {
return null;
if(!categoryMap) {
return null;
} }
return ( return (
<View className="mb-6"> <View className="mb-6">
<Heading className="text-2xl font-bold mb-4 mt-4">{title}</Heading> <Heading className="text-2xl font-bold mb-4 mt-4">{title}</Heading>
<FlatList <FlatList
@@ -54,16 +45,15 @@ return (
const categoryObj = categoryMap.find((cat) => cat.value === item); const categoryObj = categoryMap.find((cat) => cat.value === item);
return ( return (
<Link href={`/notices?category=${item}`} asChild> <Link href={`/notices?category=${item}`} asChild>
<Pressable className="bg-gray-200 p-4 rounded-lg mr-2"> <Pressable className="bg-gray-200 p-4 rounded-lg mr-2">
<Text> <Text>
{categoryObj ? categoryObj.label : item} ({getCount(item)}) {categoryObj ? categoryObj.label : item} ({getCount(item)})
</Text> </Text>
</Pressable> </Pressable>
</Link> </Link>
); );
}} }}
/> />
</View> </View>
); );
}
}

View File

@@ -1,27 +1,27 @@
import { View} from 'react-native'; import { View } from "react-native";
import { useEffect, useState } from 'react' import { useEffect, useState } from "react";
import { Heading } from '@/components/ui/heading'; import { Heading } from "@/components/ui/heading";
import { FlatList } from 'react-native'; import { FlatList } from "react-native";
import axios from 'axios'; import axios from "axios";
import UserBlock from '@/components/UserBlock'; import UserBlock from "@/components/UserBlock";
import {useAuthStore} from "@/store/authStore"; import { useAuthStore } from "@/store/authStore";
export function UserSection({ notices, title }) {
export function UserSection({notices, title}) { const token = useAuthStore((state) => state.token);
const token = useAuthStore((state) => state.token); const headers = token ? { Authorization: `Bearer ${token}` } : {};
const headers = token ? { 'Authorization': `Bearer ${token}` } : {}; const [users, setUsers] = useState([]);
const [users, setUsers] = useState([]);
useEffect(() => { useEffect(() => {
if (token){ if (token) {
axios.get('https://testowe.zikor.pl/api/v1/clients/get/all', { headers }) axios
.then(res => setUsers(res.data)) .get("https://hopp.zikor.pl/api/v1/clients/get/all", { headers })
.catch(() => setUsers([])); .then((res) => setUsers(res.data))
.catch(() => setUsers([]));
} }
}, [token]); }, [token]);
const usersWithNoticeCount = users.map(user => { const usersWithNoticeCount = users.map((user) => {
const count = notices.filter(n => n.clientId === user.id).length; const count = notices.filter((n) => n.clientId === user.id).length;
return { ...user, noticeCount: count }; return { ...user, noticeCount: count };
}); });
@@ -29,7 +29,7 @@ export function UserSection({notices, title}) {
.sort((a, b) => b.noticeCount - a.noticeCount) .sort((a, b) => b.noticeCount - a.noticeCount)
.slice(0, 5); .slice(0, 5);
return ( return (
<View className="mb-6"> <View className="mb-6">
<Heading className="text-2xl font-bold mb-4 mt-4">{title}</Heading> <Heading className="text-2xl font-bold mb-4 mt-4">{title}</Heading>
<FlatList <FlatList
@@ -38,12 +38,9 @@ return (
showsHorizontalScrollIndicator={false} showsHorizontalScrollIndicator={false}
contentContainerStyle={{ paddingHorizontal: 8, gap: 12 }} contentContainerStyle={{ paddingHorizontal: 8, gap: 12 }}
renderItem={({ item }) => { renderItem={({ item }) => {
return ( return <UserBlock user={item} />;
<UserBlock user={item} />
);
}} }}
/> />
</View> </View>
); );
}
}

View File

@@ -1,110 +1,135 @@
import {create} from "zustand"; import { create } from "zustand";
import {createJSONStorage, persist} from "zustand/middleware"; import { createJSONStorage, persist } from "zustand/middleware";
import AsyncStorage from "@react-native-async-storage/async-storage"; import AsyncStorage from "@react-native-async-storage/async-storage";
import axios from "axios"; import axios from "axios";
const API_URL = "https://testowe.zikor.pl/api/v1"; const API_URL = "https://hopp.zikor.pl/api/v1";
export const useAuthStore = create( export const useAuthStore = create(
persist( persist(
(set) => ({ (set, get) => {
user: null, if (!axios.interceptors.response.handlers.length) {
token: null, axios.interceptors.response.use(
isLoading: false, (response) => response,
error: null, (error) => {
if (
(error.response && error.response.status === 401) ||
error.response.status === 403
) {
set({ user: null, token: null, isLoading: false });
delete axios.defaults.headers.common["Authorization"];
}
return Promise.reject(error);
}
);
}
signIn: async (email, password) => { return {
set({isLoading: true, error: null}); user: null,
try { token: null,
const response = await axios.post(`${API_URL}/auth/login`, { isLoading: false,
email, error: null,
password
});
const user = response.data.user; signIn: async (email, password) => {
const token = response.data.token; set({ isLoading: true, error: null });
set({user, token, isLoading: false}); try {
} catch (error) { const response = await axios.post(`${API_URL}/auth/login`, {
set({error: error.response?.data?.message || error.message, isLoading: false}); email,
throw error; password,
} });
},
signUp: async (userData) => { const user = response.data.user;
set({isLoading: true, error: null}); const token = response.data.token;
try { set({ user, token, isLoading: false });
console.log(userData); axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) {
set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
const response = await axios.post(`${API_URL}/auth/register`, userData, { signUp: async (userData) => {
headers: {'Content-Type': 'application/json'} set({ isLoading: true, error: null });
}); try {
const response = await axios.post(
`${API_URL}/auth/register`,
userData,
{
headers: { "Content-Type": "application/json" },
}
);
console.log(response.data); const user = response.data.user;
const token = response.data.token;
set({ user, token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
return user;
} catch (error) {
set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
const user = response.data.user; signInWithGoogle: async (googleToken) => {
const token = response.data.token; set({ isLoading: true, error: null });
set({user, token, isLoading: false}); try {
const response = await axios.post(`${API_URL}/auth/google`, {
token: googleToken,
});
return user; const { user, token } = response.data;
} catch (error) { set({ user, token, isLoading: false });
set({error: error.response?.data?.message || error.message, isLoading: false}); axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
throw error; return user;
} } catch (error) {
}, set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
signInWithGoogle: async (googleToken) => { signOut: async () => {
set({isLoading: true, error: null}); try {
try { const { token } = get();
const response = await axios.post(`${API_URL}/auth/google`, {token: googleToken}); const headers = token ? { Authorization: `Bearer ${token}` } : {};
await axios.post(`${API_URL}/auth/logout`, {}, { headers });
} catch (error) {
// console.error("Logout error:", error);
} finally {
delete axios.defaults.headers.common["Authorization"];
set({ user: null, token: null, isLoading: false });
}
},
const {user, token} = response.data; checkAuth: async () => {
set({user, token, isLoading: false}); const { token } = get();
if (!token) return null;
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; set({ isLoading: true });
try {
return user; axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) { const response = await axios.get(`${API_URL}/auth/me`);
set({error: error.response?.data?.message || error.message, isLoading: false}); set({ user: response.data, isLoading: false });
throw error; return response.data;
} } catch (error) {
}, delete axios.defaults.headers.common["Authorization"];
set({ user: null, token: null, isLoading: false });
signOut: async () => { return null;
try { }
const {token} = useAuthStore.getState(); },
const headers = token ? { 'Authorization': `Bearer ${token}` } : {}; };
// Можно отправить запрос на бэкенд для инвалидации токена },
await axios.post(`${API_URL}/auth/logout`, {}, { headers }); {
} catch (error) { name: "auth-storage",
console.error("Logout error:", error); storage: createJSONStorage(() => AsyncStorage),
} finally { }
delete axios.defaults.headers.common["Authorization"]; )
set({user: null, token: null}); );
}
},
checkAuth: async () => {
const {token} = useAuthStore.getState();
if (!token) return null;
set({isLoading: true});
try {
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
const response = await axios.get(`${API_URL}/auth/me`);
set({user: response.data, isLoading: false});
return response.data;
} catch (error) {
delete axios.defaults.headers.common["Authorization"];
set({user: null, token: null, isLoading: false});
return null;
}
},
}),
{
name: "auth-storage",
storage: createJSONStorage(() => AsyncStorage),
}
)
);