Merge remote-tracking branch 'origin/authentication' into integrateWithAuth

This commit is contained in:
Patryk
2025-06-08 09:20:08 +02:00
6 changed files with 236 additions and 150 deletions

View File

@@ -4,23 +4,19 @@ import { useAuthStore } from "@/store/authStore";
const API_URL = "https://hopp.zikor.pl/api/v1"; const API_URL = "https://hopp.zikor.pl/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); const response = await fetch(`${API_URL}/notices/get/all`, {
headers: headers
const response = await fetch(`${API_URL}/notices/get/all`, { });
headers: headers, const data = await response.json();
}); if (!response.ok) {
// console.log(response);r throw new Error(response.toString());
const data = await response.json(); }
if (!response.ok) { return data;
throw new Error(response.toString());
}
return data;
} }
export async function getNoticeById(noticeId) { export async function getNoticeById(noticeId) {
@@ -62,27 +58,32 @@ export async function getImageByNoticeId(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}`); return imageUrl;
} catch (err) {
return imageUrl; console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`);
} catch (err) { imageUrl = "https://http.cat/404.jpg";
console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`); return imageUrl;
imageUrl = "https://http.cat/404.jpg"; }
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( return listResponse.data.map(imageName =>
(imageName) => `${API_URL}/images/get/${imageName}` `${API_URL}/images/get/${imageName}`
); );
}
// console.log(`Pobrano ${imageUrls.length} zdjęć dla ogłoszenia o id: ${noticeId}`); return ["https://http.cat/404.jpg"];
return imageUrls; } catch (err) {
if(err.response.status === 404) {
console.info(`Ogłoszenie o id: ${noticeId} nie posiada zdjęć.`);
return ["https://http.cat/404.jpg"];
}
console.warn(`Nie udało się pobrać 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}`); // console.log(`Brak zdjęć dla ogłoszenia o id: ${noticeId}`);
@@ -94,9 +95,7 @@ export async function getAllImagesByNoticeId(noticeId) {
} }
export const uploadImage = async (noticeId, imageUri) => { export const uploadImage = async (noticeId, imageUri) => {
console.log(imageUri); const formData = new FormData();
const formData = new FormData();
const filename = imageUri.split("/").pop(); const filename = imageUri.split("/").pop();

View File

@@ -2,7 +2,7 @@
"expo": { "expo": {
"name": "ArtisanConnect", "name": "ArtisanConnect",
"slug": "ArtisanConnect", "slug": "ArtisanConnect",
"scheme": "Artisanconnect", "scheme": "com.hamx.artisanconnect",
"version": "1.0.0", "version": "1.0.0",
"orientation": "portrait", "orientation": "portrait",
"icon": "./assets/icon.png", "icon": "./assets/icon.png",
@@ -14,13 +14,19 @@
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"
}, },
"ios": { "ios": {
"supportsTablet": true "supportsTablet": true,
"bundleIdentifier": "com.hamx.artisanconnect"
}, },
"android": { "android": {
"adaptiveIcon": { "adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png", "foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff" "backgroundColor": "#ffffff"
} },
"permissions": [
"android.permission.RECORD_AUDIO",
"android.permission.CAMERA"
],
"package": "com.hamx.artisanconnect"
}, },
"web": { "web": {
"favicon": "./assets/favicon.png" "favicon": "./assets/favicon.png"
@@ -40,6 +46,12 @@
} }
], ],
"expo-web-browser" "expo-web-browser"
] ],
"extra": {
"router": {},
"eas": {
"projectId": "7a0d8bc8-938f-4d2a-babb-945faee13429"
}
}
} }
} }

View File

@@ -1,5 +1,5 @@
import React, {useState} from 'react'; import React, {useEffect, useState} from 'react';
import {StyleSheet, ActivityIndicator, SafeAreaView, View} from 'react-native'; import {StyleSheet, ActivityIndicator, SafeAreaView, View, Platform} from 'react-native';
import {useAuthStore} from '@/store/authStore'; import {useAuthStore} from '@/store/authStore';
import {useRouter, Link} from 'expo-router'; import {useRouter, Link} from 'expo-router';
@@ -15,12 +15,37 @@ import {ArrowRightIcon} from "@/components/ui/icon"
import {Divider} from '@/components/ui/divider'; import {Divider} from '@/components/ui/divider';
import {Ionicons} from "@expo/vector-icons"; import {Ionicons} from "@expo/vector-icons";
import * as WebBrowser from 'expo-web-browser';
import * as Google from "expo-auth-session/providers/google";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {makeRedirectUri} from "expo-auth-session";
import Constants from 'expo-constants';
WebBrowser.maybeCompleteAuthSession();
// client_id ios 936418008320-ohefdfcebd41f6oa2o8phh1mgj9s49sl.apps.googleusercontent.com
// android 936418008320-d8dfjph5e4r28fcm1rbdfbh5phmbg03d.apps.googleusercontent.com
export default function Login() { export default function Login() {
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const {signIn, isLoading} = useAuthStore(); const {signIn, isLoading, signInWithGoogle} = useAuthStore();
const router = useRouter(); const router = useRouter();
const [request, response, promptAsync] = Google.useAuthRequest({
androidClientId: "936418008320-d8dfjph5e4r28fcm1rbdfbh5phmbg03d.apps.googleusercontent.com",
iosClientId: "936418008320-ohefdfcebd41f6oa2o8phh1mgj9s49sl.apps.googleusercontent.com",
webClientId: "936418008320-btdngtlfnjac1p67guje72m9el5q59a7.apps.googleusercontent.com",
redirectUri:
Platform.OS === 'android'
? makeRedirectUri({
scheme: Constants.expoConfig.android.package,
path: '/',
})
: undefined,
})
const handleInternalLogin = async () => { const handleInternalLogin = async () => {
if (!email || !password) { if (!email || !password) {
alert('Proszę wprowadzić email i hasło.'); alert('Proszę wprowadzić email i hasło.');
@@ -36,6 +61,47 @@ export default function Login() {
} }
} }
useEffect(() => {
handleGoogleLogin();
}, [response]);
const handleGoogleLogin = async () => {
// const user = await AsyncStorage.getItem("@user");
let user = null;
if (!user) {
if(response.type === "success") {
user = await getUserInfo(response.authentication.accessToken)
await signInWithGoogle(response.authentication.accessToken);
alert(`Zalogowano jako ${user.email}`);
}
} else {
console.info("Pobrano użytkownika z AsyncStorage:", JSON.parse(user));
alert(`Zalogowano jako ${user.email}`);
}
};
const getUserInfo = async (token) => {
if(!token) {
return
}
try {
const response = await fetch("https://www.googleapis.com/userinfo/v2/me",
{
headers: {
Authorization: `Bearer ${token}`
},
}
);
const user = await response.json();
await AsyncStorage.setItem("@user", JSON.stringify(user));
return user;
} catch (error) {
console.error("Błąd podczas pobierania informacji o użytkowniku:", error);
throw error;
}
}
if (isLoading) { if (isLoading) {
return ( return (
<View style={styles.container}> <View style={styles.container}>
@@ -82,7 +148,7 @@ export default function Login() {
</Text> </Text>
<Divider flex={1}/> <Divider flex={1}/>
</HStack> </HStack>
<Button size="sm"> <Button size="sm" onPress={() => promptAsync()}>
<Ionicons name="logo-google" color="#fff"/> <Ionicons name="logo-google" color="#fff"/>
</Button> </Button>
</Box> </Box>

21
ArtisanConnect/eas.json Normal file
View File

@@ -0,0 +1,21 @@
{
"cli": {
"version": ">= 16.8.0",
"appVersionSource": "remote"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal"
},
"preview": {
"distribution": "internal"
},
"production": {
"autoIncrement": true
}
},
"submit": {
"production": {}
}
}

View File

@@ -39,7 +39,7 @@
"expo": "^53.0.0", "expo": "^53.0.0",
"expo-auth-session": "~6.1.5", "expo-auth-session": "~6.1.5",
"expo-camera": "~16.1.6", "expo-camera": "~16.1.6",
"expo-constants": "~17.1.5", "expo-constants": "~17.1.6",
"expo-image-picker": "~16.1.4", "expo-image-picker": "~16.1.4",
"expo-linking": "~7.1.4", "expo-linking": "~7.1.4",
"expo-router": "~5.0.5", "expo-router": "~5.0.5",
@@ -57,11 +57,12 @@
"react-native-keyboard-aware-scroll-view": "^0.9.5", "react-native-keyboard-aware-scroll-view": "^0.9.5",
"react-native-reanimated": "~3.17.4", "react-native-reanimated": "~3.17.4",
"react-native-safe-area-context": "5.4.0", "react-native-safe-area-context": "5.4.0",
"react-native-screens": "~4.10.0", "react-native-screens": "~4.11.1",
"react-native-svg": "15.11.2", "react-native-svg": "15.11.2",
"react-native-web": "~0.20.0", "react-native-web": "~0.20.0",
"tailwindcss": "^3.4.17", "tailwindcss": "^3.4.17",
"zustand": "^5.0.3" "zustand": "^5.0.3",
"expo-crypto": "~14.1.4"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.20.0", "@babel/core": "^7.20.0",

View File

@@ -7,126 +7,113 @@ const API_URL = "https://hopp.zikor.pl/api/v1";
export const useAuthStore = create( export const useAuthStore = create(
persist( persist(
(set, get) => { (set) => ({
if (!axios.interceptors.response.handlers.length) { user_id: null,
axios.interceptors.response.use( token: null,
(response) => response, isLoading: false,
(error) => { error: null,
if (
(error.response && error.response.status === 401) || signIn: async (email, password) => {
error.response.status === 403 set({ isLoading: true, error: null });
) { try {
set({ user: null, token: null, isLoading: false }); const response = await axios.post(`${API_URL}/auth/login`, {
delete axios.defaults.headers.common["Authorization"]; email,
password,
});
const user_id = response.data.user_id;
const token = response.data.token;
set({ user_id: user_id, token: token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) {
set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
signUp: async (userData) => {
set({ isLoading: true, error: null });
try {
const response = await axios.post(
`${API_URL}/auth/register`,
userData,
{
headers: { "Content-Type": "application/json" },
} }
return Promise.reject(error); );
}
);
}
return { const user_id = response.data.user_id;
user: null, const token = response.data.token;
token: null, set({ user_id: user_id, token: token, isLoading: false });
isLoading: false,
error: null,
signIn: async (email, password) => { axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
set({ isLoading: true, error: null }); } catch (error) {
try { set({
const response = await axios.post(`${API_URL}/auth/login`, { error: error.response?.data?.message || error.message,
email, isLoading: false,
password, });
}); 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 {
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; const response = await axios.post(
} catch (error) { `${API_URL}/auth/google`,
set({ { googleToken: googleToken },
error: error.response?.data?.message || error.message, {
isLoading: false, headers: { "Content-Type": "application/json" },
}); }
throw error; );
} const user_id = response.data.user_id;
}, const token = response.data.token;
set({ user_id: user_id, token: token, isLoading: false });
signUp: async (userData) => { axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
set({ isLoading: true, error: null }); } catch (error) {
try { set({
const response = await axios.post( error: error.response?.data?.message || error.message,
`${API_URL}/auth/register`, isLoading: false,
userData, });
{ throw error;
headers: { "Content-Type": "application/json" }, }
} },
);
const user = response.data.user; signOut: async () => {
const token = response.data.token; try {
set({ user, token, isLoading: false }); await axios.post(`${API_URL}/auth/logout`);
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; } catch (error) {
return user; console.error("Logout error:", error);
} catch (error) { } finally {
set({ delete axios.defaults.headers.common["Authorization"];
error: error.response?.data?.message || error.message, set({ user_id: null, token: null });
isLoading: false, }
}); },
throw error;
}
},
signInWithGoogle: async (googleToken) => { checkAuth: async () => {
set({ isLoading: true, error: null }); const { token } = useAuthStore.getState();
try { if (!token) return null;
const response = await axios.post(`${API_URL}/auth/google`, {
token: googleToken,
});
const { user, token } = response.data; set({ isLoading: true });
set({ user, token, isLoading: false }); try {
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
return user;
} catch (error) {
set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
signOut: async () => { const response = await axios.get(`${API_URL}/auth/me`);
try {
const { token } = get();
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 });
}
},
checkAuth: async () => { set({ user_id: response.data, isLoading: false });
const { token } = get(); return response.data;
if (!token) return null; } catch (error) {
delete axios.defaults.headers.common["Authorization"];
set({ isLoading: true }); set({ user_id: null, token: null, isLoading: false });
try { return null;
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", name: "auth-storage",
storage: createJSONStorage(() => AsyncStorage), storage: createJSONStorage(() => AsyncStorage),