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,12 +1,11 @@
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 });

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(
`Nie udało się pobrać danych użytkownika o ID ${userId}.`,
err.response.status
);
throw err; throw err;
} }
} }

View File

@@ -1,21 +1,21 @@
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());
@@ -77,8 +77,8 @@ export async function getAllImagesByNoticeId(noticeId) {
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}`);
@@ -98,12 +98,12 @@ export const uploadImage = async (noticeId, 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,
@@ -115,15 +115,19 @@ export const uploadImage = async (noticeId, imageUri) => {
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(
"Error uploading image:",
error.response.data,
error.response.status
);
throw error; throw error;
} }
} };

View File

@@ -2,16 +2,20 @@ 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}`,
}); {},
{
headers,
}
);
return response.data; return response.data;
} catch (error) { } catch (error) {
console.error("Error toggling wishlist item:", error); console.error("Error toggling wishlist item:", error);
@@ -21,7 +25,7 @@ export async function toggleNoticeStatus(noticeId) {
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 });

View File

@@ -1,7 +1,13 @@
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() {
const token = useAuthStore((state) => state.token);
if (!token) {
return <Redirect href="/login" />;
}
return ( return (
<Tabs <Tabs
screenOptions={{ screenOptions={{

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,14 +1,13 @@
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() {
@@ -27,14 +26,12 @@ 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);
@@ -45,16 +42,23 @@ const token = useAuthStore((state) => state.token);
.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
title="Proponowane ogłoszenia"
notices={recomendedNotices}
ctaLink="/notices"
/>
</ScrollView> </ScrollView>
{/* </View> */} {/* </View> */}
</SafeAreaView> </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,9 +28,7 @@ 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) {
if(!categoryMap) {
return null; return null;
} }
@@ -65,5 +56,4 @@ return (
/> />
</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 })
.then((res) => setUsers(res.data))
.catch(() => setUsers([])); .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 };
}); });
@@ -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

@@ -3,11 +3,28 @@ 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) => {
if (!axios.interceptors.response.handlers.length) {
axios.interceptors.response.use(
(response) => response,
(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);
}
);
}
return {
user: null, user: null,
token: null, token: null,
isLoading: false, isLoading: false,
@@ -18,14 +35,18 @@ export const useAuthStore = create(
try { try {
const response = await axios.post(`${API_URL}/auth/login`, { const response = await axios.post(`${API_URL}/auth/login`, {
email, email,
password password,
}); });
const user = response.data.user; const user = response.data.user;
const token = response.data.token; const token = response.data.token;
set({ user, token, isLoading: false }); set({ user, token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) { } catch (error) {
set({error: error.response?.data?.message || error.message, isLoading: false}); set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error; throw error;
} }
}, },
@@ -33,21 +54,24 @@ export const useAuthStore = create(
signUp: async (userData) => { signUp: async (userData) => {
set({ isLoading: true, error: null }); set({ isLoading: true, error: null });
try { try {
console.log(userData); const response = await axios.post(
`${API_URL}/auth/register`,
const response = await axios.post(`${API_URL}/auth/register`, userData, { userData,
headers: {'Content-Type': 'application/json'} {
}); headers: { "Content-Type": "application/json" },
}
console.log(response.data); );
const user = response.data.user; const user = response.data.user;
const token = response.data.token; const token = response.data.token;
set({ user, token, isLoading: false }); set({ user, token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
return user; return user;
} catch (error) { } catch (error) {
set({error: error.response?.data?.message || error.message, isLoading: false}); set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error; throw error;
} }
}, },
@@ -55,44 +79,44 @@ export const useAuthStore = create(
signInWithGoogle: async (googleToken) => { signInWithGoogle: async (googleToken) => {
set({ isLoading: true, error: null }); set({ isLoading: true, error: null });
try { try {
const response = await axios.post(`${API_URL}/auth/google`, {token: googleToken}); const response = await axios.post(`${API_URL}/auth/google`, {
token: googleToken,
});
const { user, token } = response.data; const { user, token } = response.data;
set({ user, token, isLoading: false }); set({ user, token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
return user; return user;
} catch (error) { } catch (error) {
set({error: error.response?.data?.message || error.message, isLoading: false}); set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error; throw error;
} }
}, },
signOut: async () => { signOut: async () => {
try { try {
const {token} = useAuthStore.getState(); const { token } = get();
const headers = token ? { 'Authorization': `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
// Можно отправить запрос на бэкенд для инвалидации токена
await axios.post(`${API_URL}/auth/logout`, {}, { headers }); await axios.post(`${API_URL}/auth/logout`, {}, { headers });
} catch (error) { } catch (error) {
console.error("Logout error:", error); // console.error("Logout error:", error);
} finally { } finally {
delete axios.defaults.headers.common["Authorization"]; delete axios.defaults.headers.common["Authorization"];
set({user: null, token: null}); set({ user: null, token: null, isLoading: false });
} }
}, },
checkAuth: async () => { checkAuth: async () => {
const {token} = useAuthStore.getState(); const { token } = get();
if (!token) return null; if (!token) return null;
set({ isLoading: true }); set({ isLoading: true });
try { try {
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
const response = await axios.get(`${API_URL}/auth/me`); const response = await axios.get(`${API_URL}/auth/me`);
set({ user: response.data, isLoading: false }); set({ user: response.data, isLoading: false });
return response.data; return response.data;
} catch (error) { } catch (error) {
@@ -101,7 +125,8 @@ export const useAuthStore = create(
return null; return null;
} }
}, },
}), };
},
{ {
name: "auth-storage", name: "auth-storage",
storage: createJSONStorage(() => AsyncStorage), storage: createJSONStorage(() => AsyncStorage),