mobile-auth-patterns
Mobile authentication patterns with Clerk, Supabase, and custom auth including biometrics, secure storage, and social login. Use when implementing authentication, managing tokens, or setting up biometric unlock.
What this skill does
# Mobile Auth Patterns
Comprehensive skill for implementing authentication in React Native/Expo mobile apps.
## Overview
Mobile authentication requires special considerations:
- Secure token storage (not AsyncStorage)
- Biometric authentication for quick access
- Social login providers (Apple, Google)
- Session management across app states
- Refresh token handling
## Use When
This skill is automatically invoked when:
- Setting up authentication flows
- Implementing biometric unlock
- Integrating social login providers
- Managing secure token storage
- Handling session persistence
## Auth Provider Templates
### Clerk Integration
```typescript
// providers/ClerkProvider.tsx
import { ClerkProvider, useAuth } from '@clerk/clerk-expo';
import * as SecureStore from 'expo-secure-store';
const tokenCache = {
async getToken(key: string) {
return await SecureStore.getItemAsync(key);
},
async saveToken(key: string, value: string) {
await SecureStore.setItemAsync(key, value);
},
async clearToken(key: string) {
await SecureStore.deleteItemAsync(key);
},
};
export function AuthProvider({ children }: { children: React.ReactNode }) {
const publishableKey = process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY!;
return (
<ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
{children}
</ClerkProvider>
);
}
// hooks/useAuthenticatedUser.ts
import { useUser, useAuth } from '@clerk/clerk-expo';
export function useAuthenticatedUser() {
const { user, isLoaded } = useUser();
const { isSignedIn, signOut, getToken } = useAuth();
return {
user,
isLoaded,
isSignedIn,
signOut,
getToken,
fullName: user?.fullName,
email: user?.primaryEmailAddress?.emailAddress,
avatar: user?.imageUrl,
};
}
```
### Supabase Auth
```typescript
// lib/supabase.ts
import 'react-native-url-polyfill/auto';
import { createClient } from '@supabase/supabase-js';
import * as SecureStore from 'expo-secure-store';
import { Platform } from 'react-native';
const ExpoSecureStoreAdapter = {
getItem: async (key: string) => {
return await SecureStore.getItemAsync(key);
},
setItem: async (key: string, value: string) => {
await SecureStore.setItemAsync(key, value);
},
removeItem: async (key: string) => {
await SecureStore.deleteItemAsync(key);
},
};
const supabaseUrl = process.env.EXPO_PUBLIC_SUPABASE_URL!;
const supabaseAnonKey = process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY!;
export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
auth: {
storage: ExpoSecureStoreAdapter,
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: false,
},
});
// hooks/useSupabaseAuth.ts
import { useEffect, useState } from 'react';
import { supabase } from '@/lib/supabase';
import { Session, User } from '@supabase/supabase-js';
export function useSupabaseAuth() {
const [session, setSession] = useState<Session | null>(null);
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Get initial session
supabase.auth.getSession().then(({ data: { session } }) => {
setSession(session);
setUser(session?.user ?? null);
setIsLoading(false);
});
// Listen for auth changes
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event, session) => {
setSession(session);
setUser(session?.user ?? null);
});
return () => subscription.unsubscribe();
}, []);
const signIn = async (email: string, password: string) => {
const { error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) throw error;
};
const signUp = async (email: string, password: string) => {
const { error } = await supabase.auth.signUp({ email, password });
if (error) throw error;
};
const signOut = async () => {
const { error } = await supabase.auth.signOut();
if (error) throw error;
};
return {
session,
user,
isLoading,
isAuthenticated: !!session,
signIn,
signUp,
signOut,
};
}
```
### Biometric Authentication
```typescript
// lib/biometrics.ts
import * as LocalAuthentication from 'expo-local-authentication';
import * as SecureStore from 'expo-secure-store';
export interface BiometricCapabilities {
isAvailable: boolean;
biometryType: 'fingerprint' | 'face' | 'iris' | null;
isEnrolled: boolean;
}
export async function getBiometricCapabilities(): Promise<BiometricCapabilities> {
const hasHardware = await LocalAuthentication.hasHardwareAsync();
const isEnrolled = await LocalAuthentication.isEnrolledAsync();
const supportedTypes =
await LocalAuthentication.supportedAuthenticationTypesAsync();
let biometryType: BiometricCapabilities['biometryType'] = null;
if (
supportedTypes.includes(
LocalAuthentication.AuthenticationType.FACIAL_RECOGNITION
)
) {
biometryType = 'face';
} else if (
supportedTypes.includes(LocalAuthentication.AuthenticationType.FINGERPRINT)
) {
biometryType = 'fingerprint';
} else if (
supportedTypes.includes(LocalAuthentication.AuthenticationType.IRIS)
) {
biometryType = 'iris';
}
return {
isAvailable: hasHardware && isEnrolled,
biometryType,
isEnrolled,
};
}
export async function authenticateWithBiometrics(
promptMessage = 'Authenticate to continue'
): Promise<boolean> {
try {
const result = await LocalAuthentication.authenticateAsync({
promptMessage,
cancelLabel: 'Cancel',
disableDeviceFallback: false,
fallbackLabel: 'Use passcode',
});
return result.success;
} catch (error) {
console.error('Biometric authentication error:', error);
return false;
}
}
// Biometric-protected secure storage
export const BiometricSecureStore = {
async setItem(key: string, value: string): Promise<void> {
await SecureStore.setItemAsync(key, value, {
requireAuthentication: true,
authenticationPrompt: 'Authenticate to save credentials',
});
},
async getItem(key: string): Promise<string | null> {
try {
return await SecureStore.getItemAsync(key, {
requireAuthentication: true,
authenticationPrompt: 'Authenticate to access credentials',
});
} catch {
return null;
}
},
};
```
### Social Login (Apple & Google)
```typescript
// lib/socialAuth.ts
import * as AppleAuthentication from 'expo-apple-authentication';
import * as Google from 'expo-auth-session/providers/google';
import { supabase } from './supabase';
// Apple Sign In
export async function signInWithApple() {
try {
const credential = await AppleAuthentication.signInAsync({
requestedScopes: [
AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
AppleAuthentication.AppleAuthenticationScope.EMAIL,
],
});
if (credential.identityToken) {
const { data, error } = await supabase.auth.signInWithIdToken({
provider: 'apple',
token: credential.identityToken,
});
if (error) throw error;
return data;
}
} catch (e: any) {
if (e.code === 'ERR_REQUEST_CANCELED') {
// User cancelled
return null;
}
throw e;
}
}
// Google Sign In (with Clerk)
import { useOAuth } from '@clerk/clerk-expo';
import * as WebBrowser from 'expo-web-browser';
import * as Linking from 'expo-linking';
WebBrowser.maybeCompleteAuthSession();
export function useGoogleAuth() {
const { startOAuthFlow } = useOAuth({ strategy: 'oauth_google' });
const signInWithGoogle = async () => {
try {
const { createdSessionId, setActive } = await startOAuthFlow({
redirectUrl: Linking.createURL('/oauth-callback'),
});
if (createdSessionId && setActive) {
await setActive({ session: createdSessionId });
return true;
}
return false;
} catch (error) {
consoRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.