Это облачная функция, которую я использую для доступа к Firestore
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.getUserCredits = functions.https.onCall(async (data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError("unauthenticated", "User must be signed in.");
}
const uid = context.auth.uid;
const userRef = admin.firestore().doc(`users/${uid}`);
try {
const docSnap = await userRef.get();
if (!docSnap.exists) {
throw new functions.https.HttpsError("not-found", "User document does not exist.");
}
const userData = docSnap.data();
const credits = userData?.credits ?? 0; // Default to 0 if undefined
return { credits };
} catch (error) {
console.error("Error getting user credits:", error);
if (error.code && error.code.startsWith("permission-denied")) {
throw new functions.https.HttpsError("permission-denied", "Access to Firestore denied.");
}
throw new functions.https.HttpsError("internal", "An unexpected error occurred.");
}
});
< /code>
Я отправляю запрос из расширения Chrome, а пользователь входит Пользовательские кредиты из облачной функции: FirebaseError: пользователь должен быть вписан. "
export async function getUserCredits(): Promise {
const auth = Auth.getAuth(); // Initialize Firebase Auth
const user = auth.currentUser;
if (!user) {
console.log("No user is logged in.");
return undefined;
}
// Initialize Firebase Functions
const functions = getFunctions();
try {
// Call the Firebase Cloud Function
const getUserCreditsFunction = httpsCallable(functions, "getUserCredits");
// Call the function, passing the necessary data if needed
const result = await getUserCreditsFunction();
// Get the 'credits' from the result returned by the Cloud Function
const credits = (result.data as { credits: number })?.credits ?? undefined;
return credits;
} catch (error) {
console.log("Error getting user credits from Cloud Function:", error);
return undefined;
}
}
< /code>
Пользователь регистрируется в расширении, у меня есть пользовательские данные в «if», вот почему он вызывает функции. Я попробовал почти все, что мог. Я могу получить доступ к Firestore непосредственно из расширения, но не из облачных функций.
Подробнее здесь: https://stackoverflow.com/questions/794 ... rom-chrome
Как правильно передать аутентификацию в облачные функции при вызове из расширения Chrome ⇐ Javascript
Форум по Javascript
1738943533
Anonymous
[b] Это облачная функция, которую я использую для доступа к Firestore [/b]
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.getUserCredits = functions.https.onCall(async (data, context) => {
if (!context.auth) {
throw new functions.https.HttpsError("unauthenticated", "User must be signed in.");
}
const uid = context.auth.uid;
const userRef = admin.firestore().doc(`users/${uid}`);
try {
const docSnap = await userRef.get();
if (!docSnap.exists) {
throw new functions.https.HttpsError("not-found", "User document does not exist.");
}
const userData = docSnap.data();
const credits = userData?.credits ?? 0; // Default to 0 if undefined
return { credits };
} catch (error) {
console.error("Error getting user credits:", error);
if (error.code && error.code.startsWith("permission-denied")) {
throw new functions.https.HttpsError("permission-denied", "Access to Firestore denied.");
}
throw new functions.https.HttpsError("internal", "An unexpected error occurred.");
}
});
< /code>
Я отправляю запрос из расширения Chrome, а пользователь входит Пользовательские кредиты из облачной функции: FirebaseError: пользователь должен быть вписан. "
export async function getUserCredits(): Promise {
const auth = Auth.getAuth(); // Initialize Firebase Auth
const user = auth.currentUser;
if (!user) {
console.log("No user is logged in.");
return undefined;
}
// Initialize Firebase Functions
const functions = getFunctions();
try {
// Call the Firebase Cloud Function
const getUserCreditsFunction = httpsCallable(functions, "getUserCredits");
// Call the function, passing the necessary data if needed
const result = await getUserCreditsFunction();
// Get the 'credits' from the result returned by the Cloud Function
const credits = (result.data as { credits: number })?.credits ?? undefined;
return credits;
} catch (error) {
console.log("Error getting user credits from Cloud Function:", error);
return undefined;
}
}
< /code>
Пользователь регистрируется в расширении, у меня есть пользовательские данные в «if», вот почему он вызывает функции. Я попробовал почти все, что мог. Я могу получить доступ к Firestore непосредственно из расширения, но не из облачных функций.
Подробнее здесь: [url]https://stackoverflow.com/questions/79421370/how-to-properly-pass-authentication-to-cloud-functions-when-calling-from-chrome[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия