docs: Rework Expo React native social auth (#43017)

## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

Reworks Expo React native social to use appropriate auth methods and
restructures to use external code.

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
Chris Chinchillaandcoderabbitai[bot] authored and GitHub committed 2026-02-23 08:54:17 +01:00
1 parent f8419ef9ae
commit c0f7e7dfd1
84 files changed
+16510 -3672

No files matched your search

@@ -1,11 +1,6 @@
import { Tabs } from 'expo-router';
import React from 'react';
import { Platform } from 'react-native';
import { HapticTab } from '@/components/haptic-tab';
import { IconSymbol } from '@/components/ui/icon-symbol';
import TabBarBackground from '@/components/ui/tab-bar-background';
import { Colors } from '@/constants/colors';
import { Colors } from '@/constants/theme';
import { useColorScheme } from '@/hooks/use-color-scheme';
export default function TabLayout() {
@@ -16,28 +11,11 @@ export default function TabLayout() {
screenOptions={{
tabBarActiveTintColor: Colors[colorScheme ?? 'light'].tint,
headerShown: false,
tabBarButton: HapticTab,
tabBarBackground: TabBarBackground,
tabBarStyle: Platform.select({
ios: {
// Use a transparent background on iOS to show the blur effect
position: 'absolute',
},
default: {},
}),
}}>
<Tabs.Screen
name="index"
options={{
title: 'Home',
tabBarIcon: ({ color }) => <IconSymbol size={28} name="house.fill" color={color} />,
}}
/>
<Tabs.Screen
name="explore"
options={{
title: 'Explore',
tabBarIcon: ({ color }) => <IconSymbol size={28} name="paperplane.fill" color={color} />,
}}
/>
</Tabs>
@@ -1,110 +0,0 @@
import { Image } from 'expo-image';
import { Platform, StyleSheet } from 'react-native';
import { Collapsible } from '@/components/collapsible';
import { ExternalLink } from '@/components/external-link';
import ParallaxScrollView from '@/components/parallax-scroll-view';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { IconSymbol } from '@/components/ui/icon-symbol';
export default function TabTwoScreen() {
return (
<ParallaxScrollView
headerBackgroundColor={{ light: '#D0D0D0', dark: '#353636' }}
headerImage={
<IconSymbol
size={310}
color="#808080"
name="chevron.left.forwardslash.chevron.right"
style={styles.headerImage}
/>
}>
<ThemedView style={styles.titleContainer}>
<ThemedText type="title">Explore</ThemedText>
</ThemedView>
<ThemedText>This app includes example code to help you get started.</ThemedText>
<Collapsible title="File-based routing">
<ThemedText>
This app has two screens:{' '}
<ThemedText type="defaultSemiBold">app/(tabs)/index.tsx</ThemedText> and{' '}
<ThemedText type="defaultSemiBold">app/(tabs)/explore.tsx</ThemedText>
</ThemedText>
<ThemedText>
The layout file in <ThemedText type="defaultSemiBold">app/(tabs)/_layout.tsx</ThemedText>{' '}
sets up the tab navigator.
</ThemedText>
<ExternalLink href="https://docs.expo.dev/router/introduction">
<ThemedText type="link">Learn more</ThemedText>
</ExternalLink>
</Collapsible>
<Collapsible title="Android, iOS, and web support">
<ThemedText>
You can open this project on Android, iOS, and the web. To open the web version, press{' '}
<ThemedText type="defaultSemiBold">w</ThemedText> in the terminal running this project.
</ThemedText>
</Collapsible>
<Collapsible title="Images">
<ThemedText>
For static images, you can use the <ThemedText type="defaultSemiBold">@2x</ThemedText> and{' '}
<ThemedText type="defaultSemiBold">@3x</ThemedText> suffixes to provide files for
different screen densities
</ThemedText>
<Image source={require('@/assets/images/react-logo.png')} style={{ alignSelf: 'center' }} />
<ExternalLink href="https://reactnative.dev/docs/images">
<ThemedText type="link">Learn more</ThemedText>
</ExternalLink>
</Collapsible>
<Collapsible title="Custom fonts">
<ThemedText>
Open <ThemedText type="defaultSemiBold">app/_layout.tsx</ThemedText> to see how to load{' '}
<ThemedText style={{ fontFamily: 'SpaceMono' }}>
custom fonts such as this one.
</ThemedText>
</ThemedText>
<ExternalLink href="https://docs.expo.dev/versions/latest/sdk/font">
<ThemedText type="link">Learn more</ThemedText>
</ExternalLink>
</Collapsible>
<Collapsible title="Light and dark mode components">
<ThemedText>
This template has light and dark mode support. The{' '}
<ThemedText type="defaultSemiBold">useColorScheme()</ThemedText> hook lets you inspect
what the user&apos;s current color scheme is, and so you can adjust UI colors accordingly.
</ThemedText>
<ExternalLink href="https://docs.expo.dev/develop/user-interface/color-themes/">
<ThemedText type="link">Learn more</ThemedText>
</ExternalLink>
</Collapsible>
<Collapsible title="Animations">
<ThemedText>
This template includes an example of an animated component. The{' '}
<ThemedText type="defaultSemiBold">components/HelloWave.tsx</ThemedText> component uses
the powerful <ThemedText type="defaultSemiBold">react-native-reanimated</ThemedText>{' '}
library to create a waving hand animation.
</ThemedText>
{Platform.select({
ios: (
<ThemedText>
The <ThemedText type="defaultSemiBold">components/ParallaxScrollView.tsx</ThemedText>{' '}
component provides a parallax effect for the header image.
</ThemedText>
),
})}
</Collapsible>
</ParallaxScrollView>
);
}
const styles = StyleSheet.create({
headerImage: {
color: '#808080',
bottom: -90,
left: -35,
position: 'absolute',
},
titleContainer: {
flexDirection: 'row',
gap: 8,
},
});
@@ -1,16 +1,15 @@
import { Image } from 'expo-image';
import { StyleSheet } from 'react-native';
import { Image } from 'expo-image'
import { StyleSheet } from 'react-native'
import { HelloWave } from '@/components/hello-wave';
import ParallaxScrollView from '@/components/parallax-scroll-view';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import SignOutButton from '@/components/social-auth-buttons/sign-out-button';
import { useAuthContext } from '@/hooks/use-auth-context';
import { HelloWave } from '@/components/hello-wave'
import ParallaxScrollView from '@/components/parallax-scroll-view'
import { ThemedText } from '@/components/themed-text'
import { ThemedView } from '@/components/themed-view'
import SignOutButton from '@/components/social-auth-buttons/sign-out-button'
import { useAuthContext } from '@/hooks/use-auth-context'
export default function HomeScreen() {
const { profile } = useAuthContext();
const { profile } = useAuthContext()
return (
<ParallaxScrollView
@@ -20,7 +19,8 @@ export default function HomeScreen() {
source={require('@/assets/images/partial-react-logo.png')}
style={styles.reactLogo}
/>
}>
}
>
<ThemedView style={styles.titleContainer}>
<ThemedText type="title">Welcome!</ThemedText>
<HelloWave />
@@ -33,7 +33,7 @@ export default function HomeScreen() {
</ThemedView>
<SignOutButton />
</ParallaxScrollView>
);
)
}
const styles = StyleSheet.create({
@@ -53,4 +53,4 @@ const styles = StyleSheet.create({
left: 0,
position: 'absolute',
},
});
})
@@ -9,7 +9,7 @@ export default function NotFoundScreen() {
<>
<Stack.Screen options={{ title: 'Oops!' }} />
<ThemedView style={styles.container}>
<ThemedText type="title">This screen does not exist.</ThemedText>
<ThemedText type="title">This screen doesn&apos;t exist.</ThemedText>
<Link href="/" style={styles.link}>
<ThemedText type="link">Go to home screen!</ThemedText>
</Link>
+12 -23
View File
@@ -1,18 +1,17 @@
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import { useFonts } from 'expo-font';
import { Stack } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import 'react-native-reanimated';
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native'
import { Stack } from 'expo-router'
import { StatusBar } from 'expo-status-bar'
import 'react-native-reanimated'
import { SplashScreenController } from '@/components/splash-screen-controller';
import { SplashScreenController } from '@/components/splash-screen-controller'
import { useAuthContext } from '@/hooks/use-auth-context';
import { useColorScheme } from '@/hooks/use-color-scheme';
import AuthProvider from '@/providers/auth-provider';
import { useAuthContext } from '@/hooks/use-auth-context'
import { useColorScheme } from '@/hooks/use-color-scheme'
import AuthProvider from '@/providers/auth-provider'
// Separate RootNavigator so we can access the AuthContext
function RootNavigator() {
const { isLoggedIn } = useAuthContext();
const { isLoggedIn } = useAuthContext()
return (
<Stack>
@@ -24,20 +23,11 @@ function RootNavigator() {
</Stack.Protected>
<Stack.Screen name="+not-found" />
</Stack>
);
)
}
export default function RootLayout() {
const colorScheme = useColorScheme();
const [loaded] = useFonts({
SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
});
if (!loaded) {
// Async font loading only occurs in development.
return null;
}
const colorScheme = useColorScheme()
return (
<ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
@@ -47,6 +37,5 @@ export default function RootLayout() {
<StatusBar style="auto" />
</AuthProvider>
</ThemeProvider>
);
)
}
+10 -34
View File
@@ -1,40 +1,21 @@
import { Link, Stack } from 'expo-router';
import { Platform, StyleSheet } from 'react-native';
import { Link, Stack } from 'expo-router'
import { StyleSheet } from 'react-native'
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import AppleSignInButton from '@/components/social-auth-buttons/apple/apple-sign-in-button';
import ExpoAppleSignInButton from '@/components/social-auth-buttons/apple/expo-apple-sign-in-button';
import GoogleSignInButton from '@/components/social-auth-buttons/google/google-sign-in-button';
import { Image } from 'expo-image';
import { ThemedText } from '@/components/themed-text'
import { ThemedView } from '@/components/themed-view'
export default function LoginScreen() {
return (
<>
<Stack.Screen options={{ title: 'Login' }} />
<ThemedView style={styles.container}>
<Image style={styles.image} source={require('@/assets/supabase-logo-icon.svg')} />
<ThemedText type="title">Login</ThemedText>
<Link href="/(tabs)/explore" style={styles.link}>
<Link href="/" style={styles.link}>
<ThemedText type="link">Try to navigate to home screen!</ThemedText>
</Link>
<ThemedView style={styles.socialAuthButtonsContainer}>
{Platform.OS === 'ios' && (
<>
<ThemedText type="default">Invertase Apple Sign In</ThemedText>
<AppleSignInButton />
<ThemedText type="default">Expo Apple Sign In</ThemedText>
<ExpoAppleSignInButton />
</>
)}
{Platform.OS !== 'ios' && (<AppleSignInButton />)}
<GoogleSignInButton />
</ThemedView>
</ThemedView>
</>
);
)
}
const styles = StyleSheet.create({
@@ -43,14 +24,9 @@ const styles = StyleSheet.create({
alignItems: 'center',
justifyContent: 'center',
padding: 20,
gap: 20,
},
socialAuthButtonsContainer: {
display: 'flex',
gap: 10,
link: {
marginTop: 15,
paddingVertical: 15,
},
image: {
width: 100,
height: 100,
},
});
})
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 384 KiB

@@ -1,15 +0,0 @@
<svg width="109" height="113" viewBox="0 0 109 113" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M63.7076 110.284C60.8481 113.885 55.0502 111.912 54.9813 107.314L53.9738 40.0627L99.1935 40.0627C107.384 40.0627 111.952 49.5228 106.859 55.9374L63.7076 110.284Z" fill="url(#paint0_linear)"/>
<path d="M63.7076 110.284C60.8481 113.885 55.0502 111.912 54.9813 107.314L53.9738 40.0627L99.1935 40.0627C107.384 40.0627 111.952 49.5228 106.859 55.9374L63.7076 110.284Z" fill="url(#paint1_linear)" fill-opacity="0.2"/>
<path d="M45.317 2.07103C48.1765 -1.53037 53.9745 0.442937 54.0434 5.041L54.4849 72.2922H9.83113C1.64038 72.2922 -2.92775 62.8321 2.1655 56.4175L45.317 2.07103Z" fill="#3ECF8E"/>
<defs>
<linearGradient id="paint0_linear" x1="53.9738" y1="54.974" x2="94.1635" y2="71.8295" gradientUnits="userSpaceOnUse">
<stop stop-color="#249361"/>
<stop offset="1" stop-color="#3ECF8E"/>
</linearGradient>
<linearGradient id="paint1_linear" x1="36.1558" y1="30.578" x2="54.4844" y2="65.0806" gradientUnits="userSpaceOnUse">
<stop/>
<stop offset="1" stop-opacity="0"/>
</linearGradient>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

@@ -1,45 +0,0 @@
import { PropsWithChildren, useState } from 'react';
import { StyleSheet, TouchableOpacity } from 'react-native';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { IconSymbol } from '@/components/ui/icon-symbol';
import { Colors } from '@/constants/colors';
import { useColorScheme } from '@/hooks/use-color-scheme';
export function Collapsible({ children, title }: PropsWithChildren & { title: string }) {
const [isOpen, setIsOpen] = useState(false);
const theme = useColorScheme() ?? 'light';
return (
<ThemedView>
<TouchableOpacity
style={styles.heading}
onPress={() => setIsOpen((value) => !value)}
activeOpacity={0.8}>
<IconSymbol
name="chevron.right"
size={18}
weight="medium"
color={theme === 'light' ? Colors.light.icon : Colors.dark.icon}
style={{ transform: [{ rotate: isOpen ? '90deg' : '0deg' }] }}
/>
<ThemedText type="defaultSemiBold">{title}</ThemedText>
</TouchableOpacity>
{isOpen && <ThemedView style={styles.content}>{children}</ThemedView>}
</ThemedView>
);
}
const styles = StyleSheet.create({
heading: {
flexDirection: 'row',
alignItems: 'center',
gap: 6,
},
content: {
marginTop: 6,
marginLeft: 24,
},
});
@@ -1,24 +0,0 @@
import { Href, Link } from 'expo-router';
import { openBrowserAsync } from 'expo-web-browser';
import { type ComponentProps } from 'react';
import { Platform } from 'react-native';
type Props = Omit<ComponentProps<typeof Link>, 'href'> & { href: Href & string };
export function ExternalLink({ href, ...rest }: Props) {
return (
<Link
target="_blank"
{...rest}
href={href}
onPress={async (event) => {
if (Platform.OS !== 'web') {
// Prevent the default behavior of linking to the default browser on native.
event.preventDefault();
// Open the link in an in-app browser.
await openBrowserAsync(href);
}
}}
/>
);
}
@@ -1,18 +0,0 @@
import { BottomTabBarButtonProps } from '@react-navigation/bottom-tabs';
import { PlatformPressable } from '@react-navigation/elements';
import * as Haptics from 'expo-haptics';
export function HapticTab(props: BottomTabBarButtonProps) {
return (
<PlatformPressable
{...props}
onPressIn={(ev) => {
if (process.env.EXPO_OS === 'ios') {
// Add a soft haptic feedback when pressing down on the tabs.
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
}
props.onPressIn?.(ev);
}}
/>
);
}
@@ -1,11 +1,11 @@
import { useEffect } from 'react';
import { StyleSheet } from 'react-native';
import Animated, {
useAnimatedStyle,
useSharedValue,
useAnimatedStyle,
withTiming,
withRepeat,
withSequence,
withTiming,
} from 'react-native-reanimated';
import { ThemedText } from '@/components/themed-text';
@@ -16,7 +16,7 @@ export function HelloWave() {
useEffect(() => {
rotationAnimation.value = withRepeat(
withSequence(withTiming(25, { duration: 150 }), withTiming(0, { duration: 150 })),
4 // Run the animation 4 times
4
);
}, [rotationAnimation]);
@@ -8,7 +8,6 @@ import Animated, {
} from 'react-native-reanimated';
import { ThemedView } from '@/components/themed-view';
import { useBottomTabOverflow } from '@/components/ui/tab-bar-background';
import { useColorScheme } from '@/hooks/use-color-scheme';
const HEADER_HEIGHT = 250;
@@ -26,7 +25,7 @@ export default function ParallaxScrollView({
const colorScheme = useColorScheme() ?? 'light';
const scrollRef = useAnimatedRef<Animated.ScrollView>();
const scrollOffset = useScrollViewOffset(scrollRef);
const bottom = useBottomTabOverflow();
const headerAnimatedStyle = useAnimatedStyle(() => {
return {
transform: [
@@ -46,11 +45,7 @@ export default function ParallaxScrollView({
return (
<ThemedView style={styles.container}>
<Animated.ScrollView
ref={scrollRef}
scrollEventThrottle={16}
scrollIndicatorInsets={{ bottom }}
contentContainerStyle={{ paddingBottom: bottom }}>
<Animated.ScrollView ref={scrollRef} scrollEventThrottle={16}>
<Animated.View
style={[
styles.header,
@@ -34,7 +34,7 @@ async function onAppleButtonPress() {
// Open the browser window for user sign in
const credentialState = await appleAuthAndroid.signIn();
console.log('Apple sign in successful:', credentialState)
console.log('Apple sign in successful:', credentialState);
if (credentialState.id_token && credentialState.code && credentialState.nonce) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
@@ -42,16 +42,16 @@ async function onAppleButtonPress() {
token: credentialState.id_token,
nonce: credentialState.nonce,
access_token: credentialState.code,
}
};
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials)
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials);
if (error) {
console.error('Error signing in with Apple:', error)
console.error('Error signing in with Apple:', error);
}
if (data) {
console.log('Apple sign in successful:', data)
console.log('Apple sign in successful:', data);
}
}
}
@@ -64,4 +64,4 @@ export default function AppleSignInButton() {
buttonType={AppleButton.Type.SIGN_IN}
onPress={() => onAppleButtonPress()}
/>;
}
}
@@ -16,7 +16,7 @@ async function onAppleButtonPress() {
// Note: This method must be tested on a real device. On the iOS simulator it always throws an error.
const credentialState = await appleAuth.getCredentialStateForUser(appleAuthRequestResponse.user);
console.log('Apple sign in successful:', { credentialState, appleAuthRequestResponse })
console.log('Apple sign in successful:', { credentialState, appleAuthRequestResponse });
if (credentialState === appleAuth.State.AUTHORIZED && appleAuthRequestResponse.identityToken && appleAuthRequestResponse.authorizationCode) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
@@ -24,28 +24,28 @@ async function onAppleButtonPress() {
token: appleAuthRequestResponse.identityToken,
nonce: appleAuthRequestResponse.nonce,
access_token: appleAuthRequestResponse.authorizationCode,
}
};
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials)
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials);
if (error) {
console.error('Error signing in with Apple:', error)
console.error('Error signing in with Apple:', error);
}
if (data) {
console.log('Apple sign in successful:', data)
router.navigate('/(tabs)/explore')
console.log('Apple sign in successful:', data);
router.navigate('/(tabs)');
}
}
}
export default function AppleSignInButton() {
if (Platform.OS !== 'ios') { return <></> }
if (Platform.OS !== 'ios') { return <></>; }
return <AppleButton
buttonStyle={AppleButton.Style.BLACK}
buttonType={AppleButton.Type.SIGN_IN}
style={{ width: 160, height: 45 }}
onPress={() => onAppleButtonPress()}
/>;
}
}
@@ -1,69 +1,51 @@
import { supabase } from '@/lib/supabase';
import { AppleButton, appleAuth } from '@invertase/react-native-apple-authentication';
import type { SignInWithIdTokenCredentials } from '@supabase/supabase-js';
import { useEffect, useState } from 'react';
import AppleSignin, { type AppleAuthResponse } from 'react-apple-signin-auth';
import { router } from 'expo-router';
import { Platform } from 'react-native';
/**
* This is the Apple sign in button for the web.
*/
export default function AppleSignInButton() {
const [nonce, setNonce] = useState('');
const [sha256Nonce, setSha256Nonce] = useState('');
async function onAppleButtonSuccess(appleAuthRequestResponse: AppleAuthResponse) {
console.debug('Apple sign in successful:', { appleAuthRequestResponse })
if (appleAuthRequestResponse.authorization && appleAuthRequestResponse.authorization.id_token && appleAuthRequestResponse.authorization.code) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
provider: 'apple',
token: appleAuthRequestResponse.authorization.id_token,
nonce,
access_token: appleAuthRequestResponse.authorization.code,
}
async function onAppleButtonPress() {
// Performs login request
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
// Note: it appears putting FULL_NAME first is important, see issue #293
requestedScopes: [appleAuth.Scope.FULL_NAME, appleAuth.Scope.EMAIL],
});
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials)
// Get the current authentication state for user
// Note: This method must be tested on a real device. On the iOS simulator it always throws an error.
const credentialState = await appleAuth.getCredentialStateForUser(appleAuthRequestResponse.user);
if (error) {
console.error('Error signing in with Apple:', error)
}
console.log('Apple sign in successful:', { credentialState, appleAuthRequestResponse });
if (data) {
console.log('Apple sign in successful:', data)
}
}
}
useEffect(() => {
function generateNonce(): string {
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return array[0].toString();
if (credentialState === appleAuth.State.AUTHORIZED && appleAuthRequestResponse.identityToken && appleAuthRequestResponse.authorizationCode) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
provider: 'apple',
token: appleAuthRequestResponse.identityToken,
nonce: appleAuthRequestResponse.nonce,
access_token: appleAuthRequestResponse.authorizationCode,
};
async function generateSha256Nonce(nonce: string): Promise<string> {
const buffer = await window.crypto.subtle.digest('sha-256', new TextEncoder().encode(nonce));
const array = Array.from(new Uint8Array(buffer));
return array.map(b => b.toString(16).padStart(2, '0')).join('');
}
let nonce = generateNonce();
setNonce(nonce);
generateSha256Nonce(nonce)
.then((sha256Nonce) => { setSha256Nonce(sha256Nonce) });
}, []);
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials);
if (Platform.OS !== 'web') { return <></> }
return <AppleSignin
authOptions={{
clientId: process.env.EXPO_PUBLIC_APPLE_AUTH_SERVICE_ID ?? '',
redirectURI: process.env.EXPO_PUBLIC_APPLE_AUTH_REDIRECT_URI ?? '',
scope: 'email name',
state: 'state',
nonce: sha256Nonce,
usePopup: true,
}}
onSuccess={onAppleButtonSuccess}
if (error) {
console.error('Error signing in with Apple:', error);
}
if (data) {
console.log('Apple sign in successful:', data);
router.navigate('/(tabs)');
}
}
}
export default function AppleSignInButton() {
if (Platform.OS !== 'ios') { return <></>; }
return <AppleButton
buttonStyle={AppleButton.Style.BLACK}
buttonType={AppleButton.Type.SIGN_IN}
style={{ width: 160, height: 45 }}
onPress={() => onAppleButtonPress()}
/>;
}
}
@@ -0,0 +1,68 @@
import { supabase } from '@/lib/supabase';
import type { SignInWithIdTokenCredentials } from '@supabase/supabase-js';
import { useEffect, useState } from 'react';
import AppleSignin, { type AppleAuthResponse } from 'react-apple-signin-auth';
import { Platform } from 'react-native';
export default function AppleSignInButton() {
const [nonce, setNonce] = useState('');
const [sha256Nonce, setSha256Nonce] = useState('');
async function onAppleButtonSuccess(appleAuthRequestResponse: AppleAuthResponse) {
console.debug('Apple sign in successful:', { appleAuthRequestResponse });
if (appleAuthRequestResponse.authorization && appleAuthRequestResponse.authorization.id_token && appleAuthRequestResponse.authorization.code) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
provider: 'apple',
token: appleAuthRequestResponse.authorization.id_token,
nonce,
access_token: appleAuthRequestResponse.authorization.code,
};
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials)
if (error) {
console.error('Error signing in with Apple:', error);
}
if (data) {
console.log('Apple sign in successful:', data);
}
};
}
useEffect(() => {
function generateNonce(): string {
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return array[0].toString();
};
async function generateSha256Nonce(nonce: string): Promise<string> {
const buffer = await window.crypto.subtle.digest('sha-256', new TextEncoder().encode(nonce));
const array = Array.from(new Uint8Array(buffer));
return array.map(b => b.toString(16).padStart(2, '0')).join('');
}
let nonce = generateNonce();
setNonce(nonce);
generateSha256Nonce(nonce)
.then((sha256Nonce) => { setSha256Nonce(sha256Nonce) });
}, []);
if (Platform.OS !== 'web') { return <></>; }
return <AppleSignin
authOptions={{
clientId: process.env.EXPO_PUBLIC_APPLE_AUTH_SERVICE_ID ?? '',
redirectURI: process.env.EXPO_PUBLIC_APPLE_AUTH_REDIRECT_URI ?? '',
scope: 'email name',
state: 'state',
nonce: sha256Nonce,
usePopup: true,
}}
uiType="dark"
onSuccess={onAppleButtonSuccess}
onError={(error: any) => console.error('Apple sign in error:', error)}
/>;
}
@@ -1,69 +0,0 @@
import { supabase } from '@/lib/supabase';
import type { SignInWithIdTokenCredentials } from '@supabase/supabase-js';
import * as AppleAuthentication from 'expo-apple-authentication';
import { router } from 'expo-router';
import { Platform, StyleSheet } from 'react-native';
async function onAppleButtonPress() {
// Performs login request
try {
const appleAuthRequestResponse = await AppleAuthentication.signInAsync({
requestedScopes: [
AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
AppleAuthentication.AppleAuthenticationScope.EMAIL,
],
});
console.log('Apple sign in successful:', { appleAuthRequestResponse })
if (appleAuthRequestResponse.identityToken && appleAuthRequestResponse.authorizationCode) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
provider: 'apple',
token: appleAuthRequestResponse.identityToken,
access_token: appleAuthRequestResponse.authorizationCode,
}
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials)
if (error) {
console.error('Error signing in with Apple:', error)
}
if (data) {
console.log('Apple sign in successful:', data)
router.navigate('/(tabs)/explore')
}
}
} catch (e: any) {
if (e.code === 'ERR_REQUEST_CANCELED') {
console.error('Error signing in with Apple:', e)
} else {
console.error('Error signing in with Apple:', e)
}
}
}
export default function ExpoAppleSignInButton() {
if (Platform.OS !== 'ios') { return <></> }
return <AppleAuthentication.AppleAuthenticationButton
buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN}
buttonStyle={AppleAuthentication.AppleAuthenticationButtonStyle.BLACK}
cornerRadius={5}
style={styles.button}
onPress={() => onAppleButtonPress()}
/>
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
button: {
width: 160, height: 45
},
});
@@ -15,7 +15,7 @@ export default function GoogleSignInButton() {
const parsedUrl = new URL(url);
const hash = parsedUrl.hash.substring(1); // Remove the leading '#'
const params = new URLSearchParams(hash);
return {
access_token: params.get("access_token"),
expires_in: parseInt(params.get("expires_in") || "0"),
@@ -25,7 +25,7 @@ export default function GoogleSignInButton() {
code: params.get("code"),
};
};
async function onSignInButtonPress() {
console.debug('onSignInButtonPress - start');
const res = await supabase.auth.signInWithOAuth({
@@ -39,7 +39,7 @@ export default function GoogleSignInButton() {
const googleOAuthUrl = res.data.url;
if (!googleOAuthUrl) {
if (!googleOAuthUrl) {
console.error("no oauth url found!");
return;
}
@@ -49,7 +49,7 @@ export default function GoogleSignInButton() {
`${expo.scheme}://google-auth`,
{ showInRecents: true },
).catch((err) => {
console.error('onSignInButtonPress - openAuthSessionAsync - error', { err })
console.error('onSignInButtonPress - openAuthSessionAsync - error', { err });
console.log(err);
});
@@ -12,28 +12,28 @@ export default function GoogleSignInButton() {
const [sha256Nonce, setSha256Nonce] = useState('');
async function onGoogleButtonSuccess(authRequestResponse: CredentialResponse) {
console.debug('Google sign in successful:', { authRequestResponse })
console.debug('Google sign in successful:', { authRequestResponse });
if (authRequestResponse.clientId && authRequestResponse.credential) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
provider: 'google',
token: authRequestResponse.credential,
nonce: nonce,
}
};
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials)
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials);
if (error) {
console.error('Error signing in with Google:', error)
console.error('Error signing in with Google:', error);
}
if (data) {
console.log('Google sign in successful:', data)
console.log('Google sign in successful:', data);
}
}
}
function onGoogleButtonFailure() {
console.error('Error signing in with Google')
console.error('Error signing in with Google');
}
useEffect(() => {
@@ -41,7 +41,7 @@ export default function GoogleSignInButton() {
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return array[0].toString();
};
}
async function generateSha256Nonce(nonce: string): Promise<string> {
const buffer = await window.crypto.subtle.digest('sha-256', new TextEncoder().encode(nonce));
@@ -70,4 +70,4 @@ export default function GoogleSignInButton() {
/>
</GoogleOAuthProvider>
);
}
}
@@ -1,24 +1,15 @@
import { useAuthContext } from '@/hooks/use-auth-context';
import { supabase } from '@/lib/supabase';
import React from 'react';
import { Button } from 'react-native';
import { supabase } from '@/lib/supabase'
import React from 'react'
import { Button } from 'react-native'
async function onSignOutButtonPress() {
const { error } = await supabase.auth.signOut()
const { error } = await supabase.auth.signOut()
if (error) {
console.error('Error signing out:', error)
}
if (error) {
console.error('Error signing out:', error)
}
}
export default function SignOutButton() {
const { isLoggedIn } = useAuthContext();
return (
<Button
disabled={!isLoggedIn}
title="Sign out"
onPress={onSignOutButtonPress}
/>
);
}
return <Button title="Sign out" onPress={onSignOutButtonPress} />
}
@@ -1,15 +1,14 @@
import { useAuthContext } from '@/hooks/use-auth-context';
import { SplashScreen } from 'expo-router';
import { useAuthContext } from '@/hooks/use-auth-context'
import { SplashScreen } from 'expo-router'
SplashScreen.preventAutoHideAsync();
SplashScreen.preventAutoHideAsync()
export function SplashScreenController() {
const { isLoading } = useAuthContext();
const { isLoading } = useAuthContext()
if (!isLoading) {
console.log('SplashScreenController - Hiding splash screen');
SplashScreen.hideAsync();
SplashScreen.hideAsync()
}
return null;
}
return null
}
@@ -1,6 +1,7 @@
import { StyleSheet, Text, type TextProps } from 'react-native';
import { Text, type TextProps, StyleSheet } from 'react-native';
import { useThemeColor } from '@/hooks/use-theme-color';
import { Fonts } from '@/constants/theme';
export type ThemedTextProps = TextProps & {
lightColor?: string;
@@ -20,7 +21,7 @@ export function ThemedText({
return (
<Text
style={[
{ color },
{ color, fontFamily: Fonts?.sans },
type === 'default' ? styles.default : undefined,
type === 'title' ? styles.title : undefined,
type === 'defaultSemiBold' ? styles.defaultSemiBold : undefined,
@@ -1,32 +0,0 @@
import { SymbolView, SymbolViewProps, SymbolWeight } from 'expo-symbols';
import { StyleProp, ViewStyle } from 'react-native';
export function IconSymbol({
name,
size = 24,
color,
style,
weight = 'regular',
}: {
name: SymbolViewProps['name'];
size?: number;
color: string;
style?: StyleProp<ViewStyle>;
weight?: SymbolWeight;
}) {
return (
<SymbolView
weight={weight}
tintColor={color}
resizeMode="scaleAspectFit"
name={name}
style={[
{
width: size,
height: size,
},
style,
]}
/>
);
}
@@ -1,41 +0,0 @@
// Fallback for using MaterialIcons on Android and web.
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { SymbolWeight, SymbolViewProps } from 'expo-symbols';
import { ComponentProps } from 'react';
import { OpaqueColorValue, type StyleProp, type TextStyle } from 'react-native';
type IconMapping = Record<SymbolViewProps['name'], ComponentProps<typeof MaterialIcons>['name']>;
type IconSymbolName = keyof typeof MAPPING;
/**
* Add your SF Symbols to Material Icons mappings here.
* - see Material Icons in the [Icons Directory](https://icons.expo.fyi).
* - see SF Symbols in the [SF Symbols](https://developer.apple.com/sf-symbols/) app.
*/
const MAPPING = {
'house.fill': 'home',
'paperplane.fill': 'send',
'chevron.left.forwardslash.chevron.right': 'code',
'chevron.right': 'chevron-right',
} as IconMapping;
/**
* An icon component that uses native SF Symbols on iOS, and Material Icons on Android and web.
* This ensures a consistent look across platforms, and optimal resource usage.
* Icon `name`s are based on SF Symbols and require manual mapping to Material Icons.
*/
export function IconSymbol({
name,
size = 24,
color,
style,
}: {
name: IconSymbolName;
size?: number;
color: string | OpaqueColorValue;
style?: StyleProp<TextStyle>;
weight?: SymbolWeight;
}) {
return <MaterialIcons color={color} size={size} name={MAPPING[name]} style={style} />;
}
@@ -1,19 +0,0 @@
import { useBottomTabBarHeight } from '@react-navigation/bottom-tabs';
import { BlurView } from 'expo-blur';
import { StyleSheet } from 'react-native';
export default function BlurTabBarBackground() {
return (
<BlurView
// System chrome material automatically adapts to the system's theme
// and matches the native tab bar appearance on iOS.
tint="systemChromeMaterial"
intensity={100}
style={StyleSheet.absoluteFill}
/>
);
}
export function useBottomTabOverflow() {
return useBottomTabBarHeight();
}
@@ -1,6 +0,0 @@
// This is a shim for web and Android where the tab bar is generally opaque.
export default undefined;
export function useBottomTabOverflow() {
return 0;
}
@@ -1,26 +0,0 @@
/**
* Below are the colors that are used in the app. The colors are defined in the light and dark mode.
* There are many other ways to style your app. For example, [Nativewind](https://www.nativewind.dev/), [Tamagui](https://tamagui.dev/), [unistyles](https://reactnativeunistyles.vercel.app), etc.
*/
const tintColorLight = '#0a7ea4';
const tintColorDark = '#fff';
export const Colors = {
light: {
text: '#11181C',
background: '#fff',
tint: tintColorLight,
icon: '#687076',
tabIconDefault: '#687076',
tabIconSelected: tintColorLight,
},
dark: {
text: '#ECEDEE',
background: '#151718',
tint: tintColorDark,
icon: '#9BA1A6',
tabIconDefault: '#9BA1A6',
tabIconSelected: tintColorDark,
},
};
@@ -0,0 +1,53 @@
/**
* Below are the colors that are used in the app. The colors are defined in the light and dark mode.
* There are many other ways to style your app. For example, [Nativewind](https://www.nativewind.dev/), [Tamagui](https://tamagui.dev/), [unistyles](https://reactnativeunistyles.vercel.app), etc.
*/
import { Platform } from 'react-native';
const tintColorLight = '#0a7ea4';
const tintColorDark = '#fff';
export const Colors = {
light: {
text: '#11181C',
background: '#fff',
tint: tintColorLight,
icon: '#687076',
tabIconDefault: '#687076',
tabIconSelected: tintColorLight,
},
dark: {
text: '#ECEDEE',
background: '#151718',
tint: tintColorDark,
icon: '#9BA1A6',
tabIconDefault: '#9BA1A6',
tabIconSelected: tintColorDark,
},
};
export const Fonts = Platform.select({
ios: {
/** iOS `UIFontDescriptorSystemDesignDefault` */
sans: 'system-ui',
/** iOS `UIFontDescriptorSystemDesignSerif` */
serif: 'ui-serif',
/** iOS `UIFontDescriptorSystemDesignRounded` */
rounded: 'ui-rounded',
/** iOS `UIFontDescriptorSystemDesignMonospaced` */
mono: 'ui-monospace',
},
default: {
sans: 'normal',
serif: 'serif',
rounded: 'normal',
mono: 'monospace',
},
web: {
sans: "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",
serif: "Georgia, 'Times New Roman', serif",
rounded: "'SF Pro Rounded', 'Hiragino Maru Gothic ProN', Meiryo, 'MS PGothic', sans-serif",
mono: "SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",
},
});
@@ -1,18 +1,17 @@
import { Session } from '@supabase/supabase-js'
import { createContext, useContext } from 'react'
export type AuthData = {
session?: Session | null
claims?: Record<string, any> | null
profile?: any | null
isLoading: boolean
isLoggedIn: boolean
}
export const AuthContext = createContext<AuthData>({
session: undefined,
claims: undefined,
profile: undefined,
isLoading: true,
isLoggedIn: false
isLoggedIn: false,
})
export const useAuthContext = () => useContext(AuthContext)
@@ -3,7 +3,7 @@
* https://docs.expo.dev/guides/color-schemes/
*/
import { Colors } from '@/constants/colors';
import { Colors } from '@/constants/theme';
import { useColorScheme } from '@/hooks/use-color-scheme';
export function useThemeColor(
@@ -15,7 +15,7 @@ const ExpoSecureStoreAdapter = {
removeItem: (key: string) => {
return deleteItemAsync(key)
},
}
};
export const supabase = createClient(
process.env.EXPO_PUBLIC_SUPABASE_URL ?? '',
@@ -2,18 +2,23 @@ import AsyncStorage from '@react-native-async-storage/async-storage';
import { createClient } from '@supabase/supabase-js';
import 'react-native-url-polyfill/auto';
const isSSR = typeof window === 'undefined';
const ExpoWebSecureStoreAdapter = {
getItem: (key: string) => {
if (isSSR) return null;
console.debug("getItem", { key })
return AsyncStorage.getItem(key)
},
setItem: (key: string, value: string) => {
if (isSSR) return;
return AsyncStorage.setItem(key, value)
},
removeItem: (key: string) => {
if (isSSR) return;
return AsyncStorage.removeItem(key)
},
}
};
export const supabase = createClient(
process.env.EXPO_PUBLIC_SUPABASE_URL ?? '',
File diff suppressed because it is too large. Load diff
+35 -39
View File
@@ -11,50 +11,46 @@
"lint": "expo lint"
},
"dependencies": {
"@expo/vector-icons": "^15.0.2",
"@invertase/react-native-apple-authentication": "^2.4.1",
"@expo/vector-icons": "^15.0.3",
"@invertase/react-native-apple-authentication": "^2.5.1",
"@react-native-async-storage/async-storage": "2.2.0",
"@react-navigation/bottom-tabs": "^7.4.0",
"@react-navigation/elements": "^2.6.3",
"@react-navigation/native": "^7.1.8",
"@react-oauth/google": "^0.12.2",
"@supabase/supabase-js": "^2.57.4",
"expo-apple-authentication": "~7.2.4",
"expo-blur": "~14.1.5",
"expo-constants": "~18.0.8",
"expo-font": "~14.0.8",
"expo-haptics": "~15.0.7",
"expo-image": "~3.0.8",
"expo-linking": "~8.0.8",
"expo-router": "~6.0.1",
"expo-secure-store": "~14.2.4",
"expo-splash-screen": "~31.0.9",
"expo-status-bar": "~3.0.8",
"expo-symbols": "~1.0.7",
"expo-system-ui": "~6.0.7",
"expo-web-browser": "~15.0.7",
"expo": "~54.0.2",
"@react-navigation/bottom-tabs": "^7.14.0",
"@react-navigation/elements": "^2.9.5",
"@react-navigation/native": "^7.1.28",
"@react-oauth/google": "^0.13.4",
"@supabase/supabase-js": "^2.97.0",
"expo": "~54.0.33",
"expo-constants": "~18.0.13",
"expo-font": "~14.0.11",
"expo-haptics": "~15.0.8",
"expo-image": "~3.0.11",
"expo-linking": "~8.0.11",
"expo-router": "~6.0.23",
"expo-secure-store": "~15.0.8",
"expo-splash-screen": "~31.0.13",
"expo-status-bar": "~3.0.9",
"expo-symbols": "~1.0.8",
"expo-system-ui": "~6.0.9",
"expo-web-browser": "~15.0.10",
"react": "19.2.4",
"react-apple-signin-auth": "^1.1.2",
"react-dom": "19.1.0",
"react-native-gesture-handler": "~2.28.0",
"react-native-get-random-values": "~1.11.0",
"react-native-reanimated": "~4.1.0",
"react-native-safe-area-context": "~5.6.0",
"react-native-screens": "~4.16.0",
"react-native-url-polyfill": "^2.0.0",
"react-native-web": "~0.21.0",
"react-native-webview": "13.16.0",
"react-native-worklets": "0.5.1",
"react-native": "0.81.4",
"react": "19.1.0",
"uuid": "^11.1.0"
"react-dom": "19.2.4",
"react-native": "0.84.0",
"react-native-gesture-handler": "~2.30.0",
"react-native-get-random-values": "~2.0.0",
"react-native-reanimated": "~4.2.2",
"react-native-safe-area-context": "~5.6.2",
"react-native-screens": "~4.23.0",
"react-native-url-polyfill": "^3.0.0",
"react-native-web": "~0.21.2",
"react-native-worklets": "0.7.4"
},
"devDependencies": {
"@babel/core": "^7.28.4",
"@types/react": "~19.1.0",
"@types/react": "~19.2.14",
"@types/uuid": "^11.0.0",
"eslint": "^10.0.0",
"eslint-config-expo": "~10.0.0",
"eslint": "^9.25.0",
"typescript": "~5.9.2"
"typescript": "~5.9.3"
},
"private": true
}
@@ -1,33 +1,35 @@
import { AuthContext } from '@/hooks/use-auth-context'
import { supabase } from '@/lib/supabase'
import type { Session } from '@supabase/supabase-js'
import { PropsWithChildren, useEffect, useState } from 'react'
export default function AuthProvider({ children }: PropsWithChildren) {
const [session, setSession] = useState<Session | undefined | null>()
const [claims, setClaims] = useState<Record<string, any> | undefined | null>()
const [profile, setProfile] = useState<any>()
const [isLoading, setIsLoading] = useState<boolean>(true)
// Fetch the session once, and subscribe to auth state changes
// Fetch the claims once, and subscribe to auth state changes
useEffect(() => {
const fetchSession = async () => {
const fetchClaims = async () => {
setIsLoading(true)
const { data: { session }, error } = await supabase.auth.getSession()
const { data, error } = await supabase.auth.getClaims()
if (error) {
console.error('Error fetching session:', error)
console.error('Error fetching claims:', error)
}
setSession(session)
setClaims(data?.claims ?? null)
setIsLoading(false)
}
fetchSession()
fetchClaims()
const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
console.log('Auth state changed:', { event: _event, session })
setSession(session)
const {
data: { subscription },
} = supabase.auth.onAuthStateChange(async (_event, _session) => {
console.log('Auth state changed:', { event: _event })
const { data } = await supabase.auth.getClaims()
setClaims(data?.claims ?? null)
})
// Cleanup subscription on unmount
@@ -36,16 +38,16 @@ export default function AuthProvider({ children }: PropsWithChildren) {
}
}, [])
// Fetch the profile when the session changes
// Fetch the profile when the claims change
useEffect(() => {
const fetchProfile = async () => {
setIsLoading(true)
if (session) {
if (claims) {
const { data } = await supabase
.from('profiles')
.select('*')
.eq('id', session.user.id)
.eq('id', claims.sub)
.single()
setProfile(data)
@@ -57,15 +59,15 @@ export default function AuthProvider({ children }: PropsWithChildren) {
}
fetchProfile()
}, [session])
}, [claims])
return (
<AuthContext.Provider
value={{
session,
claims,
isLoading,
profile,
isLoggedIn: session != undefined
isLoggedIn: claims != undefined,
}}
>
{children}
@@ -0,0 +1,7 @@
# @generated expo-cli sync-2b81b286409207a5da26e14c78851eb30d8ccbdb
# The following patterns were generated by expo-cli
.expo
expo-env.d.ts
dist
# @end expo-cli
@@ -0,0 +1,49 @@
{
"expo": {
"name": "ff",
"slug": "ff",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/images/icon.png",
"scheme": "ff",
"userInterfaceStyle": "automatic",
"newArchEnabled": true,
"ios": {
"supportsTablet": true
},
"android": {
"adaptiveIcon": {
"backgroundColor": "#E6F4FE",
"foregroundImage": "./assets/images/android-icon-foreground.png",
"backgroundImage": "./assets/images/android-icon-background.png",
"monochromeImage": "./assets/images/android-icon-monochrome.png"
},
"edgeToEdgeEnabled": true,
"predictiveBackGestureEnabled": false
},
"web": {
"output": "static",
"favicon": "./assets/images/favicon.png"
},
"plugins": [
"expo-router",
[
"expo-splash-screen",
{
"image": "./assets/images/splash-icon.png",
"imageWidth": 200,
"resizeMode": "contain",
"backgroundColor": "#ffffff",
"dark": {
"backgroundColor": "#000000"
}
}
],
"expo-secure-store"
],
"experiments": {
"typedRoutes": true,
"reactCompiler": true
}
}
}
@@ -0,0 +1,23 @@
import { Tabs } from 'expo-router';
import { Colors } from '@/constants/theme';
import { useColorScheme } from '@/hooks/use-color-scheme';
export default function TabLayout() {
const colorScheme = useColorScheme();
return (
<Tabs
screenOptions={{
tabBarActiveTintColor: Colors[colorScheme ?? 'light'].tint,
headerShown: false,
}}>
<Tabs.Screen
name="index"
options={{
title: 'Home',
}}
/>
</Tabs>
);
}
@@ -0,0 +1,56 @@
import { Image } from 'expo-image'
import { StyleSheet } from 'react-native'
import { HelloWave } from '@/components/hello-wave'
import ParallaxScrollView from '@/components/parallax-scroll-view'
import { ThemedText } from '@/components/themed-text'
import { ThemedView } from '@/components/themed-view'
import SignOutButton from '@/components/social-auth-buttons/sign-out-button'
import { useAuthContext } from '@/hooks/use-auth-context'
export default function HomeScreen() {
const { profile } = useAuthContext()
return (
<ParallaxScrollView
headerBackgroundColor={{ light: '#A1CEDC', dark: '#1D3D47' }}
headerImage={
<Image
source={require('@/assets/images/partial-react-logo.png')}
style={styles.reactLogo}
/>
}
>
<ThemedView style={styles.titleContainer}>
<ThemedText type="title">Welcome!</ThemedText>
<HelloWave />
</ThemedView>
<ThemedView style={styles.stepContainer}>
<ThemedText type="subtitle">Username</ThemedText>
<ThemedText>{profile?.username}</ThemedText>
<ThemedText type="subtitle">Full name</ThemedText>
<ThemedText>{profile?.full_name}</ThemedText>
</ThemedView>
<SignOutButton />
</ParallaxScrollView>
)
}
const styles = StyleSheet.create({
titleContainer: {
flexDirection: 'row',
alignItems: 'center',
gap: 8,
},
stepContainer: {
gap: 8,
marginBottom: 8,
},
reactLogo: {
height: 178,
width: 290,
bottom: 0,
left: 0,
position: 'absolute',
},
})
@@ -0,0 +1,32 @@
import { Link, Stack } from 'expo-router';
import { StyleSheet } from 'react-native';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
export default function NotFoundScreen() {
return (
<>
<Stack.Screen options={{ title: 'Oops!' }} />
<ThemedView style={styles.container}>
<ThemedText type="title">This screen doesn&apos;t exist.</ThemedText>
<Link href="/" style={styles.link}>
<ThemedText type="link">Go to home screen!</ThemedText>
</Link>
</ThemedView>
</>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 20,
},
link: {
marginTop: 15,
paddingVertical: 15,
},
});
@@ -0,0 +1,51 @@
import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native'
import { useFonts } from 'expo-font'
import { Stack } from 'expo-router'
import { StatusBar } from 'expo-status-bar'
import 'react-native-reanimated'
import { SplashScreenController } from '@/components/splash-screen-controller'
import { useAuthContext } from '@/hooks/use-auth-context'
import { useColorScheme } from '@/hooks/use-color-scheme'
import AuthProvider from '@/providers/auth-provider'
// Separate RootNavigator so we can access the AuthContext
function RootNavigator() {
const { isLoggedIn } = useAuthContext()
return (
<Stack>
<Stack.Protected guard={isLoggedIn}>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
</Stack.Protected>
<Stack.Protected guard={!isLoggedIn}>
<Stack.Screen name="login" options={{ headerShown: false }} />
</Stack.Protected>
<Stack.Screen name="+not-found" />
</Stack>
)
}
export default function RootLayout() {
const colorScheme = useColorScheme()
const [loaded] = useFonts({
SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
})
if (!loaded) {
// Async font loading only occurs in development.
return null
}
return (
<ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
<AuthProvider>
<SplashScreenController />
<RootNavigator />
<StatusBar style="auto" />
</AuthProvider>
</ThemeProvider>
)
}
@@ -0,0 +1,32 @@
import { Link, Stack } from 'expo-router'
import { StyleSheet } from 'react-native'
import { ThemedText } from '@/components/themed-text'
import { ThemedView } from '@/components/themed-view'
export default function LoginScreen() {
return (
<>
<Stack.Screen options={{ title: 'Login' }} />
<ThemedView style={styles.container}>
<ThemedText type="title">Login</ThemedText>
<Link href="/" style={styles.link}>
<ThemedText type="link">Try to navigate to home screen!</ThemedText>
</Link>
</ThemedView>
</>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
padding: 20,
},
link: {
marginTop: 15,
paddingVertical: 15,
},
})
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 384 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

@@ -0,0 +1,40 @@
import { useEffect } from 'react';
import { StyleSheet } from 'react-native';
import Animated, {
useSharedValue,
useAnimatedStyle,
withTiming,
withRepeat,
withSequence,
} from 'react-native-reanimated';
import { ThemedText } from '@/components/themed-text';
export function HelloWave() {
const rotationAnimation = useSharedValue(0);
useEffect(() => {
rotationAnimation.value = withRepeat(
withSequence(withTiming(25, { duration: 150 }), withTiming(0, { duration: 150 })),
4
);
}, [rotationAnimation]);
const animatedStyle = useAnimatedStyle(() => ({
transform: [{ rotate: `${rotationAnimation.value}deg` }],
}));
return (
<Animated.View style={animatedStyle}>
<ThemedText style={styles.text}>👋</ThemedText>
</Animated.View>
);
}
const styles = StyleSheet.create({
text: {
fontSize: 28,
lineHeight: 32,
marginTop: -6,
},
});
@@ -0,0 +1,77 @@
import type { PropsWithChildren, ReactElement } from 'react';
import { StyleSheet } from 'react-native';
import Animated, {
interpolate,
useAnimatedRef,
useAnimatedStyle,
useScrollViewOffset,
} from 'react-native-reanimated';
import { ThemedView } from '@/components/themed-view';
import { useColorScheme } from '@/hooks/use-color-scheme';
const HEADER_HEIGHT = 250;
type Props = PropsWithChildren<{
headerImage: ReactElement;
headerBackgroundColor: { dark: string; light: string };
}>;
export default function ParallaxScrollView({
children,
headerImage,
headerBackgroundColor,
}: Props) {
const colorScheme = useColorScheme() ?? 'light';
const scrollRef = useAnimatedRef<Animated.ScrollView>();
const scrollOffset = useScrollViewOffset(scrollRef);
const headerAnimatedStyle = useAnimatedStyle(() => {
return {
transform: [
{
translateY: interpolate(
scrollOffset.value,
[-HEADER_HEIGHT, 0, HEADER_HEIGHT],
[-HEADER_HEIGHT / 2, 0, HEADER_HEIGHT * 0.75]
),
},
{
scale: interpolate(scrollOffset.value, [-HEADER_HEIGHT, 0, HEADER_HEIGHT], [2, 1, 1]),
},
],
};
});
return (
<ThemedView style={styles.container}>
<Animated.ScrollView ref={scrollRef} scrollEventThrottle={16}>
<Animated.View
style={[
styles.header,
{ backgroundColor: headerBackgroundColor[colorScheme] },
headerAnimatedStyle,
]}>
{headerImage}
</Animated.View>
<ThemedView style={styles.content}>{children}</ThemedView>
</Animated.ScrollView>
</ThemedView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: HEADER_HEIGHT,
overflow: 'hidden',
},
content: {
flex: 1,
padding: 32,
gap: 16,
overflow: 'hidden',
},
});
@@ -0,0 +1,67 @@
import { supabase } from '@/lib/supabase';
import { appleAuthAndroid, AppleButton } from '@invertase/react-native-apple-authentication';
import { SignInWithIdTokenCredentials } from '@supabase/supabase-js';
import { Platform } from 'react-native';
import 'react-native-get-random-values';
import { v4 as uuid } from 'uuid';
async function onAppleButtonPress() {
// Generate secure, random values for state and nonce
const rawNonce = uuid();
const state = uuid();
// Configure the request
appleAuthAndroid.configure({
// The Service ID you registered with Apple
clientId: process.env.EXPO_PUBLIC_APPLE_AUTH_SERVICE_ID ?? '',
// Return URL added to your Apple dev console. We intercept this redirect, but it must still match
// the URL you provided to Apple. It can be an empty route on your backend as it's never called.
redirectUri: process.env.EXPO_PUBLIC_APPLE_AUTH_REDIRECT_URI ?? '',
// The type of response requested - code, id_token, or both.
responseType: appleAuthAndroid.ResponseType.ALL,
// The amount of user information requested from Apple.
scope: appleAuthAndroid.Scope.ALL,
// Random nonce value that will be SHA256 hashed before sending to Apple.
nonce: rawNonce,
// Unique state value used to prevent CSRF attacks. A UUID will be generated if nothing is provided.
state,
});
// Open the browser window for user sign in
const credentialState = await appleAuthAndroid.signIn();
console.log('Apple sign in successful:', credentialState);
if (credentialState.id_token && credentialState.code && credentialState.nonce) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
provider: 'apple',
token: credentialState.id_token,
nonce: credentialState.nonce,
access_token: credentialState.code,
};
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials);
if (error) {
console.error('Error signing in with Apple:', error);
}
if (data) {
console.log('Apple sign in successful:', data);
}
}
}
export default function AppleSignInButton() {
if (Platform.OS !== 'android' || appleAuthAndroid.isSupported !== true) { return <></> }
return <AppleButton
buttonStyle={AppleButton.Style.BLACK}
buttonType={AppleButton.Type.SIGN_IN}
onPress={() => onAppleButtonPress()}
/>;
}
@@ -0,0 +1,51 @@
import { supabase } from '@/lib/supabase';
import { AppleButton, appleAuth } from '@invertase/react-native-apple-authentication';
import type { SignInWithIdTokenCredentials } from '@supabase/supabase-js';
import { router } from 'expo-router';
import { Platform } from 'react-native';
async function onAppleButtonPress() {
// Performs login request
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
// Note: it appears putting FULL_NAME first is important, see issue #293
requestedScopes: [appleAuth.Scope.FULL_NAME, appleAuth.Scope.EMAIL],
});
// Get the current authentication state for user
// Note: This method must be tested on a real device. On the iOS simulator it always throws an error.
const credentialState = await appleAuth.getCredentialStateForUser(appleAuthRequestResponse.user);
console.log('Apple sign in successful:', { credentialState, appleAuthRequestResponse });
if (credentialState === appleAuth.State.AUTHORIZED && appleAuthRequestResponse.identityToken && appleAuthRequestResponse.authorizationCode) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
provider: 'apple',
token: appleAuthRequestResponse.identityToken,
nonce: appleAuthRequestResponse.nonce,
access_token: appleAuthRequestResponse.authorizationCode,
};
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials);
if (error) {
console.error('Error signing in with Apple:', error);
}
if (data) {
console.log('Apple sign in successful:', data);
router.navigate('/(tabs)');
}
}
}
export default function AppleSignInButton() {
if (Platform.OS !== 'ios') { return <></>; }
return <AppleButton
buttonStyle={AppleButton.Style.BLACK}
buttonType={AppleButton.Type.SIGN_IN}
style={{ width: 160, height: 45 }}
onPress={() => onAppleButtonPress()}
/>;
}
@@ -0,0 +1,51 @@
import { supabase } from '@/lib/supabase';
import { AppleButton, appleAuth } from '@invertase/react-native-apple-authentication';
import type { SignInWithIdTokenCredentials } from '@supabase/supabase-js';
import { router } from 'expo-router';
import { Platform } from 'react-native';
async function onAppleButtonPress() {
// Performs login request
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
// Note: it appears putting FULL_NAME first is important, see issue #293
requestedScopes: [appleAuth.Scope.FULL_NAME, appleAuth.Scope.EMAIL],
});
// Get the current authentication state for user
// Note: This method must be tested on a real device. On the iOS simulator it always throws an error.
const credentialState = await appleAuth.getCredentialStateForUser(appleAuthRequestResponse.user);
console.log('Apple sign in successful:', { credentialState, appleAuthRequestResponse });
if (credentialState === appleAuth.State.AUTHORIZED && appleAuthRequestResponse.identityToken && appleAuthRequestResponse.authorizationCode) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
provider: 'apple',
token: appleAuthRequestResponse.identityToken,
nonce: appleAuthRequestResponse.nonce,
access_token: appleAuthRequestResponse.authorizationCode,
};
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials);
if (error) {
console.error('Error signing in with Apple:', error);
}
if (data) {
console.log('Apple sign in successful:', data);
router.navigate('/(tabs)');
}
}
}
export default function AppleSignInButton() {
if (Platform.OS !== 'ios') { return <></>; }
return <AppleButton
buttonStyle={AppleButton.Style.BLACK}
buttonType={AppleButton.Type.SIGN_IN}
style={{ width: 160, height: 45 }}
onPress={() => onAppleButtonPress()}
/>;
}
@@ -0,0 +1,68 @@
import { supabase } from '@/lib/supabase';
import type { SignInWithIdTokenCredentials } from '@supabase/supabase-js';
import { useEffect, useState } from 'react';
import AppleSignin, { type AppleAuthResponse } from 'react-apple-signin-auth';
import { Platform } from 'react-native';
export default function AppleSignInButton() {
const [nonce, setNonce] = useState('');
const [sha256Nonce, setSha256Nonce] = useState('');
async function onAppleButtonSuccess(appleAuthRequestResponse: AppleAuthResponse) {
console.debug('Apple sign in successful:', { appleAuthRequestResponse });
if (appleAuthRequestResponse.authorization && appleAuthRequestResponse.authorization.id_token && appleAuthRequestResponse.authorization.code) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
provider: 'apple',
token: appleAuthRequestResponse.authorization.id_token,
nonce,
access_token: appleAuthRequestResponse.authorization.code,
};
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials)
if (error) {
console.error('Error signing in with Apple:', error);
}
if (data) {
console.log('Apple sign in successful:', data);
}
};
}
useEffect(() => {
function generateNonce(): string {
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return array[0].toString();
};
async function generateSha256Nonce(nonce: string): Promise<string> {
const buffer = await window.crypto.subtle.digest('sha-256', new TextEncoder().encode(nonce));
const array = Array.from(new Uint8Array(buffer));
return array.map(b => b.toString(16).padStart(2, '0')).join('');
}
let nonce = generateNonce();
setNonce(nonce);
generateSha256Nonce(nonce)
.then((sha256Nonce) => { setSha256Nonce(sha256Nonce) });
}, []);
if (Platform.OS !== 'web') { return <></>; }
return <AppleSignin
authOptions={{
clientId: process.env.EXPO_PUBLIC_APPLE_AUTH_SERVICE_ID ?? '',
redirectURI: process.env.EXPO_PUBLIC_APPLE_AUTH_REDIRECT_URI ?? '',
scope: 'email name',
state: 'state',
nonce: sha256Nonce,
usePopup: true,
}}
uiType="dark"
onSuccess={onAppleButtonSuccess}
onError={(error: any) => console.error('Apple sign in error:', error)}
/>;
}
@@ -0,0 +1,126 @@
import { supabase } from '@/lib/supabase';
import { useEffect } from 'react';
import { TouchableOpacity } from 'react-native';
import { expo } from '@/app.json';
import { Text } from '@react-navigation/elements';
import { Image } from 'expo-image';
import * as WebBrowser from "expo-web-browser";
WebBrowser.maybeCompleteAuthSession();
export default function GoogleSignInButton() {
function extractParamsFromUrl(url: string) {
const parsedUrl = new URL(url);
const hash = parsedUrl.hash.substring(1); // Remove the leading '#'
const params = new URLSearchParams(hash);
return {
access_token: params.get("access_token"),
expires_in: parseInt(params.get("expires_in") || "0"),
refresh_token: params.get("refresh_token"),
token_type: params.get("token_type"),
provider_token: params.get("provider_token"),
code: params.get("code"),
};
};
async function onSignInButtonPress() {
console.debug('onSignInButtonPress - start');
const res = await supabase.auth.signInWithOAuth({
provider: "google",
options: {
redirectTo: `${expo.scheme}://google-auth`,
queryParams: { prompt: "consent" },
skipBrowserRedirect: true,
},
});
const googleOAuthUrl = res.data.url;
if (!googleOAuthUrl) {
console.error("no oauth url found!");
return;
}
const result = await WebBrowser.openAuthSessionAsync(
googleOAuthUrl,
`${expo.scheme}://google-auth`,
{ showInRecents: true },
).catch((err) => {
console.error('onSignInButtonPress - openAuthSessionAsync - error', { err });
console.log(err);
});
console.debug('onSignInButtonPress - openAuthSessionAsync - result', { result });
if (result && result.type === "success") {
console.debug('onSignInButtonPress - openAuthSessionAsync - success');
const params = extractParamsFromUrl(result.url);
console.debug('onSignInButtonPress - openAuthSessionAsync - success', { params });
if (params.access_token && params.refresh_token) {
console.debug('onSignInButtonPress - setSession');
const { data, error } = await supabase.auth.setSession({
access_token: params.access_token,
refresh_token: params.refresh_token,
});
console.debug('onSignInButtonPress - setSession - success', { data, error });
return;
} else {
console.error('onSignInButtonPress - setSession - failed');
// sign in/up failed
}
} else {
console.error('onSignInButtonPress - openAuthSessionAsync - failed');
}
}
// to warm up the browser
useEffect(() => {
WebBrowser.warmUpAsync();
return () => {
WebBrowser.coolDownAsync();
};
}, []);
return (
<TouchableOpacity
onPress={onSignInButtonPress}
style={{
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#ffffff',
borderWidth: 1,
borderColor: '#dbdbdb',
borderRadius: 4,
paddingVertical: 10,
paddingHorizontal: 15,
justifyContent: 'center',
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 2, // For Android shadow
}}
activeOpacity={0.8}
>
<Image
source={{ uri: 'https://developers.google.com/identity/images/g-logo.png' }}
style={{ width: 24, height: 24, marginRight: 10 }}
/>
<Text
style={{
fontSize: 16,
color: '#757575',
fontFamily: 'Roboto-Regular', // Assuming Roboto is available; install via expo-google-fonts or similar if needed
fontWeight: '500',
}}
>
Sign in with Google
</Text>
</TouchableOpacity>
);
}
@@ -0,0 +1,73 @@
import { supabase } from '@/lib/supabase';
import { CredentialResponse, GoogleLogin, GoogleOAuthProvider } from '@react-oauth/google';
import { SignInWithIdTokenCredentials } from '@supabase/supabase-js';
import { useEffect, useState } from 'react';
import 'react-native-get-random-values';
export default function GoogleSignInButton() {
// Generate secure, random values for state and nonce
const [nonce, setNonce] = useState('');
const [sha256Nonce, setSha256Nonce] = useState('');
async function onGoogleButtonSuccess(authRequestResponse: CredentialResponse) {
console.debug('Google sign in successful:', { authRequestResponse });
if (authRequestResponse.clientId && authRequestResponse.credential) {
const signInWithIdTokenCredentials: SignInWithIdTokenCredentials = {
provider: 'google',
token: authRequestResponse.credential,
nonce: nonce,
};
const { data, error } = await supabase.auth.signInWithIdToken(signInWithIdTokenCredentials);
if (error) {
console.error('Error signing in with Google:', error);
}
if (data) {
console.log('Google sign in successful:', data);
}
}
}
function onGoogleButtonFailure() {
console.error('Error signing in with Google');
}
useEffect(() => {
function generateNonce(): string {
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return array[0].toString();
}
async function generateSha256Nonce(nonce: string): Promise<string> {
const buffer = await window.crypto.subtle.digest('sha-256', new TextEncoder().encode(nonce));
const array = Array.from(new Uint8Array(buffer));
return array.map(b => b.toString(16).padStart(2, '0')).join('');
}
let nonce = generateNonce();
setNonce(nonce);
generateSha256Nonce(nonce)
.then((sha256Nonce) => { setSha256Nonce(sha256Nonce) });
}, []);
return (
<GoogleOAuthProvider
clientId={process.env.EXPO_PUBLIC_GOOGLE_AUTH_WEB_CLIENT_ID ?? ''}
nonce={sha256Nonce}
>
<GoogleLogin
nonce={sha256Nonce}
onSuccess={onGoogleButtonSuccess}
onError={onGoogleButtonFailure}
useOneTap={true}
auto_select={true}
/>
</GoogleOAuthProvider>
);
}
@@ -0,0 +1,15 @@
import { supabase } from '@/lib/supabase'
import React from 'react'
import { Button } from 'react-native'
async function onSignOutButtonPress() {
const { error } = await supabase.auth.signOut()
if (error) {
console.error('Error signing out:', error)
}
}
export default function SignOutButton() {
return <Button title="Sign out" onPress={onSignOutButtonPress} />
}
@@ -0,0 +1,14 @@
import { useAuthContext } from '@/hooks/use-auth-context'
import { SplashScreen } from 'expo-router'
SplashScreen.preventAutoHideAsync()
export function SplashScreenController() {
const { isLoading } = useAuthContext()
if (!isLoading) {
SplashScreen.hideAsync()
}
return null
}
@@ -0,0 +1,61 @@
import { Text, type TextProps, StyleSheet } from 'react-native';
import { useThemeColor } from '@/hooks/use-theme-color';
import { Fonts } from '@/constants/theme';
export type ThemedTextProps = TextProps & {
lightColor?: string;
darkColor?: string;
type?: 'default' | 'title' | 'defaultSemiBold' | 'subtitle' | 'link';
};
export function ThemedText({
style,
lightColor,
darkColor,
type = 'default',
...rest
}: ThemedTextProps) {
const color = useThemeColor({ light: lightColor, dark: darkColor }, 'text');
return (
<Text
style={[
{ color, fontFamily: Fonts?.sans },
type === 'default' ? styles.default : undefined,
type === 'title' ? styles.title : undefined,
type === 'defaultSemiBold' ? styles.defaultSemiBold : undefined,
type === 'subtitle' ? styles.subtitle : undefined,
type === 'link' ? styles.link : undefined,
style,
]}
{...rest}
/>
);
}
const styles = StyleSheet.create({
default: {
fontSize: 16,
lineHeight: 24,
},
defaultSemiBold: {
fontSize: 16,
lineHeight: 24,
fontWeight: '600',
},
title: {
fontSize: 32,
fontWeight: 'bold',
lineHeight: 32,
},
subtitle: {
fontSize: 20,
fontWeight: 'bold',
},
link: {
lineHeight: 30,
fontSize: 16,
color: '#0a7ea4',
},
});
@@ -0,0 +1,14 @@
import { View, type ViewProps } from 'react-native';
import { useThemeColor } from '@/hooks/use-theme-color';
export type ThemedViewProps = ViewProps & {
lightColor?: string;
darkColor?: string;
};
export function ThemedView({ style, lightColor, darkColor, ...otherProps }: ThemedViewProps) {
const backgroundColor = useThemeColor({ light: lightColor, dark: darkColor }, 'background');
return <View style={[{ backgroundColor }, style]} {...otherProps} />;
}
@@ -0,0 +1,53 @@
/**
* Below are the colors that are used in the app. The colors are defined in the light and dark mode.
* There are many other ways to style your app. For example, [Nativewind](https://www.nativewind.dev/), [Tamagui](https://tamagui.dev/), [unistyles](https://reactnativeunistyles.vercel.app), etc.
*/
import { Platform } from 'react-native';
const tintColorLight = '#0a7ea4';
const tintColorDark = '#fff';
export const Colors = {
light: {
text: '#11181C',
background: '#fff',
tint: tintColorLight,
icon: '#687076',
tabIconDefault: '#687076',
tabIconSelected: tintColorLight,
},
dark: {
text: '#ECEDEE',
background: '#151718',
tint: tintColorDark,
icon: '#9BA1A6',
tabIconDefault: '#9BA1A6',
tabIconSelected: tintColorDark,
},
};
export const Fonts = Platform.select({
ios: {
/** iOS `UIFontDescriptorSystemDesignDefault` */
sans: 'system-ui',
/** iOS `UIFontDescriptorSystemDesignSerif` */
serif: 'ui-serif',
/** iOS `UIFontDescriptorSystemDesignRounded` */
rounded: 'ui-rounded',
/** iOS `UIFontDescriptorSystemDesignMonospaced` */
mono: 'ui-monospace',
},
default: {
sans: 'normal',
serif: 'serif',
rounded: 'normal',
mono: 'monospace',
},
web: {
sans: "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",
serif: "Georgia, 'Times New Roman', serif",
rounded: "'SF Pro Rounded', 'Hiragino Maru Gothic ProN', Meiryo, 'MS PGothic', sans-serif",
mono: "SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",
},
});
@@ -0,0 +1,10 @@
// https://docs.expo.dev/guides/using-eslint/
const { defineConfig } = require('eslint/config');
const expoConfig = require('eslint-config-expo/flat');
module.exports = defineConfig([
expoConfig,
{
ignores: ['dist/*'],
},
]);
@@ -0,0 +1,17 @@
import { createContext, useContext } from 'react'
export type AuthData = {
claims?: Record<string, any> | null
profile?: any | null
isLoading: boolean
isLoggedIn: boolean
}
export const AuthContext = createContext<AuthData>({
claims: undefined,
profile: undefined,
isLoading: true,
isLoggedIn: false,
})
export const useAuthContext = () => useContext(AuthContext)
@@ -0,0 +1 @@
export { useColorScheme } from 'react-native';
@@ -0,0 +1,21 @@
import { useEffect, useState } from 'react';
import { useColorScheme as useRNColorScheme } from 'react-native';
/**
* To support static rendering, this value needs to be re-calculated on the client side for web
*/
export function useColorScheme() {
const [hasHydrated, setHasHydrated] = useState(false);
useEffect(() => {
setHasHydrated(true);
}, []);
const colorScheme = useRNColorScheme();
if (hasHydrated) {
return colorScheme;
}
return 'light';
}
@@ -0,0 +1,21 @@
/**
* Learn more about light and dark modes:
* https://docs.expo.dev/guides/color-schemes/
*/
import { Colors } from '@/constants/theme';
import { useColorScheme } from '@/hooks/use-color-scheme';
export function useThemeColor(
props: { light?: string; dark?: string },
colorName: keyof typeof Colors.light & keyof typeof Colors.dark
) {
const theme = useColorScheme() ?? 'light';
const colorFromProps = props[theme];
if (colorFromProps) {
return colorFromProps;
} else {
return Colors[theme][colorName];
}
}
@@ -0,0 +1,31 @@
import { createClient } from '@supabase/supabase-js';
import { deleteItemAsync, getItemAsync, setItemAsync } from 'expo-secure-store';
const ExpoSecureStoreAdapter = {
getItem: (key: string) => {
console.debug("getItem", { key, getItemAsync })
return getItemAsync(key)
},
setItem: (key: string, value: string) => {
if (value.length > 2048) {
console.warn('Value being stored in SecureStore is larger than 2048 bytes and it may not be stored successfully. In a future SDK version, this call may throw an error.')
}
return setItemAsync(key, value)
},
removeItem: (key: string) => {
return deleteItemAsync(key)
},
};
export const supabase = createClient(
process.env.EXPO_PUBLIC_SUPABASE_URL ?? '',
process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY ?? '',
{
auth: {
storage: ExpoSecureStoreAdapter as any,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false,
},
},
);
@@ -0,0 +1,34 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createClient } from '@supabase/supabase-js';
import 'react-native-url-polyfill/auto';
const isSSR = typeof window === 'undefined';
const ExpoWebSecureStoreAdapter = {
getItem: (key: string) => {
if (isSSR) return null;
console.debug("getItem", { key })
return AsyncStorage.getItem(key)
},
setItem: (key: string, value: string) => {
if (isSSR) return;
return AsyncStorage.setItem(key, value)
},
removeItem: (key: string) => {
if (isSSR) return;
return AsyncStorage.removeItem(key)
},
};
export const supabase = createClient(
process.env.EXPO_PUBLIC_SUPABASE_URL ?? '',
process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY ?? '',
{
auth: {
storage: ExpoWebSecureStoreAdapter,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false,
},
},
);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,56 @@
{
"name": "ff",
"main": "expo-router/entry",
"version": "1.0.0",
"scripts": {
"start": "expo start",
"reset-project": "node ./scripts/reset-project.js",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"lint": "expo lint"
},
"dependencies": {
"@expo/vector-icons": "^15.0.3",
"@invertase/react-native-apple-authentication": "^2.5.1",
"@react-native-async-storage/async-storage": "2.2.0",
"@react-navigation/bottom-tabs": "^7.4.0",
"@react-navigation/elements": "^2.6.3",
"@react-navigation/native": "^7.1.8",
"@react-oauth/google": "^0.13.4",
"@supabase/supabase-js": "^2.94.0",
"expo": "~54.0.33",
"expo-constants": "~18.0.13",
"expo-font": "~14.0.11",
"expo-haptics": "~15.0.8",
"expo-image": "~3.0.11",
"expo-linking": "~8.0.11",
"expo-router": "~6.0.23",
"expo-secure-store": "~15.0.8",
"expo-splash-screen": "~31.0.13",
"expo-status-bar": "~3.0.9",
"expo-symbols": "~1.0.8",
"expo-system-ui": "~6.0.9",
"expo-web-browser": "~15.0.10",
"react": "19.1.0",
"react-apple-signin-auth": "^1.1.2",
"react-dom": "19.1.0",
"react-native": "0.81.5",
"react-native-gesture-handler": "~2.28.0",
"react-native-get-random-values": "~1.11.0",
"react-native-reanimated": "~4.1.1",
"react-native-safe-area-context": "~5.6.0",
"react-native-screens": "~4.16.0",
"react-native-url-polyfill": "^3.0.0",
"react-native-web": "~0.21.0",
"react-native-worklets": "0.5.1"
},
"devDependencies": {
"@types/react": "~19.1.0",
"@types/uuid": "^10.0.0",
"eslint": "^9.25.0",
"eslint-config-expo": "~10.0.0",
"typescript": "~5.9.2"
},
"private": true
}
@@ -0,0 +1,77 @@
import { AuthContext } from '@/hooks/use-auth-context'
import { supabase } from '@/lib/supabase'
import { PropsWithChildren, useEffect, useState } from 'react'
export default function AuthProvider({ children }: PropsWithChildren) {
const [claims, setClaims] = useState<Record<string, any> | undefined | null>()
const [profile, setProfile] = useState<any>()
const [isLoading, setIsLoading] = useState<boolean>(true)
// Fetch the claims once, and subscribe to auth state changes
useEffect(() => {
const fetchClaims = async () => {
setIsLoading(true)
const { data, error } = await supabase.auth.getClaims()
if (error) {
console.error('Error fetching claims:', error)
}
setClaims(data?.claims ?? null)
setIsLoading(false)
}
fetchClaims()
const {
data: { subscription },
} = supabase.auth.onAuthStateChange(async (_event, session) => {
const { data } = session
? await supabase.auth.getClaims(session.access_token)
: { data: null }
setClaims(data?.claims ?? null)
})
// Cleanup subscription on unmount
return () => {
subscription.unsubscribe()
}
}, [])
// Fetch the profile when the claims change
useEffect(() => {
const fetchProfile = async () => {
setIsLoading(true)
if (claims) {
const { data } = await supabase
.from('profiles')
.select('*')
.eq('id', claims.sub)
.single()
setProfile(data)
} else {
setProfile(null)
}
setIsLoading(false)
}
fetchProfile()
}, [claims])
return (
<AuthContext.Provider
value={{
claims,
isLoading,
profile,
isLoggedIn: claims != undefined,
}}
>
{children}
</AuthContext.Provider>
)
}
@@ -0,0 +1,17 @@
{
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true,
"paths": {
"@/*": [
"./*"
]
}
},
"include": [
"**/*.ts",
"**/*.tsx",
".expo/types/**/*.ts",
"expo-env.d.ts"
]
}