164 lines
4.9 KiB
TypeScript
164 lines
4.9 KiB
TypeScript
import {Account, Avatars, Client, Databases, OAuthProvider, Query} from "react-native-appwrite";
|
|
import * as Linking from "expo-linking"
|
|
import {openAuthSessionAsync} from "expo-web-browser";
|
|
import {attribute} from "postcss-selector-parser";
|
|
import limit from "ajv-formats/src/limit";
|
|
|
|
// Add this debug log
|
|
// console.log('Environment Variables:', {
|
|
// endpoint: process.env.EXPO_PUBLIC_APPWRITE_ENDPOINT,
|
|
// projectId: process.env.EXPO_PUBLIC_APPWRITE_PROJECT_ID,
|
|
// });
|
|
|
|
if (!process.env.EXPO_PUBLIC_APPWRITE_ENDPOINT || !process.env.EXPO_PUBLIC_APPWRITE_PROJECT_ID) {
|
|
throw new Error('Missing required Appwrite environment variables');
|
|
}
|
|
|
|
export const config = {
|
|
platform: 'com.placebomk.mobilemk',
|
|
endpoint: process.env.EXPO_PUBLIC_APPWRITE_ENDPOINT,
|
|
projectId: process.env.EXPO_PUBLIC_APPWRITE_PROJECT_ID,
|
|
databaseId: process.env.EXPO_PUBLIC_APPWRITE_DATABASE_ID,
|
|
usersId: process.env.EXPO_PUBLIC_APPWRITE_USERS_COLLECTION_ID,
|
|
// oglasuvacId: process.env.EXPO_PUBLIC_APPWRITE_OGLASUVAC_COLLECTION_ID,
|
|
// galleryId: process.env.EXPO_PUBLIC_APPWRITE_GALERIES_COLLECTION_ID,
|
|
// reviewId: process.env.EXPO_PUBLIC_APPWRITE_REVIEWS_COLLECTION_ID,
|
|
// vehicleId: process.env.EXPO_PUBLIC_APPWRITE_VEHICLE_COLLECTION_ID,
|
|
}
|
|
|
|
export const client = new Client();
|
|
|
|
client
|
|
.setEndpoint(config.endpoint!)
|
|
.setProject(config.projectId!)
|
|
.setPlatform(config.platform!)
|
|
|
|
export const avatar = new Avatars(client);
|
|
export const account = new Account(client);
|
|
export const databases = new Databases(client);
|
|
|
|
export async function login (){
|
|
// Your code here to authenticate the user and return their JWT token.
|
|
try {
|
|
const redirectUri = Linking.createURL('/');
|
|
const response = await account.createOAuth2Token(OAuthProvider.Google, redirectUri);
|
|
|
|
if(!response) throw new Error('failed to login');
|
|
|
|
const browserResult = await openAuthSessionAsync(
|
|
response.toString(),
|
|
redirectUri
|
|
)
|
|
|
|
if (!browserResult.type || browserResult.type !== 'success') {
|
|
throw new Error('failed to log in');
|
|
}
|
|
|
|
const url = new URL(browserResult.url);
|
|
|
|
const secret = url.searchParams.get('secret')?.toString();
|
|
const userId = url.searchParams.get('userId')?.toString();
|
|
|
|
if (!secret ||!userId) {
|
|
throw new Error('failed to authenticate user');
|
|
}
|
|
|
|
const session = await account.createSession(userId, secret);
|
|
if (!session) throw new Error('failed to create session');
|
|
return true;
|
|
}
|
|
catch (error) {
|
|
console.error("Failed to authenticate user:", error);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export async function getCurrentUser() {
|
|
try {
|
|
const response = await account.get();
|
|
if(response.$id){
|
|
const userAvatar = avatar.getInitials(response.name)
|
|
return {
|
|
...response,
|
|
avatar: userAvatar.toString(),
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error(error)
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export async function logOut(): Promise<boolean> {
|
|
try {
|
|
await account.deleteSession('current');
|
|
return true;
|
|
} catch (error) {
|
|
console.error("Failed to log out user:", error);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// export async function getData() {
|
|
// try {
|
|
// const result =await databases.listDocuments(
|
|
// config.databaseId!,
|
|
// config.vehicleId!,
|
|
// [Query.orderAsc(`$createdAt`), Query.limit(5)],
|
|
|
|
// )
|
|
// console.log(result.documents)
|
|
// return result.documents;
|
|
// }
|
|
// catch (error) {
|
|
// console.error("Failed to fetch data:", error);
|
|
// return [];
|
|
// }
|
|
// }
|
|
|
|
// export async function getVehicles({filter, query, limit}: {
|
|
// filter?: string;
|
|
// query?: string;
|
|
// limit?: number;
|
|
// }){
|
|
|
|
// }
|
|
|
|
export async function saveUserToDatabase(userData: {
|
|
userId: string;
|
|
name: string;
|
|
email: string;
|
|
avatar: string;
|
|
}) {
|
|
try {
|
|
// First check if user already exists
|
|
try {
|
|
await databases.getDocument(
|
|
config.databaseId!,
|
|
config.usersId!,
|
|
userData.userId
|
|
);
|
|
console.log('User already exists in database');
|
|
return null;
|
|
} catch (error) {
|
|
// User doesn't exist, proceed with creation
|
|
const result = await databases.createDocument(
|
|
config.databaseId!,
|
|
config.usersId!,
|
|
userData.userId,
|
|
{
|
|
name: userData.name,
|
|
email: userData.email,
|
|
avatar: userData.avatar,
|
|
createdAt: new Date().toISOString(),
|
|
}
|
|
);
|
|
console.log('User created successfully');
|
|
return result;
|
|
}
|
|
} catch (error) {
|
|
console.error("Failed to save user data:", error);
|
|
return null;
|
|
}
|
|
}
|