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): Introduce support for LocalAuth with LocalCredentials #3663

Merged
merged 28 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
5d0aeef
feat(clerk-expo): Introduce LocalAuth utility
panteliselef Jun 25, 2024
d93018f
chore(clerk-expo): Update package.json
panteliselef Jun 25, 2024
f194c8b
chore(clerk-js): Add LocalAuthCredentials
panteliselef Jun 28, 2024
c2a1425
chore(clerk-expo): Rename to LocalCredentials
panteliselef Jul 3, 2024
d01daf8
feat(clerk-expo): Expose biometricType
panteliselef Jul 3, 2024
0a06840
add react as devDep
panteliselef Jul 5, 2024
4215762
add changeset
panteliselef Jul 5, 2024
e80425d
Merge branch 'refs/heads/main' into elef/user-119-local-auth-for-expo
panteliselef Jul 5, 2024
ecce02d
add package-lock.json
panteliselef Jul 5, 2024
84edb49
use correct react version for expo
panteliselef Jul 5, 2024
e946474
drop react-native-mmkv
panteliselef Jul 5, 2024
a57936f
Merge branch 'main' into elef/user-119-local-auth-for-expo
panteliselef Jul 5, 2024
7a5af17
Merge branch 'main' into elef/user-119-local-auth-for-expo
panteliselef Jul 5, 2024
0cb780e
feat(clerk-expo): Add `userOwnsCredentials`
panteliselef Jul 11, 2024
388877a
Mark deps as optional
panteliselef Jul 11, 2024
f323216
feat(clerk-expo): Support SDK 50
panteliselef Jul 13, 2024
dfccb21
Merge branch 'refs/heads/main' into elef/user-119-local-auth-for-expo
panteliselef Jul 30, 2024
a184992
revert husky deletion
panteliselef Jul 30, 2024
2b021d2
update changeset
panteliselef Jul 30, 2024
086e892
Drop provider and add web support
panteliselef Jul 30, 2024
ff0337d
Merge branch 'refs/heads/main' into elef/user-119-local-auth-for-expo
panteliselef Aug 6, 2024
c7fddbf
Prioritize face recognition over fingerprint
panteliselef Aug 6, 2024
4c2a0f8
Add jsdoc
panteliselef Aug 7, 2024
9e83bbe
Merge branch 'refs/heads/main' into elef/user-119-local-auth-for-expo
panteliselef Aug 7, 2024
76706a0
Update packages/expo/src/hooks/useLocalCredentials/useLocalCredential…
panteliselef Aug 7, 2024
9b7a409
update error
panteliselef Aug 7, 2024
35e1326
Update packages/expo/src/hooks/useLocalCredentials/useLocalCredential…
panteliselef Aug 7, 2024
6b6308d
Merge branch 'refs/heads/main' into elef/user-119-local-auth-for-expo
panteliselef Aug 7, 2024
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
5 changes: 5 additions & 0 deletions .changeset/rude-poets-beam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@clerk/clerk-expo": minor
---

Introduce support for LocalAuthentication with `useLocalCredentials`.
Empty file modified .husky/pre-commit
100755 → 100644
Empty file.
33 changes: 33 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions packages/expo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,29 @@
"@types/react": "*",
"@types/react-dom": "*",
"expo-auth-session": "^5.4.0",
"expo-local-authentication": "^13.5.0",
"expo-secure-store": "^12.4.0",
"expo-web-browser": "^12.8.2",
"react-native": "^0.73.9",
"typescript": "*"
},
"peerDependencies": {
"expo-auth-session": ">=5",
"expo-local-authentication": ">=13.5.0",
"expo-secure-store": ">=12.4.0",
"expo-web-browser": ">=12.5.0",
"react-native": ">=0.73",
"react": ">=18",
"react-dom": ">=18"
},
"peerDependenciesMeta": {
"expo-secure-store": {
"optional": true
},
"expo-local-authentication": {
"optional": true
}
},
"engines": {
"node": ">=18.17.0"
},
Expand Down
1 change: 1 addition & 0 deletions packages/expo/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export {
} from '@clerk/clerk-react';

export * from './useOAuth';
export * from './useLocalCredentials';
1 change: 1 addition & 0 deletions packages/expo/src/hooks/useLocalCredentials/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { useLocalCredentials } from './useLocalCredentials';
31 changes: 31 additions & 0 deletions packages/expo/src/hooks/useLocalCredentials/shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { SignInResource } from '@clerk/types';

type LocalCredentials = {
identifier?: string;
password: string;
};

type BiometricType = 'fingerprint' | 'face-recognition';

type LocalCredentialsReturn = {
setCredentials: (creds: LocalCredentials) => Promise<void>;
hasCredentials: boolean;
userOwnsCredentials: boolean | null;
clearCredentials: () => Promise<void>;
authenticate: () => Promise<SignInResource>;
biometryType: BiometricType | null;
};

const LocalCredentialsInitValues: LocalCredentialsReturn = {
Copy link
Member

@octoper octoper Aug 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❓ Should we have something like isPlatformSupported in LocalCredentialsInitValues in order to be easier to check if the hook can be used on specific platforms like Web or a device that does not has any biometric support, as now it seems you will have to check if biometryType is null which is not so clear if you don't take a look at the code

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For devices that do not support biometric, android and iOS fallback to PIN, and if a pin does not exist then biometricType will be null.

with biometricType you get the available authenticator and it is useful mostly for UI purposes. Displaying a Face ID or a touch ID icon for example.

Maybe simply changing the name to supportedBiometricType would do ?

We don't wanna indicate that the device can use biometric, but instead if we can use local authentication (biometric or not) in order to store credentials.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was mostly referring for platforms that this will not work at all like web,the biometric support was just an example as I didn't know if this fallbacks to pin

setCredentials: () => Promise.resolve(),
hasCredentials: false,
userOwnsCredentials: null,
clearCredentials: () => Promise.resolve(),
// @ts-expect-error Initial value cannot return what the type expects
authenticate: () => Promise.resolve({}),
biometryType: null,
};

