如何使用 Cloud Functions 在 FlutterFlow 中通过 ID 从 Firestore 中删除用户数据?

问题描述 投票:0回答:1

我需要从 FlutterFlow 应用程序中的 Firestore 中删除用户数据。我如何使用云函数来做到这一点?

firebase google-cloud-firestore google-cloud-functions flutterflow
1个回答
0
投票

尝试各种方法后,发现此解决方案允许您从 Firebase 身份验证中删除用户。

我创建了一个云函数来通过用户的 ID 删除用户,然后从 FlutterFlow 中调用它。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
// To avoid deployment errors, do not call admin.initializeApp() in your code

exports.deleteUser = functions.https.onCall(async (data, context) => {
     // Write your code below!
  console.log('Received data:', data);  // Add this for debugging
     const userId = data.userId;

  if (!context.auth) {
  console.log('userId is missing or empty');  // Add this for debugging
throw new functions.https.HttpsError('unauthenticated', User is not authenticated');
     }
     // Check userId format
     if (typeof userId !== 'string' || userId.length === 0) {
  console.log(Invalid userId format:', userId);  // Add this for debugging
  throw new functions.https.HttpsError('invalid-argument', userId must be a non-empty string');
  }

  if (!userId) {
    throw new functions.https.HttpsError('invalid-argument', No userId provided');
  }

  try {
    // Check if user exists
    await admin.auth().getUser(userId);

    // Delete user from Firebase Authentication
    await admin.auth().deleteUser(userId);

    // Delete user data from Firestore
    await admin.firestore().collection('users').doc(userId).delete();

    console.log(`User ${userId} successfully deleted`);
    return { success: true, message: User successfully deleted' };
  } catch (error) {
    console.error('Error deleting user:', error);
    
    if (error.code === 'auth/user-not-found') {
      throw new functions.https.HttpsError('not-found', User not found');
    } else if (error.code === 'auth/invalid-uid') {
      throw new functions.https.HttpsError('invalid-argument', 'Invalid userId');
    } else {
      throw new functions.https.HttpsError('internal', `Error deleting user:${error.message}`);
    }
  }
  // Write your code above!
});
© www.soinside.com 2019 - 2024. All rights reserved.