From 064e3d7343e78bdec9770f6c71fdd1f0cf9ad8c7 Mon Sep 17 00:00:00 2001 From: "Mr.Jebelli" Date: Mon, 22 Jun 2026 14:40:10 +0330 Subject: [PATCH] auto-sync token on refresh and cold start --- lib/services/notification/firebase_api.dart | 42 +++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/lib/services/notification/firebase_api.dart b/lib/services/notification/firebase_api.dart index 559487f..d1e3678 100644 --- a/lib/services/notification/firebase_api.dart +++ b/lib/services/notification/firebase_api.dart @@ -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 _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 {