簡體   English   中英

安排 firebase 身份驗證:使用 pubsub 導出到存儲桶

[英]Schedule firebase auth:export to bucket using pubsub

我正在嘗試使用 pubsub 將firebase auth:export安排到存儲桶中。 我的目的是每天備份 auth( firebase auth:export的 output 對我的目的來說非常好)。

這是我試過的pubsub:

const functions = require('firebase-functions')
const exec = require("child_process").exec

const datetime = new Date();
const formattedDate = datetime.toISOString().slice(0,10)

const commandString = `firebase auth:export auth_export_${formattedDate}.json --format=JSON && \
gsutil -m cp -r auth_export_${formattedDate}.json gs://backup_firebase_auth_daily && \
rm auth_export_${formattedDate}.json`

exports.scheduledFirebaseAuthExport = functions.pubsub
    .schedule('every 24 hours')
    .onRun(() => {
        return exec(commandString, (error, stdout, stderr) => {
            if (error) {
                console.log(`error: ${error.message}`);
                process.exit();
                return;
            }
            if (stderr) {
                console.log(`stderr: ${stderr}`);
                process.exit();
                return;
            }
            console.log(stdout);
            process.exit();
        });
    });

但我收到以下錯誤:

/bin/sh: 1: firebase: not found

我假設這是因為我無法在任何運行 pubsub 的環境中運行命令行腳本。

歡迎使用 Google Cloud API 或 firebase 備份 firebase 身份驗證的任何其他方法。

我假設這是因為我無法在任何運行 pubsub 的環境中運行命令行腳本。

實際上,您不能在 Cloud Function 中執行命令行腳本(既不是 Firebase CLI 命令也不是 gsutil 的),這是運行代碼的“環境”(這里 Pub/Sub 是 觸發 Cloud Function 的機制)。


另一方面,由於“Firebase CLI 也可以通過編程方式用作標准節點模塊”,如此所述,您可以通過雲 Function 執行 CLI 的一些命令。

請注意,上面的“一些”一詞以粗體顯示,因為正如同一 Github 頁面中所解釋的那樣:

注意:當在 Cloud Functions 等受限環境中使用時,並非所有firebase-tools命令都可以編程方式工作,因為它們需要訪問本地文件系統。

這正是auth:export命令“將活動項目的用戶帳戶導出到 JSON 或 CSV 文件”的情況。

因此,不幸的是,無法通過 Cloud Function 自動執行此命令。


歡迎使用 Google Cloud API 或 firebase 備份 firebase 身份驗證的任何其他方法。

一種方法是使用管理員 SDK:您可以批量檢索整個用戶列表,例如將其存儲在受保護的 Firestore 集合(或任何其他存儲解決方案)中。 This can be triggered from a Cloud Function (for example a scheduled Cloud Function ) or from a server you own running Node.js, Java, Python, etc.

正如其他答案已經指出的那樣,您可以使用 Cloud Function 通過 auth.export() 將 Auth 文件導出到臨時路徑。 然后,在同一個 function 中,您可以將該文件上傳到存儲桶。 整個過程可能如下所示:

 const {Storage} = require("@google-cloud/storage"); const client = require("firebase-tools"); const split = require("split"); const path = require("path"); const os = require("os"); const fs = require("fs"); exports.scheduledExportAuthData = functions.pubsub.schedule("every 24 hours").onRun(async (context) => { // Google Cloud data const projectId = "your_firebase_project_id"; const bucketName = "your_google_cloud_bucket"; // Path parameters const exportPathPrefix = "authExports/authExport_"; const currentDate = admin.firestore.Timestamp.now().toDate(); const exportPath = exportPathPrefix + currentDate.toISOString().split("T")[0] + ".json"; const tempPath = path.join(os.tmpdir(), path.basename(exportPath)); // Init Storage const storage = new Storage(); const bucket = storage.bucket(bucketName); // Export Auth file in temporary path await client.auth.export(tempPath, {project: projectId}).catch( (error) => console.log(`Error exporting Auth data: ${error}`)); // Uploading the auth file to the GC bucket await bucket.upload(tempPath, { destination: exportPath, }).catch( (error) => console.log(`Error uploading Auth file: ${error}`)); // Once the file has been uploaded delete the temporary file to free up disk space. fs.unlinkSync(tempPath); });

但是,我不知道這種方法在大型數據庫中的性能。

此外,您可以刪除存儲桶中早於 X 天的導出文件。 您可以在相同(或其他)function 中執行此操作,最后添加如下內容:

 exports.scheduledExportAuthData = functions.region("europe-west1").pubsub.schedule("every 24 hours").onRun(async (context) => { // Function begins..... // Delete Auth exports older than 14 days const expirationDays = 14; // Lists files in the bucket filtered by the export path prefix // and delete them the last modified date meets the criteria const options = { prefix: exportPathPrefix, }; const [files] = await bucket.getFiles(options); files.forEach( (file) => { const fileDate = file.updated; if ((currentDate-fileDate)/86400000 > expirationDays) { bucket.file(file.name).delete().catch( (error) => console.log(`Error deleting Auth file: ${error}`)); } }); }); // Function ends

除了使用最后一段代碼,您還可以刪除舊的導出,在您的存儲桶中添加 object 生命周期規則。 例如,要刪除超過 14 天的身份驗證導出,您可以使用捕獲中的配置: Google Cloud Bucket Lifecycle Configuration

firebase firebase-tools現在提供auth.export()功能。 見回購

在此處查看雲 function 的示例實現: 備份 firebase 用戶

import * as tools from 'firebase-tools'

 // Export users to a temporary file
 await tools.auth.export(path, { project: projectId })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM