Ekran logowania i rejestracja działa! Tylko wewnętrzne logowanie, bez google

This commit is contained in:
2025-06-04 15:41:40 +02:00
parent 9962dc1e55
commit 1862b6b79e
8 changed files with 418 additions and 73 deletions

View File

@@ -0,0 +1,108 @@
import {create} from "zustand";
import {createJSONStorage, persist} from "zustand/middleware";
import AsyncStorage from "@react-native-async-storage/async-storage";
import axios from "axios";
const API_URL = "http://10.0.2.2:8080/api/v1";
export const useAuthStore = create(
persist(
(set) => ({
user: null,
token: null,
isLoading: false,
error: null,
signIn: async (email, password) => {
set({isLoading: true, error: null});
try {
const response = await axios.post(`${API_URL}/auth/login`, {
email,
password
});
const user = response.data.user;
const token = response.data.token;
set({user, token, isLoading: false});
} catch (error) {
set({error: error.response?.data?.message || error.message, isLoading: false});
throw error;
}
},
signUp: async (userData) => {
set({isLoading: true, error: null});
try {
console.log(userData);
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});
return user;
} catch (error) {
set({error: error.response?.data?.message || error.message, isLoading: false});
throw error;
}
},
signInWithGoogle: async (googleToken) => {
set({isLoading: true, error: null});
try {
const response = await axios.post(`${API_URL}/auth/google`, {token: googleToken});
const {user, token} = response.data;
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;
}
},
signOut: async () => {
try {
// Можно отправить запрос на бэкенд для инвалидации токена
await axios.post(`${API_URL}/auth/logout`);
} catch (error) {
console.error("Logout error:", error);
} 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),
}
)
);