I use flutter and firebase. I'm trying to receive notification by using functions, but i got the follow error : I/flutter ( 3555): DEBUG: Error sending notification: [firebase_functions/unauthenticated] The function must be called while authenticated. See my index.js :
// Import Firebase Functions V2 and Firebase Admin SDK
const { onDocumentCreated } = require('firebase-functions/v2/firestore');
const { https } = require('firebase-functions/v2');
const { setGlobalOptions } = require('firebase-functions/v2');
const admin = require('firebase-admin');
// Initialize Firebase Admin SDK with explicit credential
// This ensures proper initialization even in local development
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
}
// Set global options
setGlobalOptions({
region: "europe-west2",
maxInstances: 10
});
exports.sendChallengeNotification = https.onCall(async (data, context) => {
// Validate authentication
if (!context || !context.auth || !context.auth.uid) {
throw new https.HttpsError(
'unauthenticated',
'The function must be called while authenticated.'
);
}
print("adversaryToken: $adversaryToken");
print("title: $title");
print("body: $body");
// Validate required parameters
const { adversaryToken, title, body } = data;
if (!adversaryToken || !title || !body) {
throw new https.HttpsError(
'invalid-argument',
'Missing required parameters: adversaryToken, title, or body'
);
}
try {
// Get sender's information
const senderDoc = await admin.firestore()
.collection('users')
.doc(context.auth.uid)
.get();
if (!senderDoc.exists) {
throw new https.HttpsError('not-found', 'Sender profile not found');
}
const senderData = senderDoc.data();
const message = {
notification: {
title: title,
body: body,
},
data: {
senderUid: context.auth.uid,
senderName: senderData.name || 'Unknown User',
type: 'challenge',
timestamp: Date.now().toString()
},
token: adversaryToken,
android: {
priority: 'high',
notification: {
clickAction: 'FLUTTER_NOTIFICATION_CLICK'
}
},
apns: {
payload: {
aps: {
sound: 'default'
}
}
}
};
const response = await admin.messaging().send(message);
// Log the successful notification
await admin.firestore().collection('notifications').add({
sender: context.auth.uid,
token: adversaryToken,
title: title,
body: body,
timestamp: admin.firestore.FieldValue.serverTimestamp(),
status: 'sent',
messageId: response
});
return {
success: true,
messageId: response,
timestamp: Date.now()
};
} catch (error) {
console.error('Error in sendChallengeNotification:', error);
// Log the failed notification
await admin.firestore().collection('notifications').add({
sender: context.auth.uid,
token: adversaryToken,
title: title,
body: body,
timestamp: admin.firestore.FieldValue.serverTimestamp(),
status: 'failed',
error: error.message
});
throw new https.HttpsError(
'internal',
'Failed to send notification',
error.message
);
}
});
See my flutter function :
Future<void> sendNotificationToAdversary(String adversaryUserID, String title, String body) async {
try {
print("DEBUG: Received parameters - adversaryUserID: $adversaryUserID, title: $title, body: $body");
if (adversaryUserID.isEmpty) {
print("DEBUG: AdversaryUserID is empty. Exiting.");
return;
}
// Ensure Firebase is initialized
if (Firebase.apps.isEmpty) {
await Firebase.initializeApp();
}
// Check authentication
User? currentUser = FirebaseAuth.instance.currentUser;
if (currentUser == null) {
print("DEBUG: User is not authenticated.");
throw FirebaseAuthException(code: 'unauthenticated', message: 'Please log in.');
}
print("DEBUG: Authenticated user ID: ${currentUser.uid}");
// Retrieve adversary FCM token
DocumentSnapshot userDoc = await FirebaseFirestore.instance.collection('users').doc(adversaryUserID).get();
if (!userDoc.exists) {
print("DEBUG: No user found with ID: $adversaryUserID.");
return;
}
String? adversaryToken = userDoc.get('fcmToken') as String?;
if (adversaryToken == null || adversaryToken.isEmpty) {
print("DEBUG: FCM token missing for adversary.");
return;
}
print("DEBUG: Retrieved FCM token: $adversaryToken");
// Initialize Cloud Functions
FirebaseFunctions functions = FirebaseFunctions.instanceFor(region: 'europe-west2');
print("DEBUG: Initialized Cloud Functions.");
if (title.isEmpty) {
throw Exception('Notification title is required');
}
if (body.isEmpty) {
throw Exception('Notification body is required');
}
// Call the Cloud Function with the adversary's token, title, and body
HttpsCallable callable = functions.httpsCallable('sendChallengeNotification');
final response = await callable.call({
'adversaryToken': adversaryToken,
'title': title,
'body': body,
});
print("DEBUG: Notification sent successfully. Response: $response");
} catch (e) {
print("DEBUG: Error sending notification: $e");
if (e is FirebaseException) {
print("DEBUG: Firebase Error Code: ${e.code}");
print("DEBUG: Firebase Error Message: ${e.message}");
}
}
}
-d '{ "name": "Hello World" }'me@cloudshell:~ (ratemyproject-68373)$ curl -X POST \
-H "Authorization: bearer $(gcloud auth print-identity-token)"
-H "Content-Type: application/json"
-d '{ "name": "Hello World" }' {"error":{"message":"Bad Request","status":"INVALID_ARGUMENT"}}me@cloudshell:~ (ratemyproject-68373)$
In Google Cloud, i already gave the autorisations to allUsers. Any idea? Thanks for advance, for you time.
Edit : @Frank van Puffelen thanks for your answer. Like i wrote it, i already put the good rights and i showed my firebase tools cli login, that show an error. Thanks
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745674898a4639628.html
评论列表(0条)