Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(clerk-expo): Add LocalAuth and LocalAuthCredentials #3629

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/expo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,18 @@
"@types/react-dom": "*",
"expo-auth-session": "^5.4.0",
"expo-web-browser": "^12.8.2",
"expo-local-authentication": "^14.0.1",
"react-native": "^0.74.2",
"react-native-mmkv": "^2.12.2",
"typescript": "*"
},
"peerDependencies": {
"expo-local-authentication": ">=14",
"expo-auth-session": ">=4",
"expo-web-browser": ">=12.5.0",
"react": ">=18",
"react-native-mmkv": ">=2.12",
"react-native": ">=0.74",
"react-dom": ">=18"
},
"engines": {
Expand Down
15 changes: 14 additions & 1 deletion packages/expo/src/ClerkProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,28 @@ import { ClerkProvider as ClerkReactProvider } from '@clerk/clerk-react';
import React from 'react';

import type { TokenCache } from './cache';
// import { LocalAuthProvider } from './experimental/LocalAuth';
import { isReactNative } from './runtime';
import { getClerkInstance } from './singleton';

export type ClerkProviderProps = ClerkReactProviderProps & {
tokenCache?: TokenCache;
// localAuth?: {
// lockTimeout?: number;
// inactiveScreen?: React.ReactNode;
// onLockTimeOutReached?: () => void;
// lockTimeOutScreen?: React.FunctionComponent<{ authenticateWithBiometrics: () => Promise<boolean> }>;
// };
};

export function ClerkProvider(props: ClerkProviderProps): JSX.Element {
const { children, tokenCache, publishableKey, ...rest } = props;
const {
children,
tokenCache,
publishableKey,
// localAuth,
...rest
} = props;
const pk = publishableKey || process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY || process.env.CLERK_PUBLISHABLE_KEY || '';

return (
Expand Down
142 changes: 142 additions & 0 deletions packages/expo/src/experimental/LocalAuth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import type { UserResource } from '@clerk/types';
import * as LocalAuthentication from 'expo-local-authentication';
import type { PropsWithChildren } from 'react';
import React, { createContext, useCallback, useEffect, useRef, useState } from 'react';
// eslint-disable-next-line import/namespace
import { AppState } from 'react-native';
import { MMKV } from 'react-native-mmkv';

import { getClerkInstance } from '../singleton';

export const UserInactivityStore = new MMKV({
id: 'UserInactivity',
});

// Utility type to check if a type is a function
type IsFunction<T> = T extends (...args: any[]) => any ? true : false;

// Main utility type to exclude function properties
type ExcludeFunctions<T> = {
[K in keyof T]: IsFunction<T[K]> extends true ? never : T[K];
};

export const UserInactivityContext = createContext<{
localAuthUser: ExcludeFunctions<UserResource> | null;
}>({
localAuthUser: null,
});

type LocalAuthProviderProps = {
lockTimeout?: number;
// onLockTimeOutReached?: () => void;
// inactiveScreen?: React.ReactNode;
lockTimeOutScreen?: React.FunctionComponent<{
authenticateWithBiometrics: () => Promise<boolean>;
localAuthUser: ExcludeFunctions<UserResource>;
}>;
};
// export const useUserInactivity = () => useContext(UserInactivityContext);

export function LocalAuthProvider(props: PropsWithChildren<LocalAuthProviderProps>): JSX.Element {
const {
children,
lockTimeout = 1000 * 10,
// onLockTimeOutReached,
lockTimeOutScreen: LockTimeOutScreen,
} = props;
const lockTimeoutRef = useRef(lockTimeout);
// const onLockTimeOutReachedRef = useRef(onLockTimeOutReached);
const appState = useRef(AppState.currentState);
const [localUser, setLocalUser] = useState<ExcludeFunctions<UserResource> | null>(null);
const getElapsed = useCallback(() => {
const hasUser = !!JSON.parse(UserInactivityStore.getString('user') || '')?.id;
const elapsed = Date.now() - (UserInactivityStore.getNumber('startTime') || 0);

if (!hasUser) {
return false;
}

return elapsed >= lockTimeoutRef.current;
}, []);

const [isLocked, setLocked] = useState(getElapsed());
// const [isInactive, setInactive] = useState(false);

const authenticateWithBiometrics = useCallback(async () => {
const { success } = await LocalAuthentication.authenticateAsync();
setLocked(!success);
return success;
}, []);

const handleActiveState = useCallback(
async (skipElapsed = false) => {
if (!skipElapsed && !getElapsed()) {
return;
}

console.log('is ellapsed');
setLocked(true);
// router.replace('/(modals)/lock');
// if (typeof onLockTimeOutReachedRef.current === 'function') {
// onLockTimeOutReachedRef.current();
// } else {
await authenticateWithBiometrics();
},
[authenticateWithBiometrics, getElapsed],
);

useEffect(() => {
setLocalUser(JSON.parse(UserInactivityStore.getString('user') || '') || {});
void handleActiveState(true);
}, [handleActiveState]);

useEffect(() => {
const sub = AppState.addEventListener('change', nextAppState => {
if (nextAppState === 'inactive') {
console.log('--- to inactive');
// setInactive(true);
UserInactivityStore.set('user', JSON.stringify(getClerkInstance().user || ''));
} else {
// setInactive(false);
}

if (nextAppState === 'background') {
console.log('--- to background');
UserInactivityStore.set('user', JSON.stringify(getClerkInstance().user || ''));
recordStartTime();
} else if (nextAppState === 'active' && appState.current.match(/background/i)) {
console.log('--- active');

setLocalUser(JSON.parse(UserInactivityStore.getString('user') || '') || {});
void handleActiveState();
}

appState.current = nextAppState;
});

return () => {
sub.remove();
};
}, [handleActiveState]);

const recordStartTime = () => {
UserInactivityStore.set('startTime', Date.now());
};

return (
<UserInactivityContext.Provider
value={{
localAuthUser: localUser,
}}
>
{LockTimeOutScreen && isLocked ? (
<LockTimeOutScreen
authenticateWithBiometrics={authenticateWithBiometrics}
localAuthUser={localUser!}
/>
) : (
children
)}
</UserInactivityContext.Provider>
);
}
89 changes: 89 additions & 0 deletions packages/expo/src/experimental/LocalAuthCredentials.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { useClerk, useSignIn } from '@clerk/clerk-react';
import type { SignInResource } from '@clerk/types';
import * as SecureStore from 'expo-secure-store';
import type { PropsWithChildren } from 'react';
import React, { createContext, useContext, useState } from 'react';

type LocalAuthCredentials = {
identifier: string;
password: string;
};

export const LocalAuthContext = createContext<{
setLocalAuthCredentials: (creds: LocalAuthCredentials) => Promise<void>;
hasLocalAuthCredentials: boolean;
clearLocalAuthAccount: () => void;
authenticateWithLocalAccount: () => Promise<SignInResource>;
}>({
// @ts-expect-error Initial value cannot return what the type expects
setLocalAuthCredentials: () => {},
hasLocalAuthCredentials: false,
clearLocalAuthAccount: () => {},
// @ts-expect-error Initial value cannot return what the type expects
authenticateWithLocalAccount: () => {},
});

export const useLocalAuthCredentials = () => {
return useContext(LocalAuthContext);
};

export function LocalAuthCredentialsProvider(props: PropsWithChildren): JSX.Element {
const { isLoaded, signIn } = useSignIn();
const { publishableKey } = useClerk();
const key = `__clerk_local_auth_${publishableKey}_identifier`;
const pkey = `__clerk_local_auth_${publishableKey}_password`;
const [hasLocalAuthCredentials, setHasLocalAuthCredentials] = useState(!!SecureStore.getItem(key));

const setLocalAuthCredentials = async (creds: LocalAuthCredentials) => {
if (!SecureStore.canUseBiometricAuthentication()) {
return;
}
await SecureStore.setItemAsync(key, creds.identifier);
await SecureStore.setItemAsync(pkey, creds.password, {
keychainAccessible: SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY,
requireAuthentication: true,
});
setHasLocalAuthCredentials(true);
};

const clearLocalAuthAccount = async () => {
await Promise.all([SecureStore.deleteItemAsync(key), SecureStore.deleteItemAsync(pkey)]);
setHasLocalAuthCredentials(false);
};

const authenticateWithLocalAccount = async () => {
if (!isLoaded) {
throw 'not loaded';
}
const identifier = await SecureStore.getItemAsync(key);
if (!identifier) {
// TODO: improve error
throw 'Identifier not found';
}
const password = await SecureStore.getItemAsync(pkey);

if (!password) {
// TODO: improve error
throw 'password not found';
}

return signIn.create({
strategy: 'password',
identifier,
password,
});
};

return (
<LocalAuthContext.Provider
value={{
setLocalAuthCredentials,
hasLocalAuthCredentials,
clearLocalAuthAccount,
authenticateWithLocalAccount,
}}
>
{props.children}
</LocalAuthContext.Provider>
);
}
2 changes: 2 additions & 0 deletions packages/expo/src/experimental/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// export { LocalAuthProvider } from './LocalAuth';
export { LocalAuthCredentialsProvider, useLocalAuthCredentials } from './LocalAuthCredentials';
6 changes: 6 additions & 0 deletions packages/expo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ export {

export { isClerkAPIResponseError, isEmailLinkError, isKnownError, isMetamaskError } from '@clerk/clerk-react/errors';

export {
// LocalAuthProvider as __experimental_LocalAuthProvider,
LocalAuthCredentialsProvider as __experimental_LocalAuthCredentialsProvider,
useLocalAuthCredentials as __experimental_useLocalAuthCredentials,
} from './experimental';

/**
* @deprecated Use `getClerkInstance()` instead.
*/
Expand Down
Loading