-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathSignIn.tsx
More file actions
833 lines (734 loc) · 25.3 KB
/
SignIn.tsx
File metadata and controls
833 lines (734 loc) · 25.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
/**
* Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {
AsgardeoRuntimeError,
EmbeddedFlowComponentV2 as EmbeddedFlowComponent,
EmbeddedFlowType,
EmbeddedSignInFlowResponseV2,
EmbeddedSignInFlowRequestV2,
EmbeddedSignInFlowStatusV2,
EmbeddedSignInFlowTypeV2,
FlowMetadataResponse,
Preferences,
} from '@asgardeo/browser';
import {FC, ReactElement, useState, useEffect, useRef, ReactNode} from 'react';
// eslint-disable-next-line import/no-named-as-default
import BaseSignIn, {BaseSignInProps} from './BaseSignIn';
import useAsgardeo from '../../../../../contexts/Asgardeo/useAsgardeo';
import useTranslation from '../../../../../hooks/useTranslation';
import {useOAuthCallback} from '../../../../../hooks/v2/useOAuthCallback';
import {initiateOAuthRedirect} from '../../../../../utils/oauth';
import {normalizeFlowResponse} from '../../../../../utils/v2/flowTransformer';
import {handlePasskeyAuthentication, handlePasskeyRegistration} from '../../../../../utils/v2/passkey';
/**
* Render props function parameters
*/
export interface SignInRenderProps {
/**
* Additional data from the flow response containing contextual information
* like consent prompt details and session timeouts.
*/
additionalData?: Record<string, any>;
/**
* Current flow components
*/
components: EmbeddedFlowComponent[];
/**
* Current error if any
*/
error: Error | null;
/**
* Function to manually initialize the flow
*/
initialize: () => Promise<void>;
/**
* Whether the flow has been initialized
*/
isInitialized: boolean;
/**
* Loading state indicator
*/
isLoading: boolean;
/**
* Flag indicating whether the flow step timeout has expired.
* Consuming components can use this to disable submit buttons.
*/
isTimeoutDisabled?: boolean;
/**
* Flow metadata returned by the platform (v2 only). `null` while loading or unavailable.
*/
meta: FlowMetadataResponse | null;
/**
* Function to submit authentication data (primary)
*/
onSubmit: (payload: EmbeddedSignInFlowRequestV2) => Promise<void>;
}
/**
* Props for the SignIn component.
* Matches the interface from the main SignIn component for consistency.
*/
export type SignInProps = {
/**
* Render props function for custom UI
*/
children?: (props: SignInRenderProps) => ReactNode;
/**
* Custom CSS class name for the form container.
*/
className?: string;
/**
* Callback function called when authentication fails.
* @param error - The error that occurred during authentication.
*/
onError?: (error: Error) => void;
/**
* Callback function called when authentication is successful.
* @param authData - The authentication data returned upon successful completion.
*/
onSuccess?: (authData: Record<string, any>) => void;
/**
* Component-level preferences to override global i18n and theme settings.
* Preferences are deep-merged with global ones, with component preferences
* taking precedence. Affects this component and all its descendants.
*/
preferences?: Preferences;
/**
* Size variant for the component.
*/
size?: 'small' | 'medium' | 'large';
/**
* Theme variant for the component.
*/
variant?: BaseSignInProps['variant'];
};
/**
* State for tracking passkey registration
*/
interface PasskeyState {
actionId: string | null;
challenge: string | null;
creationOptions: string | null;
error: Error | null;
flowId: string | null;
isActive: boolean;
}
/**
* A component-driven SignIn component that provides authentication flow with pre-built styling.
* This component handles the flow API calls for authentication and delegates UI logic to BaseSignIn.
* It automatically transforms simple input-based responses into component-driven UI format.
*
* @example
* // Default UI
* ```tsx
* import { SignIn } from '@asgardeo/react/component-driven';
*
* const App = () => {
* return (
* <SignIn
* onSuccess={(authData) => {
* console.log('Authentication successful:', authData);
* }}
* onError={(error) => {
* console.error('Authentication failed:', error);
* }}
* size="medium"
* variant="outlined"
* />
* );
* };
* ```
*
* @example
* // Custom UI with render props
* ```tsx
* import { SignIn } from '@asgardeo/react/component-driven';
*
* const App = () => {
* return (
* <SignIn
* onSuccess={(authData) => console.log('Success:', authData)}
* onError={(error) => console.error('Error:', error)}
* >
* {({signIn, isLoading, components, error, isInitialized}) => (
* <div className="custom-signin">
* <h1>Custom Sign In</h1>
* {!isInitialized ? (
* <p>Initializing...</p>
* ) : error ? (
* <div className="error">{error.message}</div>
* ) : (
* <form onSubmit={(e) => {
* e.preventDefault();
* signIn({inputs: {username: 'user', password: 'pass'}});
* }}>
* <button type="submit" disabled={isLoading}>
* {isLoading ? 'Signing in...' : 'Sign In'}
* </button>
* </form>
* )}
* </div>
* )}
* </SignIn>
* );
* };
* ```
*/
const SignIn: FC<SignInProps> = ({
className,
preferences,
size = 'medium',
onSuccess,
onError,
variant,
children,
}: SignInProps): ReactElement => {
const {applicationId, afterSignInUrl, signIn, isInitialized, isLoading, meta} = useAsgardeo();
const {t} = useTranslation(preferences?.i18n);
// State management for the flow
const [components, setComponents] = useState<EmbeddedFlowComponent[]>([]);
const [additionalData, setAdditionalData] = useState<Record<string, any>>({});
const [currentFlowId, setCurrentFlowId] = useState<string | null>(null);
const [isFlowInitialized, setIsFlowInitialized] = useState(false);
const [flowError, setFlowError] = useState<Error | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const [isTimeoutDisabled, setIsTimeoutDisabled] = useState<boolean>(false);
const [passkeyState, setPasskeyState] = useState<PasskeyState>({
actionId: null,
challenge: null,
creationOptions: null,
error: null,
flowId: null,
isActive: false,
});
const initializationAttemptedRef: any = useRef(false);
const oauthCodeProcessedRef: any = useRef(false);
const passkeyProcessedRef: any = useRef(false);
/**
* Sets flowId between sessionStorage and state.
* This ensures both are always in sync.
*/
const setFlowId = (flowId: string | null): void => {
setCurrentFlowId(flowId);
if (flowId) {
sessionStorage.setItem('asgardeo_flow_id', flowId);
} else {
sessionStorage.removeItem('asgardeo_flow_id');
}
};
/**
* Clear all flow-related storage and state.
*/
const clearFlowState = (): void => {
setFlowId(null);
setIsFlowInitialized(false);
sessionStorage.removeItem('asgardeo_auth_id');
setIsTimeoutDisabled(false);
// Reset refs to allow new flows to start properly
oauthCodeProcessedRef.current = false;
};
/**
* Parse URL parameters used in flows.
*/
const getUrlParams = (): any => {
const urlParams: any = new URL(window?.location?.href ?? '').searchParams;
return {
applicationId: urlParams.get('applicationId'),
authId: urlParams.get('authId'),
code: urlParams.get('code'),
error: urlParams.get('error'),
errorDescription: urlParams.get('error_description'),
flowId: urlParams.get('flowId'),
nonce: urlParams.get('nonce'),
state: urlParams.get('state'),
};
};
/**
* Handle authId from URL and store it in sessionStorage.
*/
const handleAuthId = (authId: string | null): void => {
if (authId) {
sessionStorage.setItem('asgardeo_auth_id', authId);
}
};
/**
* Clean up OAuth-related URL parameters from the browser URL.
*/
const cleanupOAuthUrlParams = (includeNonce: boolean = false): void => {
if (!window?.location?.href) return;
const url: any = new URL(window.location.href);
url.searchParams.delete('error');
url.searchParams.delete('error_description');
url.searchParams.delete('code');
url.searchParams.delete('state');
if (includeNonce) {
url.searchParams.delete('nonce');
}
window?.history?.replaceState({}, '', url.toString());
};
/**
* Clean up flow-related URL parameters (flowId, authId) from the browser URL.
* Used after flowId is set in state to prevent using invalidated flowId from URL.
*/
const cleanupFlowUrlParams = (): void => {
if (!window?.location?.href) return;
const url: any = new URL(window.location.href);
url.searchParams.delete('flowId');
url.searchParams.delete('authId');
url.searchParams.delete('applicationId');
window?.history?.replaceState({}, '', url.toString());
};
/**
* Set error state and call onError callback.
* Ensures isFlowInitialized is true so errors can be displayed in the UI.
*/
const setError = (error: Error): void => {
setFlowError(error);
setIsFlowInitialized(true);
onError?.(error);
};
/**
* Handle OAuth error from URL parameters.
* Clears flow state, creates error, and cleans up URL.
*/
const handleOAuthError = (error: string, errorDescription: string | null): void => {
clearFlowState();
const errorMessage: any = errorDescription || `OAuth error: ${error}`;
const err: any = new AsgardeoRuntimeError(errorMessage, 'SIGN_IN_ERROR', 'react');
setError(err);
cleanupOAuthUrlParams(true);
};
/**
* Handle REDIRECTION response by storing flow state and redirecting to OAuth provider.
*/
const handleRedirection = (response: EmbeddedSignInFlowResponseV2): boolean => {
if (response.type === EmbeddedSignInFlowTypeV2.Redirection) {
const redirectURL: any = (response.data as any)?.redirectURL || (response as any)?.redirectURL;
if (redirectURL && window?.location) {
if (response.flowId) {
setFlowId(response.flowId);
}
const urlParams: any = getUrlParams();
handleAuthId(urlParams.authId);
initiateOAuthRedirect(redirectURL);
return true;
}
}
return false;
};
/**
* Initialize the authentication flow.
* Priority: flowId > applicationId (from context) > applicationId (from URL)
*/
const initializeFlow = async (): Promise<void> => {
const urlParams: any = getUrlParams();
// Reset OAuth code processed ref when starting a new flow
oauthCodeProcessedRef.current = false;
handleAuthId(urlParams.authId);
const effectiveApplicationId: any = applicationId || urlParams.applicationId;
if (!urlParams.flowId && !effectiveApplicationId) {
const error: any = new AsgardeoRuntimeError(
'Either flowId or applicationId is required for authentication',
'SIGN_IN_ERROR',
'react',
);
setError(error);
throw error;
}
try {
setFlowError(null);
let response: EmbeddedSignInFlowResponseV2;
if (urlParams.flowId) {
response = (await signIn({
flowId: urlParams.flowId,
})) as EmbeddedSignInFlowResponseV2;
} else {
response = (await signIn({
applicationId: effectiveApplicationId,
flowType: EmbeddedFlowType.Authentication,
})) as EmbeddedSignInFlowResponseV2;
}
if (handleRedirection(response)) {
return;
}
const {
flowId: normalizedFlowId,
components: normalizedComponents,
additionalData: normalizedAdditionalData,
} = normalizeFlowResponse(
response,
t,
{
resolveTranslations: false,
},
meta,
);
if (normalizedFlowId && normalizedComponents) {
setFlowId(normalizedFlowId);
setComponents(normalizedComponents);
setAdditionalData(normalizedAdditionalData ?? {});
setIsFlowInitialized(true);
setIsTimeoutDisabled(false);
// Clean up flowId from URL after setting it in state
cleanupFlowUrlParams();
}
} catch (error) {
const err: any = error as any;
clearFlowState();
// Extract error message from response or error object
const errorMessage: any = err?.failureReason || (err instanceof Error ? err.message : String(err));
// Set error with the extracted message
setError(new Error(errorMessage));
initializationAttemptedRef.current = false;
}
};
/**
* Initialize the flow and handle cleanup of stale flow state.
*/
useEffect(() => {
const urlParams: any = getUrlParams();
// Check for OAuth error in URL
if (urlParams.error) {
handleOAuthError(urlParams.error, urlParams.errorDescription);
return;
}
handleAuthId(urlParams.authId);
// Skip OAuth code processing - let the dedicated OAuth useEffect handle it
// No action needed here as the dedicated useEffect will handle it
}, []);
useEffect(() => {
// Only initialize if we're not processing an OAuth callback or submission
const currentUrlParams: any = getUrlParams();
if (
isInitialized &&
!isLoading &&
!isFlowInitialized &&
!initializationAttemptedRef.current &&
!currentFlowId &&
!currentUrlParams.code &&
!currentUrlParams.state &&
!isSubmitting &&
!oauthCodeProcessedRef.current
) {
initializationAttemptedRef.current = true;
initializeFlow();
}
}, [isInitialized, isLoading, isFlowInitialized, currentFlowId]);
/**
* Handle step timeout if configured in additionalData.
*/
useEffect(() => {
const timeoutMs: number = Number(additionalData?.['stepTimeout']) || 0;
if (timeoutMs <= 0 || !isFlowInitialized) {
setIsTimeoutDisabled(false);
return undefined;
}
const remaining: number = Math.max(0, Math.floor((timeoutMs - Date.now()) / 1000));
const handleTimeout = (): void => {
const errorMessage: string = t('errors.signin.timeout') || 'Time allowed to complete the step has expired.';
setError(new Error(errorMessage));
setIsTimeoutDisabled(true);
};
if (remaining <= 0) {
handleTimeout();
return undefined;
}
const timerId: any = setTimeout(() => {
handleTimeout();
}, remaining * 1000);
return () => clearTimeout(timerId);
}, [additionalData?.['stepTimeout'], isFlowInitialized, t]);
/**
* Handle form submission from BaseSignIn or render props.
*/
const handleSubmit = async (payload: EmbeddedSignInFlowRequestV2): Promise<void> => {
// Use flowId from payload if available, otherwise fall back to currentFlowId
const effectiveFlowId: any = payload.flowId || currentFlowId;
if (!effectiveFlowId) {
throw new Error('No active flow ID');
}
const processedInputs: Record<string, any> = {...payload.inputs};
// Auto-compile consent decisions if we are currently on a consent prompt step
if (additionalData?.['consentPrompt']) {
try {
const consentPromptRawData: any = additionalData['consentPrompt'];
const purposes: any[] =
typeof consentPromptRawData === 'string'
? JSON.parse(consentPromptRawData)
: consentPromptRawData.purposes || consentPromptRawData;
// Find the action component to determine if it was a deny action
let isDeny: boolean = false;
if (payload.action) {
// Flatten components to find the action
const findAction = (comps: any[]): any => {
if (!comps || comps.length === 0) return null;
const found: any = comps.find((c: any) => c.id === payload.action);
if (found) return found;
return comps.reduce((acc: any, c: any) => {
if (acc) return acc;
if (c.components) return findAction(c.components);
return null;
}, null);
};
const submitAction: any = findAction(components);
if (submitAction && submitAction.variant?.toLowerCase() !== 'primary') {
isDeny = true;
}
}
const decisions: any = {
purposes: purposes.map((p: any) => ({
approved: !isDeny,
elements: [
...(p.essential || []).map((attr: string) => ({
approved: !isDeny,
name: attr,
})),
...(p.optional || []).map((attr: string) => {
const key: string = `__consent_opt__${p.purposeId}__${attr}`;
return {
approved: isDeny ? false : processedInputs[key] !== 'false',
name: attr,
};
}),
],
purposeName: p.purposeName,
})),
};
processedInputs['consent_decisions'] = JSON.stringify(decisions);
// Cleanup temporary consent tracking fields from inputs
Object.keys(processedInputs).forEach((key: string) => {
if (key.startsWith('__consent_opt__')) {
delete processedInputs[key];
}
});
} catch (e) {
// Failed to construct consent_decisions payload automatically
}
}
try {
setIsSubmitting(true);
setFlowError(null);
const response: EmbeddedSignInFlowResponseV2 = (await signIn({
flowId: effectiveFlowId,
...payload,
inputs: processedInputs,
})) as EmbeddedSignInFlowResponseV2;
if (handleRedirection(response)) {
return;
}
if (
response.data?.additionalData?.['passkeyChallenge'] ||
response.data?.additionalData?.['passkeyCreationOptions']
) {
const {passkeyChallenge, passkeyCreationOptions}: any = response.data.additionalData;
const effectiveFlowIdForPasskey: any = response.flowId || effectiveFlowId;
// Reset passkey processed ref to allow processing
passkeyProcessedRef.current = false;
// Set passkey state to trigger the passkey
setPasskeyState({
actionId: 'submit',
challenge: passkeyChallenge,
creationOptions: passkeyCreationOptions,
error: null,
flowId: effectiveFlowIdForPasskey,
isActive: true,
});
setIsSubmitting(false);
return;
}
const {
flowId: normalizedFlowId,
components: normalizedComponents,
additionalData: normalizedAdditionalData,
} = normalizeFlowResponse(
response,
t,
{
resolveTranslations: false,
},
meta,
);
// Handle Error flow status - flow has failed and is invalidated
if (response.flowStatus === EmbeddedSignInFlowStatusV2.Error) {
clearFlowState();
// Extract failureReason from response if available
const failureReason: any = (response as any)?.failureReason;
const errorMessage: any = failureReason || 'Authentication flow failed. Please try again.';
const err: any = new Error(errorMessage);
setError(err);
cleanupFlowUrlParams();
// Throw the error so it's caught by the catch block and propagated to BaseSignIn
throw err;
}
if (response.flowStatus === EmbeddedSignInFlowStatusV2.Complete) {
// Get redirectUrl from response (from /oauth2/auth/callback) or fall back to afterSignInUrl
const redirectUrl: any = (response as any)?.redirectUrl || (response as any)?.redirect_uri;
const finalRedirectUrl: any = redirectUrl || afterSignInUrl;
// Clear submitting state before redirect
setIsSubmitting(false);
// Clear all OAuth-related storage on successful completion
setFlowId(null);
setIsFlowInitialized(false);
sessionStorage.removeItem('asgardeo_flow_id');
sessionStorage.removeItem('asgardeo_auth_id');
// Clean up OAuth URL params before redirect
cleanupOAuthUrlParams(true);
if (onSuccess) {
onSuccess({
redirectUrl: finalRedirectUrl,
...(response.data || {}),
});
}
if (finalRedirectUrl && window?.location) {
window.location.href = finalRedirectUrl;
}
return;
}
// Update flowId if response contains a new one
if (normalizedFlowId && normalizedComponents) {
setFlowId(normalizedFlowId);
setComponents(normalizedComponents);
setAdditionalData(normalizedAdditionalData ?? {});
setIsTimeoutDisabled(false);
// Ensure flow is marked as initialized when we have components
setIsFlowInitialized(true);
// Clean up flowId from URL after setting it in state
cleanupFlowUrlParams();
// Display failure reason from INCOMPLETE response
if ((response as any)?.failureReason) {
setFlowError(new Error((response as any).failureReason));
}
}
} catch (error) {
const err: any = error as any;
clearFlowState();
// Extract error message from response or error object
const errorMessage: any = err?.failureReason || (err instanceof Error ? err.message : String(err));
setError(new Error(errorMessage));
return;
} finally {
setIsSubmitting(false);
}
};
/**
* Handle authentication errors.
*/
const handleError = (error: Error): void => {
setError(error);
};
useOAuthCallback({
currentFlowId,
isInitialized: isInitialized && !isLoading,
isSubmitting,
onError: (err: any) => {
clearFlowState();
setError(err instanceof Error ? err : new Error(String(err)));
},
onSubmit: async (payload: any) => handleSubmit({flowId: payload.flowId, inputs: payload.inputs}),
processedRef: oauthCodeProcessedRef,
setFlowId,
});
/**
* Handle passkey authentication/registration when passkey state becomes active.
* This effect auto-triggers the browser passkey popup and submits the result.
*/
useEffect(() => {
if (!passkeyState.isActive || (!passkeyState.challenge && !passkeyState.creationOptions) || !passkeyState.flowId) {
return;
}
// Prevent re-processing
if (passkeyProcessedRef.current) {
return;
}
passkeyProcessedRef.current = true;
const performPasskeyProcess = async (): Promise<void> => {
let inputs: Record<string, string>;
if (passkeyState.challenge) {
const passkeyResponse: any = await handlePasskeyAuthentication(passkeyState.challenge!);
const passkeyResponseObj: any = JSON.parse(passkeyResponse);
inputs = {
authenticatorData: passkeyResponseObj.response.authenticatorData,
clientDataJSON: passkeyResponseObj.response.clientDataJSON,
credentialId: passkeyResponseObj.id,
signature: passkeyResponseObj.response.signature,
userHandle: passkeyResponseObj.response.userHandle,
};
} else if (passkeyState.creationOptions) {
const passkeyResponse: any = await handlePasskeyRegistration(passkeyState.creationOptions!);
const passkeyResponseObj: any = JSON.parse(passkeyResponse);
inputs = {
attestationObject: passkeyResponseObj.response.attestationObject,
clientDataJSON: passkeyResponseObj.response.clientDataJSON,
credentialId: passkeyResponseObj.id,
};
} else {
throw new Error('No passkey challenge or creation options available');
}
await handleSubmit({
flowId: passkeyState.flowId!,
inputs,
});
};
performPasskeyProcess()
.then(() => {
setPasskeyState({
actionId: null,
challenge: null,
creationOptions: null,
error: null,
flowId: null,
isActive: false,
});
})
.catch((error: any) => {
setPasskeyState((prev: any) => ({...prev, error: error as Error, isActive: false}));
setFlowError(error as Error);
onError?.(error as Error);
});
}, [passkeyState.isActive, passkeyState.challenge, passkeyState.creationOptions, passkeyState.flowId]);
if (children) {
const renderProps: SignInRenderProps = {
additionalData,
components,
error: flowError,
initialize: initializeFlow,
isInitialized: isFlowInitialized,
isLoading: isLoading || isSubmitting || !isInitialized,
isTimeoutDisabled,
meta,
onSubmit: handleSubmit,
};
return <>{children(renderProps)}</>;
}
// Otherwise, render the default BaseSignIn component
return (
<BaseSignIn
additionalData={additionalData}
components={components}
isLoading={isLoading || !isInitialized || !isFlowInitialized}
isTimeoutDisabled={isTimeoutDisabled}
onSubmit={handleSubmit}
onError={handleError}
error={flowError}
className={className}
size={size}
variant={variant}
preferences={preferences}
/>
);
};
export default SignIn;