Got some new errors. but close to having stuff

This commit is contained in:
2024-10-09 16:55:16 -05:00
parent 8128194488
commit 6e01a31e76
12 changed files with 442 additions and 17 deletions

View File

@ -0,0 +1,102 @@
import React from 'react';
import * as AppleAuthentication from 'expo-apple-authentication';
import { StyleSheet, Alert } from 'react-native';
import { ThemedView } from '@/components/ThemedView';
import { useColorScheme } from '@/hooks/useColorScheme';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
import { saveUserData } from '@/components/services/securestorage/UserData';
type UserData = {
appleId: string;
appleEmail: string;
fullName: string;
pushToken: string;
};
export default function SignInScreen({ onSignIn }: { onSignIn: () => void }) {
const scheme = useColorScheme() ?? 'light';
const handleAppleSignIn = async () => {
try {
const credential = await AppleAuthentication.signInAsync({
requestedScopes: [
AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
AppleAuthentication.AppleAuthenticationScope.EMAIL,
],
});
const projectId = Constants.expoConfig?.extra?.eas?.projectId;
if (!projectId) {
throw new Error('Project ID not found');
}
const pushToken = await Notifications.getExpoPushTokenAsync({
projectId: projectId
});
console.log(credential.user, credential.email, credential.fullName, credential.fullName?.givenName, credential.fullName?.familyName, pushToken);
const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/users/createUser`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
},
body: JSON.stringify({
appleId: credential.user,
appleEmail: credential.email,
fullName: `${credential.fullName?.givenName} ${credential.fullName?.familyName}`,
pushToken: pushToken.data,
}),
});
if (!response.ok) {
throw new Error('Failed to create user');
}
const userData = await response.json();
await saveUserData(userData);
onSignIn();
} catch (error) {
if (error.code === 'ERR_REQUEST_CANCELLED') {
// Handle when user cancels sign in
console.error('User canceled sign in', error);
Alert.alert('An error occurred', 'User canceled sign in');
} else {
console.error('An unknown error occurred', error);
Alert.alert('Unknown error', 'An unknown error occurred');
}
}
};
return (
<ThemedView style={styles.container}>
<AppleAuthentication.AppleAuthenticationButton
buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN}
buttonStyle={(scheme === 'light') ?
AppleAuthentication.AppleAuthenticationButtonStyle.BLACK :
AppleAuthentication.AppleAuthenticationButtonStyle.WHITE
}
cornerRadius={5}
style={styles.button}
onPress={handleAppleSignIn}
/>
</ThemedView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
button: {
width: 200,
height: 44,
},
});

View File

@ -0,0 +1,76 @@
import React, { useState, useEffect, useRef } from 'react';
import { Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
async function registerForPushNotificationsAsync() {
let token;
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
if (Device.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return;
}
const projectId = Constants.expoConfig?.extra?.eas?.projectId;
if (!projectId) {
alert('Project ID not found');
return;
}
token = (await Notifications.getExpoPushTokenAsync({ projectId })).data;
} else {
alert('Must use physical device for Push Notifications');
}
return token;
}
export function PushNotificationManager({ children }: { children: React.ReactNode }) {
const [expoPushToken, setExpoPushToken] = useState<string | undefined>('');
const [notification, setNotification] = useState<Notifications.Notification | undefined>(undefined);
const notificationListener = useRef<Notifications.Subscription>();
const responseListener = useRef<Notifications.Subscription>();
useEffect(() => {
registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
setNotification(notification);
});
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
console.log(response);
// Handle notification response here
});
return () => {
Notifications.removeNotificationSubscription(notificationListener.current!);
Notifications.removeNotificationSubscription(responseListener.current!);
};
}, []);
return <>{children}</>;
}

View File

@ -0,0 +1,26 @@
import * as SecureStore from 'expo-secure-store';
type UserData = {
appleId: string;
appleEmail: string;
fullName: string;
pushToken: string;
};
export const saveUserData = async (userData: any) => {
try {
await SecureStore.setItemAsync('userData', JSON.stringify(userData));
} catch (error) {
console.error('Error saving user data:', error);
}
};
export const getUserData = async () => {
try {
const userData = await SecureStore.getItemAsync('userData');
return userData ? JSON.parse(userData) : null;
} catch (error) {
console.error('Error getting user data:', error);
return null;
}
};