export { LocalCredentialsInitValues };

export type { LocalCredentials, BiometricType, LocalCredentialsReturn };
183 changes: 183 additions & 0 deletions packages/expo/src/hooks/useLocalCredentials/useLocalCredentials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import { useClerk, useSignIn, useUser } from '@clerk/clerk-react';
import { AuthenticationType, isEnrolledAsync, supportedAuthenticationTypesAsync } from 'expo-local-authentication';
import {
deleteItemAsync,
getItem,
getItemAsync,
setItemAsync,
WHEN_PASSCODE_SET_THIS_DEVICE_ONLY,
} from 'expo-secure-store';
import { useEffect, useState } from 'react';

import { errorThrower } from '../../utils';
import type { BiometricType, LocalCredentials, LocalCredentialsReturn } from './shared';

const useEnrolledBiometric = () => {
const [isEnrolled, setIsEnrolled] = useState(false);

useEffect(() => {
let ignore = false;

void isEnrolledAsync().then(res => {
if (ignore) {
return;
}
setIsEnrolled(res);
});

return () => {
ignore = true;
};
}, []);

return isEnrolled;
};

const useAuthenticationType = () => {
const [authenticationType, setAuthenticationType] = useState<BiometricType | null>(null);

useEffect(() => {
let ignore = false;

void supportedAuthenticationTypesAsync().then(numericTypes => {
if (ignore) {
return;
}
if (numericTypes.length === 0) {
return;
}

if (numericTypes.includes(AuthenticationType.FINGERPRINT)) {
setAuthenticationType('fingerprint');
} else {
setAuthenticationType('face-recognition');
}
});

return () => {
ignore = true;
};
}, []);

return authenticationType;
};

const useUserOwnsCredentials = ({ storeKey }: { storeKey: string }) => {
const { user } = useUser();
const [userOwnsCredentials, setUserOwnsCredentials] = useState(false);

const getUserCredentials = (storedIdentifier: string | null): boolean => {
if (!user || !storedIdentifier) {
return false;
}

const identifiers = [
user.emailAddresses.map(e => e.emailAddress),
user.phoneNumbers.map(p => p.phoneNumber),
].flat();

if (user.username) {
identifiers.push(user.username);
}
return identifiers.includes(storedIdentifier);
};

useEffect(() => {
let ignore = false;
getItemAsync(storeKey)
.catch(() => null)
.then(res => {
if (ignore) {
return;
}
setUserOwnsCredentials(getUserCredentials(res));
});

return () => {
ignore = true;
};
}, [storeKey, user]);

return [userOwnsCredentials, setUserOwnsCredentials] as const;
};

export const useLocalCredentials = (): LocalCredentialsReturn => {
panteliselef marked this conversation as resolved.
Show resolved Hide resolved
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(!!getItem(key));
const [userOwnsCredentials, setUserOwnsCredentials] = useUserOwnsCredentials({ storeKey: key });
const hasEnrolledBiometric = useEnrolledBiometric();
const authenticationType = useAuthenticationType();

const biometryType = hasEnrolledBiometric ? authenticationType : null;

const setCredentials = async (creds: LocalCredentials) => {
if (!(await isEnrolledAsync())) {
return;
}

if (creds.identifier && !creds.password) {
return errorThrower.throw(
`useLocalCredentials: setCredentials() A password is required when specifying an identifier.`,
);
}

if (creds.identifier) {
await setItemAsync(key, creds.identifier);
}

const storedIdentifier = await getItemAsync(key).catch(() => null);

if (!storedIdentifier) {
return errorThrower.throw(
`useLocalCredentials: setCredentials() an identifier should already be set in order to update its password.`,
);
}

setHasLocalAuthCredentials(true);
await setItemAsync(pkey, creds.password, {
keychainAccessible: WHEN_PASSCODE_SET_THIS_DEVICE_ONLY,
requireAuthentication: true,
});
};

const clearCredentials = async () => {
await Promise.all([deleteItemAsync(key), deleteItemAsync(pkey)]);
panteliselef marked this conversation as resolved.
Show resolved Hide resolved
setHasLocalAuthCredentials(false);
setUserOwnsCredentials(false);
};

const authenticate = async () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 It would be nice to (optionally?) set the credentials after a successful auth

if (!isLoaded) {
return errorThrower.throw(
`useLocalCredentials: authenticate() Clerk has not loaded yet. Wait for clerk to load before calling this function`,
);
}
const identifier = await getItemAsync(key).catch(() => null);
if (!identifier) {
return errorThrower.throw(`useLocalCredentials: authenticate() the identifier could not be found`);
}
const password = await getItemAsync(pkey).catch(() => null);

if (!password) {
return errorThrower.throw(`useLocalCredentials: authenticate() cannot retrieve a password for that identifier`);
}
panteliselef marked this conversation as resolved.
Show resolved Hide resolved

return signIn.create({
strategy: 'password',
identifier,
password,
});
};
return {
panteliselef marked this conversation as resolved.
Show resolved Hide resolved
setCredentials,
hasCredentials: hasLocalAuthCredentials,
userOwnsCredentials,
clearCredentials,
authenticate,
biometryType,
panteliselef marked this conversation as resolved.
Show resolved Hide resolved
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import type { LocalCredentialsReturn } from './shared';
import { LocalCredentialsInitValues } from './shared';

export const useLocalCredentials = (): LocalCredentialsReturn => {
return LocalCredentialsInitValues;
};
Loading