|
| 1 | +import 'dart:async'; |
| 2 | + |
| 3 | +import 'package:firebase_auth/firebase_auth.dart' hide PhoneAuthProvider; |
| 4 | +import 'package:firebase_ui_auth/firebase_ui_auth.dart'; |
| 5 | +import 'package:firebase_ui_auth/src/widgets/internal/universal_page_route.dart'; |
| 6 | +import 'package:flutter/scheduler.dart'; |
| 7 | +import 'package:flutter/widgets.dart'; |
| 8 | + |
| 9 | +Future<UserCredential> startMFAVerification({ |
| 10 | + required BuildContext context, |
| 11 | + required MultiFactorResolver resolver, |
| 12 | +}) async { |
| 13 | + if (resolver.hints.first is PhoneMultiFactorInfo) { |
| 14 | + return startPhoneMFAVerification( |
| 15 | + context: context, |
| 16 | + resolver: resolver, |
| 17 | + ); |
| 18 | + } else { |
| 19 | + throw Exception('Unsupported MFA type'); |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +Future<UserCredential> startPhoneMFAVerification({ |
| 24 | + required BuildContext context, |
| 25 | + required MultiFactorResolver resolver, |
| 26 | + FirebaseAuth? auth, |
| 27 | +}) async { |
| 28 | + final session = resolver.session; |
| 29 | + final hint = resolver.hints.first; |
| 30 | + final completer = Completer<UserCredential>(); |
| 31 | + final navigator = Navigator.of(context); |
| 32 | + |
| 33 | + final provider = PhoneAuthProvider(); |
| 34 | + provider.auth = auth ?? FirebaseAuth.instance; |
| 35 | + |
| 36 | + final flow = PhoneAuthFlow( |
| 37 | + auth: auth ?? FirebaseAuth.instance, |
| 38 | + action: AuthAction.none, |
| 39 | + provider: PhoneAuthProvider(), |
| 40 | + ); |
| 41 | + |
| 42 | + provider.authListener = flow; |
| 43 | + |
| 44 | + final flowKey = Object(); |
| 45 | + |
| 46 | + SchedulerBinding.instance.addPostFrameCallback((timeStamp) { |
| 47 | + provider.sendVerificationCode( |
| 48 | + hint: hint as PhoneMultiFactorInfo, |
| 49 | + multiFactorSession: session, |
| 50 | + action: AuthAction.none, |
| 51 | + ); |
| 52 | + }); |
| 53 | + |
| 54 | + navigator.push( |
| 55 | + createPageRoute( |
| 56 | + context: context, |
| 57 | + builder: (context) { |
| 58 | + return AuthFlowBuilder<PhoneAuthController>( |
| 59 | + flow: flow, |
| 60 | + flowKey: flowKey, |
| 61 | + child: SMSCodeInputScreen( |
| 62 | + flowKey: flowKey, |
| 63 | + action: AuthAction.none, |
| 64 | + auth: auth, |
| 65 | + actions: [ |
| 66 | + AuthStateChangeAction<CredentialReceived>((context, inner) { |
| 67 | + final cred = inner.credential as PhoneAuthCredential; |
| 68 | + final assertion = PhoneMultiFactorGenerator.getAssertion(cred); |
| 69 | + try { |
| 70 | + final cred = resolver.resolveSignIn(assertion); |
| 71 | + completer.complete(cred); |
| 72 | + } catch (e) { |
| 73 | + completer.completeError(e); |
| 74 | + } |
| 75 | + }), |
| 76 | + ], |
| 77 | + ), |
| 78 | + ); |
| 79 | + }, |
| 80 | + ), |
| 81 | + ); |
| 82 | + |
| 83 | + final cred = await completer.future; |
| 84 | + |
| 85 | + navigator.pop(); |
| 86 | + return cred; |
| 87 | +} |
0 commit comments