auto-sync token on refresh and cold start
This commit is contained in:
parent
8317dc74af
commit
064e3d7343
|
|
@ -1,6 +1,8 @@
|
|||
import 'package:didvan/models/notification_message.dart';
|
||||
import 'package:didvan/services/app_home_widget/home_widget_repository.dart';
|
||||
import 'package:didvan/services/app_initalizer.dart';
|
||||
import 'package:didvan/services/auth/auth_api_service.dart';
|
||||
import 'package:didvan/services/auth/token_storage.dart';
|
||||
import 'package:didvan/services/notification/notification_service.dart';
|
||||
import 'package:didvan/services/storage/storage.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
|
|
@ -88,6 +90,46 @@ class FirebaseApi {
|
|||
});
|
||||
|
||||
FirebaseMessaging.onMessage.listen((event) => handleMessage(event));
|
||||
|
||||
// Push the current token to auth-service whenever it changes (Firebase
|
||||
// rotates it every few months, or after app reinstall, or after the
|
||||
// user clears app data). Without this we'd lose push delivery for
|
||||
// already-logged-in users until they explicitly logged in again.
|
||||
FirebaseMessaging.instance.onTokenRefresh.listen((newToken) async {
|
||||
fcmToken = newToken;
|
||||
await _syncTokenToServer(newToken);
|
||||
});
|
||||
|
||||
// Also sync once on every cold start: covers the case where the user
|
||||
// already logged in on a previous build and the server has a stale or
|
||||
// missing token.
|
||||
if (fcmToken != null && fcmToken!.isNotEmpty) {
|
||||
await _syncTokenToServer(fcmToken!);
|
||||
}
|
||||
}
|
||||
|
||||
/// Push the FCM token up to auth-service so push notifications can reach
|
||||
/// this device. Safely no-ops when the user isn't logged in (no userId
|
||||
/// yet) — we'll catch them on the next cold start once they sign in.
|
||||
Future<void> _syncTokenToServer(String token) async {
|
||||
try {
|
||||
final userId = TokenStorage.userId;
|
||||
if (userId == null || userId.isEmpty) {
|
||||
if (kDebugMode) {
|
||||
print('FCM token refresh: skipping — user not logged in yet');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final result = await AuthApiService.instance.updateUser(
|
||||
id: userId,
|
||||
data: {'firebaseToken': token},
|
||||
);
|
||||
if (kDebugMode) {
|
||||
print('FCM token pushed to server: success=${result.isSuccess}');
|
||||
}
|
||||
} catch (e) {
|
||||
if (kDebugMode) print('FCM token sync failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
void handleMessage(RemoteMessage? message) async {
|
||||
|
|
|
|||
Loading…
Reference in New Issue