OAuth implemented

This commit is contained in:
Sanidhya Kumar Verma
2024-09-04 11:38:47 +00:00
committed by GitHub
parent 8cb07ae079
commit 1f0ecd696d
2 changed files with 88 additions and 3 deletions
+24 -3
View File
@@ -1,15 +1,36 @@
import { Image, Text, View } from "react-native";
import { useOAuth } from "@clerk/clerk-expo";
import { useCallback } from "react";
import { Alert, Image, Text, View } from "react-native";
import { icons } from "@/constants";
import { CustomButton } from "./custom-button";
import { googleOAuth } from "@/lib/auth";
import { router } from "expo-router";
type OAuthProps = {
title: string;
};
export const OAuth = ({ title }: OAuthProps) => {
const handleGoogleSignIn = () => {};
const { startOAuthFlow } = useOAuth({ strategy: "oauth_google" });
const handleGoogleOAuth = useCallback(async () => {
try {
const result = await googleOAuth(startOAuthFlow);
if (result?.code === "session_exists") {
router.replace("/(root)/(tabs)/home");
}
Alert.alert(
result?.success ? "Success" : "Error",
result?.message || "You are Logged In!",
);
} catch (err) {
console.error("OAuth error", err);
}
}, [startOAuthFlow]);
return (
<View>
@@ -34,7 +55,7 @@ export const OAuth = ({ title }: OAuthProps) => {
)}
bgVariant="outline"
textVariant="primary"
onPress={handleGoogleSignIn}
onPress={handleGoogleOAuth}
/>
</View>
);
+64
View File
@@ -1,5 +1,12 @@
import type {
StartOAuthFlowParams,
StartOAuthFlowReturnType,
} from "@clerk/clerk-expo";
import * as Linking from "expo-linking";
import * as SecureStore from "expo-secure-store";
import { fetchAPI } from "./fetch";
export interface TokenCache {
getToken: (key: string) => Promise<string | undefined | null>;
saveToken: (key: string, token: string) => Promise<void>;
@@ -32,3 +39,60 @@ export const tokenCache = {
}
},
};
type StartOAuthFlowType = (
startOAuthFlowParams?: StartOAuthFlowParams,
) => Promise<StartOAuthFlowReturnType>;
export const googleOAuth = async (startOAuthFlow: StartOAuthFlowType) => {
try {
const { createdSessionId, signUp, setActive } = await startOAuthFlow({
redirectUrl: Linking.createURL("/(root)/(tabs)/home", {
scheme: "ryde", // match with scheme in app.json
}),
});
if (createdSessionId) {
if (setActive) {
await setActive!({ session: createdSessionId });
if (signUp && signUp.createdUserId) {
await fetchAPI("/(api)/user", {
method: "POST",
body: JSON.stringify({
name: `${signUp.firstName} ${signUp.lastName}`,
email: signUp.emailAddress,
clerkId: signUp.createdUserId,
}),
});
}
return {
success: true,
code: "success",
message: "You are logged in.",
};
}
return {
success: false,
code: "failed",
message: "An error occured.",
};
} else {
// Use signIn or signUp for next steps such as MFA
}
} catch (err) {
console.log("[OAUTH]: ", err);
return {
success: false,
code: (
err as {
code?: string;
}
)?.code,
message: "Internal Server Error.",
};
}
};