forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_provider.dart
More file actions
345 lines (315 loc) · 12.6 KB
/
Copy pathauth_provider.dart
File metadata and controls
345 lines (315 loc) · 12.6 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
import 'dart:async';
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:omi/backend/http/api/apps.dart' as apps_api;
import 'package:omi/backend/preferences.dart';
import 'package:omi/env/env.dart';
import 'package:omi/app_globals.dart';
import 'package:omi/providers/base_provider.dart';
import 'package:omi/services/account_cutover/account_cutover_runtime.dart';
import 'package:omi/services/auth_service.dart';
import 'package:omi/services/auth/auth_token_result.dart';
import 'package:omi/services/notifications.dart';
import 'package:omi/utils/auth/clear_user_state.dart';
import 'package:omi/utils/alerts/app_snackbar.dart';
import 'package:omi/utils/l10n_extensions.dart';
import 'package:omi/utils/logger.dart';
import 'package:omi/utils/platform/platform_manager.dart';
import 'package:omi/utils/platform/platform_service.dart';
/// Runs a provider-link helper, then migrates only the anonymous source proof
/// it returned after the destination account has been established.
Future<ProviderLinkResult?> completeProviderLinkAndMigrate({
required Future<ProviderLinkResult?> Function() linkProvider,
required Future<bool> Function(String sourceUid, String sourceToken) migrate,
}) async {
final result = await linkProvider();
final source = result?.anonymousSourceMigration;
final destinationUid = result?.destinationUid;
if (source != null && destinationUid != null && destinationUid != source.uid) {
await migrate(source.uid, source.token);
}
return result;
}
class AuthenticationProvider extends BaseProvider {
FirebaseAuth get _auth => FirebaseAuth.instance;
User? user;
String? authToken;
bool _loading = false;
bool _requiresReauthentication = false;
int _sessionExpirationGeneration = 0;
StreamSubscription<User?>? _authStateSubscription;
StreamSubscription<User?>? _idTokenSubscription;
StreamSubscription<AuthSessionExpiredEvent>? _sessionExpiredSubscription;
@override
bool get loading => _loading;
bool get requiresReauthentication => _requiresReauthentication;
int get sessionExpirationGeneration => _sessionExpirationGeneration;
AuthenticationProvider({bool initializeListeners = true}) {
if (initializeListeners) _initializeAuthListeners();
}
void _initializeAuthListeners() {
// DEBUG: Log initial state
Logger.debug(
'DEBUG AuthProvider: Initial currentUser=${_auth.currentUser?.uid}, isAnonymous=${_auth.currentUser?.isAnonymous}',
);
Future.microtask(() {
_authStateSubscription = _auth.authStateChanges().distinct((p, n) => p?.uid == n?.uid).listen((User? user) {
AuthService.instance.handleAuthUserChanged(user?.uid);
Logger.debug(
'DEBUG AuthProvider: authStateChanges fired - user=${user?.uid}, isAnonymous=${user?.isAnonymous}',
);
this.user = user;
// Only update SharedPreferences if Firebase has a user
// Don't clear cached credentials - allows fallback for dev builds
if (user != null) {
SharedPreferencesUtil().uid = user.uid;
SharedPreferencesUtil().email = user.email ?? '';
SharedPreferencesUtil().givenName = user.displayName?.split(' ')[0] ?? '';
}
final cutoverOwner = (user != null && !user.isAnonymous) ? user.uid : null;
unawaited(AccountCutoverRuntime.instance.bindAuthenticatedOwner(cutoverOwner));
notifyListeners();
});
_idTokenSubscription = _auth.idTokenChanges().distinct((p, n) => p?.uid == n?.uid).listen((User? user) async {
AuthService.instance.handleAuthUserChanged(user?.uid);
if (user == null) {
Logger.debug('User is currently signed out or the token has been revoked!');
SharedPreferencesUtil().authToken = '';
SharedPreferencesUtil().tokenExpirationTime = 0;
authToken = null;
} else {
Logger.debug('User is signed in at ${DateTime.now()} with user ${user.uid}');
try {
if (_requiresReauthentication ||
SharedPreferencesUtil().authToken.isEmpty ||
DateTime.now().millisecondsSinceEpoch > SharedPreferencesUtil().tokenExpirationTime) {
authToken = await AuthService.instance.getIdToken();
}
if (authToken != null && authToken!.isNotEmpty) {
_requiresReauthentication = false;
}
} catch (e) {
authToken = null;
Logger.debug('Failed to get token: $e');
}
}
notifyListeners();
});
_sessionExpiredSubscription = AuthService.instance.sessionExpiredEvents.listen((event) {
_requiresReauthentication = true;
_sessionExpirationGeneration++;
user = null;
authToken = null;
final rootContext = globalNavigatorKey.currentContext;
if (rootContext != null && rootContext.mounted) {
clearAllUserState(rootContext);
}
notifyListeners();
});
});
}
bool isSignedIn() {
return !_requiresReauthentication && _auth.currentUser != null && !_auth.currentUser!.isAnonymous;
}
bool get _hasFirebaseUser => _auth.currentUser != null && !_auth.currentUser!.isAnonymous;
@override
void dispose() {
_authStateSubscription?.cancel();
_idTokenSubscription?.cancel();
_sessionExpiredSubscription?.cancel();
super.dispose();
}
void setLoading(bool value) {
_loading = value;
notifyListeners();
}
Future<void> onGoogleSignIn(Function() onSignIn) async {
final useWebAuth = Env.useWebAuth;
if (!loading) {
setLoadingState(true);
try {
UserCredential? credential;
if (PlatformService.isMobile && !useWebAuth) {
credential = await AuthService.instance.signInWithGoogleMobile();
} else {
credential = await AuthService.instance.authenticateWithProvider('google');
}
if (credential != null && _hasFirebaseUser) {
await _signIn(onSignIn, credential: credential, authProvider: 'google');
} else {
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.authFailedToSignInWithGoogle ??
'Failed to sign in with Google, please try again.',
);
}
} catch (e) {
Logger.debug('OAuth Google sign in error: $e');
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.authenticationFailed ?? 'Authentication failed. Please try again.',
);
}
setLoadingState(false);
}
}
Future<void> onAppleSignIn(Function() onSignIn) async {
final useWebAuth = Env.useWebAuth;
if (!loading) {
setLoadingState(true);
try {
UserCredential? credential;
if (PlatformService.isMobile && !useWebAuth && !Platform.isAndroid) {
credential = await AuthService.instance.signInWithAppleMobile();
} else {
credential = await AuthService.instance.authenticateWithProvider('apple');
}
if (credential != null && _hasFirebaseUser) {
await _signIn(onSignIn, credential: credential, authProvider: 'apple');
} else {
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.authFailedToSignInWithApple ??
'Failed to sign in with Apple, please try again.',
);
}
} catch (e) {
Logger.debug('OAuth Apple sign in error: $e');
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.authenticationFailed ?? 'Authentication failed. Please try again.',
);
}
setLoadingState(false);
}
}
Future<String?> _getIdToken() async {
try {
final token = await AuthService.instance.getIdToken();
NotificationService.instance.saveNotificationToken();
Logger.debug('Firebase token retrieved successfully');
return token;
} catch (e, stackTrace) {
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.authFailedToRetrieveToken ??
'Failed to retrieve firebase token, please try again.',
);
PlatformManager.instance.crashReporter.reportCrash(e, stackTrace);
return null;
}
}
Future<void> _signIn(Function() onSignIn, {required UserCredential credential, required String authProvider}) async {
final token = await _getIdToken();
if (token != null) {
User currentUser;
try {
currentUser = FirebaseAuth.instance.currentUser!;
} catch (e, stackTrace) {
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.authUnexpectedErrorFirebase ??
'Unexpected error signing in, Firebase error, please try again.',
);
PlatformManager.instance.crashReporter.reportCrash(e, stackTrace);
return;
}
final newUid = currentUser.uid;
SharedPreferencesUtil().uid = newUid;
user = currentUser;
authToken = token;
_requiresReauthentication = false;
PlatformManager.instance.analytics.identify(
authMethod: authProvider,
userCreatedAt: currentUser.metadata.creationTime,
);
if (credential.additionalUserInfo?.isNewUser == true) {
PlatformManager.instance.analytics.accountCreated(authProvider: authProvider);
}
notifyListeners();
onSignIn();
} else {
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.authUnexpectedError ?? 'Unexpected error signing in, please try again',
);
}
}
void openTermsOfService() {
_launchUrl('https://www.omi.me/pages/terms-of-service');
}
void openPrivacyPolicy() {
_launchUrl('https://www.omi.me/pages/privacy');
}
void _launchUrl(String url) async {
final uri = Uri.tryParse(url);
if (uri == null) {
Logger.debug('Invalid URL');
return;
}
await launchUrl(uri, mode: LaunchMode.inAppBrowserView);
}
Future<void> linkWithGoogle() async {
setLoading(true);
try {
final result = await completeProviderLinkAndMigrate(
linkProvider: AuthService.instance.linkWithGoogle,
migrate: migrateAppOwnerId,
);
if (result == null) {
setLoading(false);
return;
}
} catch (e) {
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.authFailedToLinkGoogle ??
'Failed to link with Google, please try again.',
);
rethrow;
} finally {
setLoading(false);
}
}
Future<void> linkWithApple() async {
setLoading(true);
try {
final appleProvider = AppleAuthProvider();
try {
await FirebaseAuth.instance.currentUser?.linkWithProvider(appleProvider);
} catch (e) {
if (e is FirebaseAuthException && e.code == 'credential-already-in-use') {
// Get existing user credentials
final existingCred = e.credential;
final oldUserId = FirebaseAuth.instance.currentUser?.uid;
final sourceToken = await FirebaseAuth.instance.currentUser?.getIdToken();
// Sign out current anonymous user
AuthService.instance.handleAuthUserChanged(null);
await FirebaseAuth.instance.signOut();
// Sign in with existing account
await FirebaseAuth.instance.signInWithCredential(existingCred!);
final newUserId = FirebaseAuth.instance.currentUser?.uid;
if (newUserId != null) AuthService.instance.markAuthenticatedUser(newUserId);
await AuthService.instance.getIdToken();
SharedPreferencesUtil().onboardingCompleted = false;
SharedPreferencesUtil().uid = newUserId ?? '';
SharedPreferencesUtil().email = FirebaseAuth.instance.currentUser?.email ?? '';
SharedPreferencesUtil().givenName = FirebaseAuth.instance.currentUser?.displayName?.split(' ')[0] ?? '';
if (oldUserId != null && newUserId != null && sourceToken != null) {
await migrateAppOwnerId(oldUserId, sourceToken);
}
return;
}
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.authFailedToLinkApple ??
'Failed to link with Apple, please try again.',
);
rethrow;
}
} catch (e) {
Logger.debug('Error linking with Apple: $e');
AppSnackbar.showSnackbarError(
globalNavigatorKey.currentContext?.l10n.authFailedToLinkApple ?? 'Failed to link with Apple, please try again.',
);
rethrow;
} finally {
setLoading(false);
}
}
Future<bool> migrateAppOwnerId(String oldId, String sourceToken) async {
return await apps_api.migrateAppOwnerId(oldId, sourceToken);
}
}