如何在 Firebase Cloud Functions 环境中的 FlutterFlow 中创建云函数以通过 ID 删除用户?

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

为了要求能够删除应用程序中的用户数据,需要在 Firebase Cloud Functions 环境中的 FlutterFlow 中创建一个云函数,通过 ID 删除用户。结果就做出了这个解决方案。

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

firebase flutterflow
1个回答
0
投票
    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.