在 Algolia 和 Firestore 中使用安全规则可以确保您的数据仅被授权用户访问。以下是在 Firebase Firestore 中使用 Algolia 的示例安全规则:
match / {collection} / {document} { allow read: if true; allow write: if false; }
此规则允许所有用户读取 Firestore 中的任何文档,但不允许写入。要允许 Algolia 读取文档并索引它们,可以通过确保该请求来自 Algolia IP 地址之一来激活读取权限:
match / {collection} / {document} { allow read: if request.auth == null && (request.resource == null || get(/databases/$(database)/documents/algolia_ips/$(request.resource.data.ip)).exists); allow write: if false; }
要使此规则正常工作,需要在 Firestore 中创建一个名为“algolia_ips”的集合,并在其中保存 Algolia IP。在每个索引中,需要指定此集合中的权限对象 ID。例如,以下是使用 Algolia 的 Node.js Cloud Function 构建索引的示例代码:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); const algoliasearch = require('algoliasearch');
admin.initializeApp(functions.config().firebase); const ALGOLIA_APP_ID = functions.config().algolia.app_id; const ALGOLIA_API_KEY = functions.config().algolia.api_key; const ALGOLIA_INDEX_NAME = 'posts'; const client = algoliasearch(ALGOLIA_APP_ID, ALGOLIA_API_KEY); const index = client.initIndex(ALGOLIA_INDEX_NAME);
exports.syncAlgoliaWithFirestore = functions.firestore.document('posts/{postId}').onWrite((change, context) => { const postId = context.params.postId;
if (!change.after.exists) { return index.deleteObject(postId); }
const post = change.after.data(); post.objectID = postId;
return index.saveObject(post); });
此