Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(mobile): add Apple auth and extend sign-in panel

Richie McIlroy1709166e2476
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index 9c97d7ec2..7c4902a5b 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -24,6 +24,9 @@ WebBrowser.maybeCompleteAuthSession();
const sessionKey = "cap.mobile.apiKey";
const userIdKey = "cap.mobile.userId";
+const secureStoreOptions: SecureStore.SecureStoreOptions = {
+ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
+};
type AuthState = {
status: "loading" | "signedOut" | "signedIn";
@@ -34,6 +37,7 @@ type AuthState = {
client: MobileApiClient;
requestEmailCode: (email: string) => Promise<void>;
verifyEmailCode: (email: string, code: string) => Promise<void>;
+ signInWithApple: () => Promise<void>;
signInWithGoogle: () => Promise<void>;
signInWithSso: (organizationId: string) => Promise<void>;
signOut: () => Promise<void>;
@@ -43,6 +47,7 @@ type AuthState = {
const AuthContext = createContext<AuthState | null>(null);
const fallbackAuthConfig: MobileAuthConfigResponse = {
+ appleAuthAvailable: false,
googleAuthAvailable: true,
workosAuthAvailable: true,
};
@@ -132,9 +137,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const storeSession = useCallback(
async (session: { apiKey: string; userId: string | null }) => {
- await SecureStore.setItemAsync(sessionKey, session.apiKey);
+ await SecureStore.setItemAsync(
+ sessionKey,
+ session.apiKey,
+ secureStoreOptions,
+ );
if (session.userId) {
- await SecureStore.setItemAsync(userIdKey, session.userId);
+ await SecureStore.setItemAsync(
+ userIdKey,
+ session.userId,
+ secureStoreOptions,
+ );
} else {
await SecureStore.deleteItemAsync(userIdKey);
}
@@ -162,16 +175,29 @@ export function AuthProvider({ children }: { children: ReactNode }) {
[client, storeSession],
);
- const signInWithGoogle = useCallback(async () => {
- const redirectUri = Linking.createURL("auth");
- const result = await WebBrowser.openAuthSessionAsync(
- createSessionRequestUrl(apiBaseUrl, redirectUri, "google"),
- redirectUri,
- );
- if (result.type !== "success") return;
+ const signInWithProvider = useCallback(
+ async (provider: "apple" | "google") => {
+ const redirectUri = Linking.createURL("auth");
+ const result = await WebBrowser.openAuthSessionAsync(
+ createSessionRequestUrl(apiBaseUrl, redirectUri, provider),
+ redirectUri,
+ );
+ if (result.type !== "success") return;
- await storeSession(requireAuthRedirectSession(result.url));
- }, [storeSession]);
+ await storeSession(requireAuthRedirectSession(result.url));
+ },
+ [storeSession],
+ );
+
+ const signInWithApple = useCallback(
+ () => signInWithProvider("apple"),
+ [signInWithProvider],
+ );
+
+ const signInWithGoogle = useCallback(
+ () => signInWithProvider("google"),
+ [signInWithProvider],
+ );
const signInWithSso = useCallback(
async (organizationId: string) => {
@@ -223,6 +249,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
client,
requestEmailCode,
verifyEmailCode,
+ signInWithApple,
signInWithGoogle,
signInWithSso,
signOut,
@@ -238,6 +265,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
client,
requestEmailCode,
verifyEmailCode,
+ signInWithApple,
signInWithGoogle,
signInWithSso,
signOut,
diff --git a/apps/mobile/src/auth/SignInPanel.tsx b/apps/mobile/src/auth/SignInPanel.tsx
index 27f6f3eae..1a57ad267 100644
--- a/apps/mobile/src/auth/SignInPanel.tsx
+++ b/apps/mobile/src/auth/SignInPanel.tsx
@@ -1,3 +1,4 @@
+import * as AppleAuthentication from "expo-apple-authentication";
import { SymbolView } from "expo-symbols";
import * as WebBrowser from "expo-web-browser";
import { useEffect, useRef, useState } from "react";
@@ -20,7 +21,7 @@ const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const emailCodeCooldownMs = 30_000;
const codeSlots = ["code-0", "code-1", "code-2", "code-3", "code-4", "code-5"];
type FocusedInput = "code" | "email" | "sso" | null;
-type LoadingKind = "email" | "code" | "google" | "sso";
+type LoadingKind = "apple" | "email" | "code" | "google" | "sso";
type SignInError = {
message: string;
source: LoadingKind | "resend";
@@ -99,6 +100,8 @@ export function SignInPanel({
const [focusedInput, setFocusedInput] = useState<FocusedInput>(null);
const [loading, setLoading] = useState<LoadingKind | null>(null);
const [error, setError] = useState<SignInError | null>(null);
+ const [appleAuthenticationAvailable, setAppleAuthenticationAvailable] =
+ useState(false);
const normalizedEmail = email.trim().toLowerCase();
const normalizedOrganizationId = organizationId.trim();
@@ -119,14 +122,18 @@ export function SignInPanel({
const canStartSso = isSsoReady && loading === null;
const isCodeStep = codeSent && !showSso;
const showBackButton = showSso || isCodeStep;
+ const showApple =
+ auth.authConfig.appleAuthAvailable && appleAuthenticationAvailable;
const showGoogle = auth.authConfig.googleAuthAvailable;
const showSaml = auth.authConfig.workosAuthAvailable;
- const showProviderOptions = showGoogle || showSaml;
+ const showProviderOptions = showApple || showGoogle || showSaml;
const errorMessage = error?.message ?? null;
const emailInputHasError =
error?.source === "email" && !showSso && !isCodeStep;
const ssoInputHasError = error?.source === "sso" && showSso;
const codeEntryHasError = error?.source === "code" && isCodeStep;
+ const appleActionHasError =
+ error?.source === "apple" && !showSso && !isCodeStep;
const googleActionHasError =
error?.source === "google" && !showSso && !isCodeStep;
const ssoActionHasError = error?.source === "sso" && showSso;
@@ -161,11 +168,13 @@ export function SignInPanel({
? "Sending verification code"
: loading === "code"
? "Verifying code"
- : loading === "google"
- ? "Starting Google sign in"
- : loading === "sso"
- ? "Starting SAML SSO sign in"
- : null;
+ : loading === "apple"
+ ? "Starting Apple sign in"
+ : loading === "google"
+ ? "Starting Google sign in"
+ : loading === "sso"
+ ? "Starting SAML SSO sign in"
+ : null;
const activeSignInAccessibilityValue = activeSignInAccessibilityText
? { text: activeSignInAccessibilityText }
: undefined;
@@ -185,6 +194,14 @@ export function SignInPanel({
: isCodeStep
? { text: `${code.length} of 6 digits entered` }
: undefined;
+ const appleButtonAccessibilityValue =
+ loading === "apple"
+ ? activeSignInAccessibilityValue
+ : appleActionHasError && errorMessage
+ ? { text: errorMessage }
+ : loading !== null
+ ? activeSignInAccessibilityValue
+ : undefined;
const googleButtonAccessibilityValue =
loading === "google"
? activeSignInAccessibilityValue
@@ -251,6 +268,14 @@ export function SignInPanel({
: !isCodeReady
? "Enter the 6-digit code to continue"
: "Verifies the 6-digit code";
+ const appleButtonHint =
+ loading === "apple"
+ ? "Apple sign in is starting"
+ : loading !== null
+ ? "Sign in is in progress"
+ : appleActionHasError && errorMessage
+ ? errorMessage
+ : "Starts Apple sign in";
const googleButtonHint =
loading === "google"
? "Google sign in is starting"
@@ -328,6 +353,27 @@ export function SignInPanel({
return () => clearInterval(interval);
}, [isCodeRequestCoolingDown]);
+ useEffect(() => {
+ let active = true;
+ if (!auth.authConfig.appleAuthAvailable) {
+ setAppleAuthenticationAvailable(false);
+ return () => {
+ active = false;
+ };
+ }
+ void AppleAuthentication.isAvailableAsync().then(
+ (available) => {
+ if (active) setAppleAuthenticationAvailable(available);
+ },
+ () => {
+ if (active) setAppleAuthenticationAvailable(false);
+ },
+ );
+ return () => {
+ active = false;
+ };
+ }, [auth.authConfig.appleAuthAvailable]);
+
const goBack = () => {
if (isAuthBusy()) return;
if (showSso) setShowSso(false);
@@ -423,6 +469,24 @@ export function SignInPanel({
openWebPath(path);
};
+ const signInWithApple = async () => {
+ if (!beginLoading("apple")) return;
+ setError(null);
+ try {
+ await auth.signInWithApple();
+ } catch (appleError) {
+ setError({
+ message: getProviderErrorMessage(
+ appleError,
+ "Unable to start Apple sign in.",
+ ),
+ source: "apple",
+ });
+ } finally {
+ endLoading();
+ }
+ };
+
const signInWithGoogle = async () => {
if (!beginLoading("google")) return;
setError(null);
@@ -740,6 +804,36 @@ export function SignInPanel({
<Text style={styles.dividerText}>OR</Text>
<View style={styles.divider} />
</View>
+ {showApple ? (
+ <View
+ pointerEvents={loading === null ? "auto" : "none"}
+ style={[
+ styles.appleButtonContainer,
+ loading !== null && styles.appleButtonDisabled,
+ ]}
+ >
+ <AppleAuthentication.AppleAuthenticationButton
+ accessibilityLabel="Sign in with Apple"
+ accessibilityHint={appleButtonHint}
+ accessibilityState={{
+ busy: loading === "apple",
+ disabled: loading !== null,
+ }}
+ accessibilityValue={appleButtonAccessibilityValue}
+ buttonType={
+ AppleAuthentication.AppleAuthenticationButtonType
+ .SIGN_IN
+ }
+ buttonStyle={
+ AppleAuthentication.AppleAuthenticationButtonStyle
+ .BLACK
+ }
+ cornerRadius={radius.md}
+ onPress={signInWithApple}
+ style={styles.appleButton}
+ />
+ </View>
+ ) : null}
{showGoogle ? (
<ActionButton
label={googleButtonLabel}
@@ -887,6 +981,16 @@ const styles = StyleSheet.create({
formStack: {
gap: 12,
},
+ appleButtonContainer: {
+ width: "100%",
+ },
+ appleButtonDisabled: {
+ opacity: 0.6,
+ },
+ appleButton: {
+ width: "100%",
+ height: 44,
+ },
input: {
minHeight: 44,
borderRadius: radius.md,