我需要将firebase数据索引到algolia,firebase中的读写规则都需要身份验证(auth!=null)



我使用的是algolia文档中描述的代码。当firebase规则允许在没有身份验证的情况下进行读写时,它就起作用了。这不适用于需要身份验证的数据。我能做些什么来在下面的代码中添加auth?我尝试过使用firebaseadmin,我认为只有当规则被更改为允许读取单个uid时,这种方法才能工作。

const algoliasearch = require('algoliasearch');
const dotenv = require('dotenv');
const firebase = require('firebase');
const admin = require("firebase-admin");
var serviceAccount = require("./config/serviceAccountKey.json");
// load values from the .env file in this directory into process.env
dotenv.config();

admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: process.env.FIREBASE_DATABASE_URL
});
firebase.initializeApp({
databaseURL: process.env.FIREBASE_DATABASE_URL
});
admin
.auth()
.createCustomToken('siddharth')
.then((customToken) => {
console.log(customToken);
firebase.auth().authenticateWithCustomToken(customToken);
})
.catch((error) => {
console.log('Error creating custom token:', error);
});
// admin.auth.createCustomToken('siddharth').then(token => {
// });

const database = firebase.database();
const algolia = algoliasearch(
process.env.ALGOLIA_APP_ID,
process.env.ALGOLIA_API_KEY
);
const index = algolia.initIndex(process.env.ALGOLIA_INDEX_NAME);
database.ref('/questions').once('value', questions => {
const records = [];
questions.forEach(question => {
// get the key and data from the snapshot
const childKey = question.key;
const childData = question.val();
// We set the Algolia objectID as the Firebase .key
childData.objectID = childKey;
// Add object for indexing
records.push(childData);
});
console.log(records);
// Add or update new objects
index
.saveObjects(records)
.then(() => {
console.log('questions imported into Algolia');
})
.catch(error => {
console.error('Error when importing question into Algolia', error);
process.exit(1);
});
});

由于这似乎是一个Node.js脚本,通过使用Admin SDK的服务凭据访问Firebase Authentication,因此您也可以使用该Admin SDK访问数据库。使用服务凭据通过Admin SDK访问Firebase服务可提供完全的管理访问权限,并绕过您可能为数据库配置的任何安全规则。

在代码中,更改:

const database = firebase.database();

收件人:

const database = admin.database();

相关内容

最新更新