@vvedantb/native-ui 0.31.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -6
- package/dist/auth/AccountScreens.jsx +450 -0
- package/dist/auth/AuthProviders.jsx +2 -2
- package/dist/auth/GoogleSignInButton.jsx +1 -1
- package/dist/auth/SignInScreen.jsx +28 -94
- package/dist/auth/authErrors.js +1 -1
- package/dist/auth/clerkCore3.js +110 -0
- package/dist/auth/index.js +2 -1
- package/dist/auth/totp.js +49 -60
- package/dist/entries/auth.js +1 -1
- package/package.json +4 -4
- package/src/auth/AccountScreens.tsx +294 -0
- package/src/auth/AuthProviders.tsx +8 -5
- package/src/auth/GoogleSignInButton.tsx +1 -1
- package/src/auth/SignInScreen.tsx +25 -55
- package/src/auth/authErrors.ts +1 -1
- package/src/auth/clerkCore3.ts +88 -0
- package/src/auth/index.ts +3 -1
- package/src/auth/totp.ts +5 -11
- package/src/entries/auth.ts +1 -1
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { useRef, useState, type ReactNode } from "react";
|
|
2
|
+
import type { TextInput } from "react-native";
|
|
3
|
+
import { useUser } from "@clerk/expo";
|
|
4
|
+
import { useRouter, type Href } from "expo-router";
|
|
5
|
+
import { Button } from "../Button";
|
|
6
|
+
import { Input } from "../Input";
|
|
7
|
+
import { PasswordInput } from "../PasswordInput";
|
|
8
|
+
import { AuthScreen, FieldError } from "./AuthScreen";
|
|
9
|
+
import {
|
|
10
|
+
authErrorMessage,
|
|
11
|
+
DEFAULT_STAGE_TIMEOUT_MS,
|
|
12
|
+
logAuthFailure,
|
|
13
|
+
withAuthTimeout,
|
|
14
|
+
} from "./authErrors";
|
|
15
|
+
|
|
16
|
+
/** The messages the account screens can show. Generic: none names a provider. */
|
|
17
|
+
export const ACCOUNT_MESSAGES = {
|
|
18
|
+
changePasswordTitle: "Change password",
|
|
19
|
+
changePasswordSubtitle: "Enter your current password, then a new one.",
|
|
20
|
+
setPasswordTitle: "Set a password",
|
|
21
|
+
setPasswordSubtitle: "Your account has no password yet. Choose one.",
|
|
22
|
+
currentPasswordLabel: "Current password",
|
|
23
|
+
newPasswordLabel: "New password",
|
|
24
|
+
confirmPasswordLabel: "Confirm new password",
|
|
25
|
+
missingCurrentPassword: "Enter your current password",
|
|
26
|
+
missingNewPassword: "Enter a new password",
|
|
27
|
+
passwordMismatch: "The passwords do not match",
|
|
28
|
+
changePasswordFailed: "Could not change the password",
|
|
29
|
+
changePassword: "Change password",
|
|
30
|
+
setPassword: "Set password",
|
|
31
|
+
deleteTitle: "Delete account",
|
|
32
|
+
deleteSubtitle: "This deletes your account and its data. It cannot be undone.",
|
|
33
|
+
deleteConfirmMismatch: "Type the word exactly to confirm",
|
|
34
|
+
deleteFailed: "Could not delete the account",
|
|
35
|
+
deleteAccount: "Delete account",
|
|
36
|
+
cancel: "Cancel",
|
|
37
|
+
notReady: "Your account is not ready yet. Try again in a moment.",
|
|
38
|
+
} as const;
|
|
39
|
+
|
|
40
|
+
type AccountScreenBase = {
|
|
41
|
+
title?: string;
|
|
42
|
+
subtitle?: string;
|
|
43
|
+
/** Above the title. App brand chrome goes here. */
|
|
44
|
+
header?: ReactNode;
|
|
45
|
+
/** Below the form. */
|
|
46
|
+
footer?: ReactNode;
|
|
47
|
+
/** Shows a "Cancel" button that calls it. No button without it. */
|
|
48
|
+
onCancel?: () => void;
|
|
49
|
+
/** Time for the call, in milliseconds. A longer call fails with code `auth_timeout`. Default 20000. */
|
|
50
|
+
stageTimeoutMs?: number;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export type ChangePasswordScreenProps = AccountScreenBase & {
|
|
54
|
+
/** Rejects a shorter new password before sending it. Default: no check. */
|
|
55
|
+
minPasswordLength?: number;
|
|
56
|
+
/** Ends the user's other sessions after the change. Default `true`. */
|
|
57
|
+
signOutOfOtherSessions?: boolean;
|
|
58
|
+
/** Called after the password changed. Default: `router.back()`. */
|
|
59
|
+
onSuccess?: () => void;
|
|
60
|
+
/** Prefix for every `testID`. Default `"change-password"`. */
|
|
61
|
+
testIDPrefix?: string;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Changes the signed-in user's password with `user.updatePassword`: the
|
|
66
|
+
* current password, then the new one typed twice. An account with no password
|
|
67
|
+
* (Google only) gets no current-password field and the "Set a password" copy.
|
|
68
|
+
* Errors show under the fields. Render it under `ClerkProvider`, signed in.
|
|
69
|
+
*/
|
|
70
|
+
export function ChangePasswordScreen({
|
|
71
|
+
title,
|
|
72
|
+
subtitle,
|
|
73
|
+
header,
|
|
74
|
+
footer,
|
|
75
|
+
onCancel,
|
|
76
|
+
stageTimeoutMs = DEFAULT_STAGE_TIMEOUT_MS,
|
|
77
|
+
minPasswordLength,
|
|
78
|
+
signOutOfOtherSessions = true,
|
|
79
|
+
onSuccess,
|
|
80
|
+
testIDPrefix = "change-password",
|
|
81
|
+
}: ChangePasswordScreenProps) {
|
|
82
|
+
const { isLoaded, user } = useUser();
|
|
83
|
+
const router = useRouter();
|
|
84
|
+
const [current, setCurrent] = useState("");
|
|
85
|
+
const [next, setNext] = useState("");
|
|
86
|
+
const [confirm, setConfirm] = useState("");
|
|
87
|
+
const [error, setError] = useState("");
|
|
88
|
+
const [submitting, setSubmitting] = useState(false);
|
|
89
|
+
const nextField = useRef<TextInput>(null);
|
|
90
|
+
const confirmField = useRef<TextInput>(null);
|
|
91
|
+
const id = (name: string) => `${testIDPrefix}-${name}`;
|
|
92
|
+
// Until the user loads, show the current-password field: most accounts have one.
|
|
93
|
+
const hasPassword = user ? user.passwordEnabled : true;
|
|
94
|
+
|
|
95
|
+
const submit = async () => {
|
|
96
|
+
if (submitting) return;
|
|
97
|
+
if (!isLoaded || !user) return setError(ACCOUNT_MESSAGES.notReady);
|
|
98
|
+
if (hasPassword && !current) return setError(ACCOUNT_MESSAGES.missingCurrentPassword);
|
|
99
|
+
if (!next) return setError(ACCOUNT_MESSAGES.missingNewPassword);
|
|
100
|
+
if (minPasswordLength && next.length < minPasswordLength) {
|
|
101
|
+
return setError(`Use at least ${minPasswordLength} characters for the password`);
|
|
102
|
+
}
|
|
103
|
+
if (next !== confirm) return setError(ACCOUNT_MESSAGES.passwordMismatch);
|
|
104
|
+
setSubmitting(true);
|
|
105
|
+
setError("");
|
|
106
|
+
// React Compiler memoises a component only when its `try` has no branch and
|
|
107
|
+
// no `finally`, so the branches sit before and after it.
|
|
108
|
+
const params = hasPassword
|
|
109
|
+
? { newPassword: next, signOutOfOtherSessions, currentPassword: current }
|
|
110
|
+
: { newPassword: next, signOutOfOtherSessions };
|
|
111
|
+
let failed = false;
|
|
112
|
+
let failure: unknown;
|
|
113
|
+
try {
|
|
114
|
+
await withAuthTimeout(user.updatePassword(params), "update-password", stageTimeoutMs);
|
|
115
|
+
} catch (caught) {
|
|
116
|
+
failed = true;
|
|
117
|
+
failure = caught;
|
|
118
|
+
}
|
|
119
|
+
setSubmitting(false);
|
|
120
|
+
if (failed) {
|
|
121
|
+
logAuthFailure("update-password", failure);
|
|
122
|
+
return setError(authErrorMessage(failure, ACCOUNT_MESSAGES.changePasswordFailed));
|
|
123
|
+
}
|
|
124
|
+
setCurrent("");
|
|
125
|
+
setNext("");
|
|
126
|
+
setConfirm("");
|
|
127
|
+
if (onSuccess) onSuccess();
|
|
128
|
+
else router.back();
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
return (
|
|
132
|
+
<AuthScreen
|
|
133
|
+
testID={id("screen")}
|
|
134
|
+
title={title ?? (hasPassword ? ACCOUNT_MESSAGES.changePasswordTitle : ACCOUNT_MESSAGES.setPasswordTitle)}
|
|
135
|
+
subtitle={subtitle ?? (hasPassword ? ACCOUNT_MESSAGES.changePasswordSubtitle : ACCOUNT_MESSAGES.setPasswordSubtitle)}
|
|
136
|
+
header={header}
|
|
137
|
+
footer={footer}
|
|
138
|
+
>
|
|
139
|
+
{hasPassword ? (
|
|
140
|
+
<PasswordInput
|
|
141
|
+
testID={id("current")}
|
|
142
|
+
accessibilityLabel={ACCOUNT_MESSAGES.currentPasswordLabel}
|
|
143
|
+
autoCapitalize="none"
|
|
144
|
+
autoComplete="password"
|
|
145
|
+
textContentType="password"
|
|
146
|
+
returnKeyType="next"
|
|
147
|
+
submitBehavior="submit"
|
|
148
|
+
onSubmitEditing={() => nextField.current?.focus()}
|
|
149
|
+
value={current}
|
|
150
|
+
placeholder={ACCOUNT_MESSAGES.currentPasswordLabel}
|
|
151
|
+
onChangeText={setCurrent}
|
|
152
|
+
/>
|
|
153
|
+
) : null}
|
|
154
|
+
<PasswordInput
|
|
155
|
+
testID={id("new")}
|
|
156
|
+
ref={nextField}
|
|
157
|
+
accessibilityLabel={ACCOUNT_MESSAGES.newPasswordLabel}
|
|
158
|
+
autoCapitalize="none"
|
|
159
|
+
autoComplete="new-password"
|
|
160
|
+
textContentType="newPassword"
|
|
161
|
+
returnKeyType="next"
|
|
162
|
+
submitBehavior="submit"
|
|
163
|
+
onSubmitEditing={() => confirmField.current?.focus()}
|
|
164
|
+
value={next}
|
|
165
|
+
placeholder={ACCOUNT_MESSAGES.newPasswordLabel}
|
|
166
|
+
onChangeText={setNext}
|
|
167
|
+
/>
|
|
168
|
+
<PasswordInput
|
|
169
|
+
testID={id("confirm")}
|
|
170
|
+
ref={confirmField}
|
|
171
|
+
accessibilityLabel={ACCOUNT_MESSAGES.confirmPasswordLabel}
|
|
172
|
+
autoCapitalize="none"
|
|
173
|
+
autoComplete="new-password"
|
|
174
|
+
textContentType="newPassword"
|
|
175
|
+
returnKeyType="go"
|
|
176
|
+
value={confirm}
|
|
177
|
+
placeholder={ACCOUNT_MESSAGES.confirmPasswordLabel}
|
|
178
|
+
onChangeText={setConfirm}
|
|
179
|
+
onSubmitEditing={() => void submit()}
|
|
180
|
+
/>
|
|
181
|
+
<FieldError testID={id("error")} message={error} />
|
|
182
|
+
<Button testID={id("submit")} loading={submitting} onPress={() => void submit()}>
|
|
183
|
+
{hasPassword ? ACCOUNT_MESSAGES.changePassword : ACCOUNT_MESSAGES.setPassword}
|
|
184
|
+
</Button>
|
|
185
|
+
{onCancel ? (
|
|
186
|
+
<Button testID={id("cancel")} variant="ghost" disabled={submitting} onPress={onCancel}>
|
|
187
|
+
{ACCOUNT_MESSAGES.cancel}
|
|
188
|
+
</Button>
|
|
189
|
+
) : null}
|
|
190
|
+
</AuthScreen>
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export type DeleteAccountScreenProps = AccountScreenBase & {
|
|
195
|
+
/** The word the user types to confirm. Compared without case. Default `"DELETE"`. */
|
|
196
|
+
confirmWord?: string;
|
|
197
|
+
/** Called after the account is deleted, in place of `router.replace`. */
|
|
198
|
+
onDeleted?: () => void;
|
|
199
|
+
/** Where to go after the account is deleted. Default `"/"`. */
|
|
200
|
+
afterDeleteHref?: Href;
|
|
201
|
+
/** Prefix for every `testID`. Default `"delete-account"`. */
|
|
202
|
+
testIDPrefix?: string;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Deletes the signed-in user's account with `user.delete()`. The user types
|
|
207
|
+
* `confirmWord` first; the delete button stays off until it matches. Needs
|
|
208
|
+
* "Allow users to delete their accounts" turned on for the instance. Errors
|
|
209
|
+
* show under the field. Render it under `ClerkProvider`, signed in.
|
|
210
|
+
*/
|
|
211
|
+
export function DeleteAccountScreen({
|
|
212
|
+
title,
|
|
213
|
+
subtitle,
|
|
214
|
+
header,
|
|
215
|
+
footer,
|
|
216
|
+
onCancel,
|
|
217
|
+
stageTimeoutMs = DEFAULT_STAGE_TIMEOUT_MS,
|
|
218
|
+
confirmWord = "DELETE",
|
|
219
|
+
onDeleted,
|
|
220
|
+
afterDeleteHref = "/",
|
|
221
|
+
testIDPrefix = "delete-account",
|
|
222
|
+
}: DeleteAccountScreenProps) {
|
|
223
|
+
const { isLoaded, user } = useUser();
|
|
224
|
+
const router = useRouter();
|
|
225
|
+
const [typed, setTyped] = useState("");
|
|
226
|
+
const [error, setError] = useState("");
|
|
227
|
+
const [submitting, setSubmitting] = useState(false);
|
|
228
|
+
const id = (name: string) => `${testIDPrefix}-${name}`;
|
|
229
|
+
const matches = typed.trim().toLowerCase() === confirmWord.toLowerCase();
|
|
230
|
+
|
|
231
|
+
const submit = async () => {
|
|
232
|
+
if (submitting) return;
|
|
233
|
+
if (!matches) return setError(ACCOUNT_MESSAGES.deleteConfirmMismatch);
|
|
234
|
+
if (!isLoaded || !user) return setError(ACCOUNT_MESSAGES.notReady);
|
|
235
|
+
setSubmitting(true);
|
|
236
|
+
setError("");
|
|
237
|
+
// No branch inside the `try`: see `ChangePasswordScreen`.
|
|
238
|
+
let failed = false;
|
|
239
|
+
let failure: unknown;
|
|
240
|
+
try {
|
|
241
|
+
await withAuthTimeout(user.delete(), "delete-account", stageTimeoutMs);
|
|
242
|
+
} catch (caught) {
|
|
243
|
+
failed = true;
|
|
244
|
+
failure = caught;
|
|
245
|
+
}
|
|
246
|
+
setSubmitting(false);
|
|
247
|
+
if (failed) {
|
|
248
|
+
logAuthFailure("delete-account", failure);
|
|
249
|
+
return setError(authErrorMessage(failure, ACCOUNT_MESSAGES.deleteFailed));
|
|
250
|
+
}
|
|
251
|
+
if (onDeleted) onDeleted();
|
|
252
|
+
else router.replace(afterDeleteHref);
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const label = `Type ${confirmWord} to confirm`;
|
|
256
|
+
return (
|
|
257
|
+
<AuthScreen
|
|
258
|
+
testID={id("screen")}
|
|
259
|
+
title={title ?? ACCOUNT_MESSAGES.deleteTitle}
|
|
260
|
+
subtitle={subtitle ?? ACCOUNT_MESSAGES.deleteSubtitle}
|
|
261
|
+
header={header}
|
|
262
|
+
footer={footer}
|
|
263
|
+
>
|
|
264
|
+
<Input
|
|
265
|
+
testID={id("confirm")}
|
|
266
|
+
accessibilityLabel={label}
|
|
267
|
+
autoCapitalize="characters"
|
|
268
|
+
autoCorrect={false}
|
|
269
|
+
returnKeyType="done"
|
|
270
|
+
value={typed}
|
|
271
|
+
placeholder={label}
|
|
272
|
+
onChangeText={(text) => {
|
|
273
|
+
setTyped(text);
|
|
274
|
+
setError("");
|
|
275
|
+
}}
|
|
276
|
+
/>
|
|
277
|
+
<FieldError testID={id("error")} message={error} />
|
|
278
|
+
<Button
|
|
279
|
+
testID={id("submit")}
|
|
280
|
+
variant="destructive"
|
|
281
|
+
loading={submitting}
|
|
282
|
+
disabled={!matches}
|
|
283
|
+
onPress={() => void submit()}
|
|
284
|
+
>
|
|
285
|
+
{ACCOUNT_MESSAGES.deleteAccount}
|
|
286
|
+
</Button>
|
|
287
|
+
{onCancel ? (
|
|
288
|
+
<Button testID={id("cancel")} variant="ghost" disabled={submitting} onPress={onCancel}>
|
|
289
|
+
{ACCOUNT_MESSAGES.cancel}
|
|
290
|
+
</Button>
|
|
291
|
+
) : null}
|
|
292
|
+
</AuthScreen>
|
|
293
|
+
);
|
|
294
|
+
}
|
|
@@ -1,17 +1,20 @@
|
|
|
1
1
|
import type { ReactNode } from "react";
|
|
2
|
-
import { ClerkLoaded, ClerkProvider, useAuth as useClerkAuth, type TokenCache } from "@clerk/
|
|
2
|
+
import { ClerkLoaded, ClerkProvider, useAuth as useClerkAuth, type TokenCache } from "@clerk/expo";
|
|
3
3
|
import { ConvexProvider, type ConvexReactClient } from "convex/react";
|
|
4
4
|
import { ConvexProviderWithClerk } from "convex/react-clerk";
|
|
5
5
|
|
|
6
6
|
export type AuthProvidersProps = {
|
|
7
7
|
children: ReactNode;
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* The Clerk publishable key. The app reads it from its own config; this component does not check it.
|
|
10
|
+
* `@clerk/expo` needs it: pass it unless `clerk` is `false`.
|
|
11
|
+
*/
|
|
9
12
|
publishableKey?: string;
|
|
10
|
-
/** `tokenCache` from `@clerk/
|
|
13
|
+
/** `tokenCache` from `@clerk/expo/token-cache`, so the session survives a restart. */
|
|
11
14
|
tokenCache?: TokenCache;
|
|
12
15
|
/** A Convex client. Without one, the children sit under Clerk only (vmem). */
|
|
13
16
|
convex?: ConvexReactClient | null;
|
|
14
|
-
/** `useAuth` from `@clerk/
|
|
17
|
+
/** `useAuth` from `@clerk/expo`, for `ConvexProviderWithClerk`. Default: the one this package imports. */
|
|
15
18
|
useAuth?: typeof useClerkAuth;
|
|
16
19
|
/** Wrap the children in `ClerkLoaded`, so they wait for the session. Default `true`. */
|
|
17
20
|
loaded?: boolean;
|
|
@@ -42,7 +45,7 @@ export function AuthProviders({
|
|
|
42
45
|
}
|
|
43
46
|
const inner = loaded ? <ClerkLoaded>{children}</ClerkLoaded> : children;
|
|
44
47
|
return (
|
|
45
|
-
<ClerkProvider publishableKey={publishableKey} tokenCache={tokenCache}>
|
|
48
|
+
<ClerkProvider publishableKey={publishableKey ?? ""} tokenCache={tokenCache}>
|
|
46
49
|
{convex ? (
|
|
47
50
|
<ConvexProviderWithClerk client={convex} useAuth={useAuth}>
|
|
48
51
|
{inner}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useEffect, useState } from "react";
|
|
2
2
|
import { Platform } from "react-native";
|
|
3
|
-
import { useSSO } from "@clerk/
|
|
3
|
+
import { useSSO } from "@clerk/expo";
|
|
4
4
|
import * as AuthSession from "expo-auth-session";
|
|
5
5
|
import * as WebBrowser from "expo-web-browser";
|
|
6
6
|
import { useRouter, type Href } from "expo-router";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useRef, useState, type ReactNode } from "react";
|
|
2
2
|
import { Text, View, type TextInput } from "react-native";
|
|
3
|
-
import { useSignIn, useSignUp } from "@clerk/
|
|
3
|
+
import { useSignIn, useSignUp } from "@clerk/expo";
|
|
4
4
|
import { useRouter, type Href } from "expo-router";
|
|
5
5
|
import { Button } from "../Button";
|
|
6
6
|
import { textStyle } from "../controlStyles";
|
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
logAuthFailure,
|
|
17
17
|
withAuthTimeout,
|
|
18
18
|
} from "./authErrors";
|
|
19
|
+
import { clerkCall, signInCalls } from "./clerkCore3";
|
|
19
20
|
import { SecondFactorScreen } from "./SecondFactorScreen";
|
|
20
21
|
import {
|
|
21
22
|
pickFirstFactorStrategy,
|
|
@@ -34,9 +35,6 @@ import { GoogleSignInButton, type AuthNavigationOptions } from "./GoogleSignInBu
|
|
|
34
35
|
|
|
35
36
|
export type SignInMode = "sign-in" | "sign-up" | "reset-password";
|
|
36
37
|
|
|
37
|
-
/** The first factor that emails a password-reset code. */
|
|
38
|
-
const RESET_STRATEGY = "reset_password_email_code";
|
|
39
|
-
|
|
40
38
|
/** The messages the screen can show. Generic: none names a provider. */
|
|
41
39
|
export const AUTH_MESSAGES = {
|
|
42
40
|
missingFields: "Enter your email and password",
|
|
@@ -210,8 +208,9 @@ export function SignInScreen({
|
|
|
210
208
|
onIncomplete,
|
|
211
209
|
stageTimeoutMs = DEFAULT_STAGE_TIMEOUT_MS,
|
|
212
210
|
}: SignInScreenProps) {
|
|
213
|
-
|
|
214
|
-
const
|
|
211
|
+
// Both are always defined: before Clerk loads, a call waits for it.
|
|
212
|
+
const signIn = signInCalls(useSignIn().signIn);
|
|
213
|
+
const signUpAttempt = useSignUp().signUp;
|
|
215
214
|
const router = useRouter();
|
|
216
215
|
const colorScheme = useScheme();
|
|
217
216
|
const [email, setEmail] = useState("");
|
|
@@ -290,8 +289,6 @@ export function SignInScreen({
|
|
|
290
289
|
};
|
|
291
290
|
|
|
292
291
|
const chooseFirstStrategy = async (strategy: FirstFactorStrategy, list: FirstFactor[]) => {
|
|
293
|
-
const { signIn } = signInState;
|
|
294
|
-
if (!signIn) return;
|
|
295
292
|
setFirstError("");
|
|
296
293
|
setFirstStrategy(strategy);
|
|
297
294
|
setPendingFirstFactor(true);
|
|
@@ -316,11 +313,10 @@ export function SignInScreen({
|
|
|
316
313
|
|
|
317
314
|
// Routes a sign-in attempt. `needs_first_factor` is built in only after `signIn.create`.
|
|
318
315
|
const routeAttempt = async (attempt: IncompleteSignIn, afterCreate: boolean) => {
|
|
319
|
-
const { setActive } = signInState;
|
|
320
316
|
// Clerk's `SignInStatus` omits `needs_client_trust`: widen before comparing.
|
|
321
317
|
const status: string | null = attempt.status;
|
|
322
|
-
if (status === "complete" && attempt.createdSessionId
|
|
323
|
-
await withAuthTimeout(setActive(
|
|
318
|
+
if (status === "complete" && attempt.createdSessionId) {
|
|
319
|
+
await withAuthTimeout(signIn.setActive(), "set-active", stageTimeoutMs);
|
|
324
320
|
done();
|
|
325
321
|
} else if (status === "needs_new_password") {
|
|
326
322
|
setPendingFirstFactor(false);
|
|
@@ -338,8 +334,7 @@ export function SignInScreen({
|
|
|
338
334
|
};
|
|
339
335
|
|
|
340
336
|
const onFirstFactor = async (firstCode: string) => {
|
|
341
|
-
|
|
342
|
-
if (!isLoaded || !signIn || firstLoading) return;
|
|
337
|
+
if (firstLoading) return;
|
|
343
338
|
setFirstLoading(true);
|
|
344
339
|
setFirstError("");
|
|
345
340
|
const result = await submitFirstFactor({
|
|
@@ -364,8 +359,7 @@ export function SignInScreen({
|
|
|
364
359
|
};
|
|
365
360
|
|
|
366
361
|
const onNewPassword = async () => {
|
|
367
|
-
|
|
368
|
-
if (!isLoaded || !signIn || !setActive || submitting) return;
|
|
362
|
+
if (submitting) return;
|
|
369
363
|
if (!newPassword) return fail(AUTH_MESSAGES.resetPasswordFailed, AUTH_MESSAGES.missingNewPassword);
|
|
370
364
|
if (minPasswordLength && newPassword.length < minPasswordLength) {
|
|
371
365
|
return fail(AUTH_MESSAGES.resetPasswordFailed, `Use at least ${minPasswordLength} characters for the password`);
|
|
@@ -376,15 +370,11 @@ export function SignInScreen({
|
|
|
376
370
|
setSubmitting(true);
|
|
377
371
|
setError("");
|
|
378
372
|
try {
|
|
379
|
-
const result = await withAuthTimeout(
|
|
380
|
-
signIn.resetPassword({ password: newPassword }),
|
|
381
|
-
"reset-password",
|
|
382
|
-
stageTimeoutMs,
|
|
383
|
-
);
|
|
373
|
+
const result = await withAuthTimeout(signIn.resetPassword(newPassword), "reset-password", stageTimeoutMs);
|
|
384
374
|
// Clerk's `SignInStatus` omits `needs_client_trust`: widen before comparing.
|
|
385
375
|
const afterReset: string | null = result.status;
|
|
386
376
|
if (afterReset === "complete" && result.createdSessionId) {
|
|
387
|
-
await withAuthTimeout(setActive(
|
|
377
|
+
await withAuthTimeout(signIn.setActive(), "set-active", stageTimeoutMs);
|
|
388
378
|
done();
|
|
389
379
|
} else if (afterReset === "needs_second_factor" || afterReset === "needs_client_trust") {
|
|
390
380
|
// A reset on an account with two-step verification: the code step, then the session.
|
|
@@ -405,17 +395,12 @@ export function SignInScreen({
|
|
|
405
395
|
};
|
|
406
396
|
|
|
407
397
|
const onSignIn = async () => {
|
|
408
|
-
|
|
409
|
-
if (!isLoaded || !signIn || !setActive || submitting) return;
|
|
398
|
+
if (submitting) return;
|
|
410
399
|
if (!email || !password) return fail(AUTH_MESSAGES.signInFailed, AUTH_MESSAGES.missingFields);
|
|
411
400
|
setSubmitting(true);
|
|
412
401
|
setError("");
|
|
413
402
|
try {
|
|
414
|
-
const attempt = await withAuthTimeout(
|
|
415
|
-
signIn.create({ identifier: email, password }),
|
|
416
|
-
"create",
|
|
417
|
-
stageTimeoutMs,
|
|
418
|
-
);
|
|
403
|
+
const attempt = await withAuthTimeout(signIn.password(email, password), "create", stageTimeoutMs);
|
|
419
404
|
await routeAttempt(attempt, true);
|
|
420
405
|
} catch (caught) {
|
|
421
406
|
logAuthFailure("create", caught);
|
|
@@ -430,18 +415,11 @@ export function SignInScreen({
|
|
|
430
415
|
|
|
431
416
|
// Emails the reset code. Throws what the call throws.
|
|
432
417
|
const requestResetCode = async () => {
|
|
433
|
-
|
|
434
|
-
if (!signIn) return;
|
|
435
|
-
await withAuthTimeout(
|
|
436
|
-
signIn.create({ strategy: RESET_STRATEGY, identifier: email.trim() }),
|
|
437
|
-
"create",
|
|
438
|
-
stageTimeoutMs,
|
|
439
|
-
);
|
|
418
|
+
await withAuthTimeout(signIn.sendResetCode(email.trim()), "create", stageTimeoutMs);
|
|
440
419
|
};
|
|
441
420
|
|
|
442
421
|
const onResetRequest = async () => {
|
|
443
|
-
|
|
444
|
-
if (!isLoaded || !signIn || submitting) return;
|
|
422
|
+
if (submitting) return;
|
|
445
423
|
if (!email.trim()) return fail(AUTH_MESSAGES.sendResetFailed, AUTH_MESSAGES.missingEmail);
|
|
446
424
|
setSubmitting(true);
|
|
447
425
|
setError("");
|
|
@@ -458,8 +436,7 @@ export function SignInScreen({
|
|
|
458
436
|
};
|
|
459
437
|
|
|
460
438
|
const onResetResend = async () => {
|
|
461
|
-
|
|
462
|
-
if (!isLoaded || !signIn || resetLoading) return;
|
|
439
|
+
if (resetLoading) return;
|
|
463
440
|
setResetLoading(true);
|
|
464
441
|
setResetCodeError("");
|
|
465
442
|
try {
|
|
@@ -474,16 +451,11 @@ export function SignInScreen({
|
|
|
474
451
|
|
|
475
452
|
// Checks the emailed code. A good code gives `needs_new_password`, which `routeAttempt` shows.
|
|
476
453
|
const onResetCode = async (resetCode: string) => {
|
|
477
|
-
|
|
478
|
-
if (!isLoaded || !signIn || resetLoading) return;
|
|
454
|
+
if (resetLoading) return;
|
|
479
455
|
setResetLoading(true);
|
|
480
456
|
setResetCodeError("");
|
|
481
457
|
try {
|
|
482
|
-
const attempt
|
|
483
|
-
signIn.attemptFirstFactor({ strategy: RESET_STRATEGY, code: resetCode }),
|
|
484
|
-
"attempt-first-factor",
|
|
485
|
-
stageTimeoutMs,
|
|
486
|
-
);
|
|
458
|
+
const attempt = await withAuthTimeout(signIn.verifyResetCode(resetCode), "attempt-first-factor", stageTimeoutMs);
|
|
487
459
|
const status: string | null = attempt.status;
|
|
488
460
|
const known = ["complete", "needs_new_password", "needs_second_factor", "needs_client_trust"];
|
|
489
461
|
if (status && known.includes(status)) {
|
|
@@ -523,8 +495,7 @@ export function SignInScreen({
|
|
|
523
495
|
};
|
|
524
496
|
|
|
525
497
|
const onSignUp = async () => {
|
|
526
|
-
|
|
527
|
-
if (!isLoaded || !attempt || submitting) return;
|
|
498
|
+
if (submitting) return;
|
|
528
499
|
if (!email || !password) return fail(AUTH_MESSAGES.signUpFailed, AUTH_MESSAGES.missingFields);
|
|
529
500
|
if (minPasswordLength && password.length < minPasswordLength) {
|
|
530
501
|
return fail(AUTH_MESSAGES.signUpFailed, `Use at least ${minPasswordLength} characters for the password`);
|
|
@@ -538,8 +509,8 @@ export function SignInScreen({
|
|
|
538
509
|
setSubmitting(true);
|
|
539
510
|
setError("");
|
|
540
511
|
try {
|
|
541
|
-
await
|
|
542
|
-
await
|
|
512
|
+
await clerkCall(signUpAttempt.password({ emailAddress: email, password }));
|
|
513
|
+
await clerkCall(signUpAttempt.verifications.sendEmailCode());
|
|
543
514
|
setPendingVerification(true);
|
|
544
515
|
} catch (caught) {
|
|
545
516
|
fail(AUTH_MESSAGES.signUpFailed, authErrorMessage(caught, AUTH_MESSAGES.signUpFailed));
|
|
@@ -549,15 +520,14 @@ export function SignInScreen({
|
|
|
549
520
|
};
|
|
550
521
|
|
|
551
522
|
const onVerify = async () => {
|
|
552
|
-
|
|
553
|
-
if (!isLoaded || !attempt || !setActive || submitting) return;
|
|
523
|
+
if (submitting) return;
|
|
554
524
|
if (!code) return fail(AUTH_MESSAGES.verifyFailed, AUTH_MESSAGES.missingCode);
|
|
555
525
|
setSubmitting(true);
|
|
556
526
|
setError("");
|
|
557
527
|
try {
|
|
558
|
-
|
|
559
|
-
if (
|
|
560
|
-
await
|
|
528
|
+
await clerkCall(signUpAttempt.verifications.verifyEmailCode({ code }));
|
|
529
|
+
if (signUpAttempt.status === "complete" && signUpAttempt.createdSessionId) {
|
|
530
|
+
await clerkCall(signUpAttempt.finalize());
|
|
561
531
|
done();
|
|
562
532
|
} else {
|
|
563
533
|
fail(AUTH_MESSAGES.verifyFailed, AUTH_MESSAGES.needsAnotherStep);
|
package/src/auth/authErrors.ts
CHANGED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { useSignIn } from "@clerk/expo";
|
|
2
|
+
import type { IncompleteSignIn } from "./SignInScreen";
|
|
3
|
+
import type { PrepareFirstFactorParams, PrepareSecondFactorParams, SecondFactorStrategy } from "./totp";
|
|
4
|
+
|
|
5
|
+
/** The sign-in resource of the `useSignIn` hook at the root of `@clerk/expo` 4. */
|
|
6
|
+
type CoreSignIn = ReturnType<typeof useSignIn>["signIn"];
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Awaits a call on Clerk's sign-in or sign-up resource. These calls resolve
|
|
10
|
+
* with `{ error }` where the older ones rejected: this throws that error, so
|
|
11
|
+
* `authErrorMessage` and `logAuthFailure` read it as before.
|
|
12
|
+
*/
|
|
13
|
+
export async function clerkCall(call: Promise<{ error: unknown }>): Promise<void> {
|
|
14
|
+
const { error } = await call;
|
|
15
|
+
if (error) throw error;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Wraps the sign-in resource for the helpers in `totp.ts` and for
|
|
20
|
+
* `SignInScreen`. Each method makes the call, throws its error, and returns
|
|
21
|
+
* the sign-in as it stands after the call. The methods are `async`, so an
|
|
22
|
+
* error the resource throws at once is also a rejection.
|
|
23
|
+
*/
|
|
24
|
+
export function signInCalls(signIn: CoreSignIn) {
|
|
25
|
+
const state = (): IncompleteSignIn => ({
|
|
26
|
+
status: signIn.status,
|
|
27
|
+
createdSessionId: signIn.createdSessionId,
|
|
28
|
+
supportedFirstFactors: signIn.supportedFirstFactors,
|
|
29
|
+
supportedSecondFactors: signIn.supportedSecondFactors,
|
|
30
|
+
});
|
|
31
|
+
return {
|
|
32
|
+
get supportedFirstFactors() {
|
|
33
|
+
return signIn.supportedFirstFactors;
|
|
34
|
+
},
|
|
35
|
+
get supportedSecondFactors() {
|
|
36
|
+
return signIn.supportedSecondFactors;
|
|
37
|
+
},
|
|
38
|
+
/** Starts a new sign-in with email and password. */
|
|
39
|
+
async password(identifier: string, password: string) {
|
|
40
|
+
await clerkCall(signIn.password({ identifier, password }));
|
|
41
|
+
return state();
|
|
42
|
+
},
|
|
43
|
+
/** Starts a new sign-in for `identifier` and emails its password-reset code. */
|
|
44
|
+
async sendResetCode(identifier: string) {
|
|
45
|
+
await clerkCall(signIn.create({ identifier }));
|
|
46
|
+
await clerkCall(signIn.resetPasswordEmailCode.sendCode());
|
|
47
|
+
},
|
|
48
|
+
async verifyResetCode(code: string) {
|
|
49
|
+
await clerkCall(signIn.resetPasswordEmailCode.verifyCode({ code }));
|
|
50
|
+
return state();
|
|
51
|
+
},
|
|
52
|
+
/** Sets the new password. Other sessions stay signed in, as before. */
|
|
53
|
+
async resetPassword(password: string) {
|
|
54
|
+
await clerkCall(signIn.resetPasswordEmailCode.submitPassword({ password, signOutOfOtherSessions: false }));
|
|
55
|
+
return state();
|
|
56
|
+
},
|
|
57
|
+
async prepareFirstFactor(params: PrepareFirstFactorParams) {
|
|
58
|
+
if (params.strategy === "phone_code") {
|
|
59
|
+
await clerkCall(signIn.phoneCode.sendCode({ phoneNumberId: params.phoneNumberId }));
|
|
60
|
+
} else {
|
|
61
|
+
await clerkCall(signIn.emailCode.sendCode({ emailAddressId: params.emailAddressId }));
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
async attemptFirstFactor(params: { strategy: "email_code" | "phone_code"; code: string }) {
|
|
65
|
+
const { code } = params;
|
|
66
|
+
if (params.strategy === "phone_code") await clerkCall(signIn.phoneCode.verifyCode({ code }));
|
|
67
|
+
else await clerkCall(signIn.emailCode.verifyCode({ code }));
|
|
68
|
+
return state();
|
|
69
|
+
},
|
|
70
|
+
/** Sends the second-factor code. Clerk picks the phone number or email of the sign-in itself. */
|
|
71
|
+
async prepareSecondFactor(params: PrepareSecondFactorParams) {
|
|
72
|
+
if (params.strategy === "phone_code") await clerkCall(signIn.mfa.sendPhoneCode());
|
|
73
|
+
else await clerkCall(signIn.mfa.sendEmailCode());
|
|
74
|
+
},
|
|
75
|
+
async attemptSecondFactor(params: { strategy: SecondFactorStrategy; code: string }) {
|
|
76
|
+
const { code } = params;
|
|
77
|
+
if (params.strategy === "totp") await clerkCall(signIn.mfa.verifyTOTP({ code }));
|
|
78
|
+
else if (params.strategy === "backup_code") await clerkCall(signIn.mfa.verifyBackupCode({ code }));
|
|
79
|
+
else if (params.strategy === "phone_code") await clerkCall(signIn.mfa.verifyPhoneCode({ code }));
|
|
80
|
+
else await clerkCall(signIn.mfa.verifyEmailCode({ code }));
|
|
81
|
+
return state();
|
|
82
|
+
},
|
|
83
|
+
/** Makes the session of a complete sign-in the active one. */
|
|
84
|
+
async setActive() {
|
|
85
|
+
await clerkCall(signIn.finalize());
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
package/src/auth/index.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Clerk + Convex providers and the shared sign-in and sign-up screens. On
|
|
2
|
-
// `@vvedantb/native-ui/auth` only: they import `@clerk/
|
|
2
|
+
// `@vvedantb/native-ui/auth` only: they import `@clerk/expo`, `convex`,
|
|
3
3
|
// `expo-auth-session`, `expo-web-browser` and `expo-router`, and Metro does not
|
|
4
4
|
// tree-shake.
|
|
5
5
|
export { AuthProviders } from "./AuthProviders";
|
|
@@ -36,6 +36,8 @@ export type {
|
|
|
36
36
|
SignInScreenProps,
|
|
37
37
|
SignUpScreenProps,
|
|
38
38
|
} from "./SignInScreen";
|
|
39
|
+
export { ChangePasswordScreen, DeleteAccountScreen, ACCOUNT_MESSAGES } from "./AccountScreens";
|
|
40
|
+
export type { ChangePasswordScreenProps, DeleteAccountScreenProps } from "./AccountScreens";
|
|
39
41
|
export { SecondFactorScreen } from "./SecondFactorScreen";
|
|
40
42
|
export type { SecondFactorScreenProps } from "./SecondFactorScreen";
|
|
41
43
|
export {
|