I am trying to access a Firebase Firestore DB from a GCP Cloud Function - the function is not part of the Firebase project - so two separate projects. When I config/init the DB I get a permissions error
def hello_world(request):
import firebase_admin
import flask
import json
from flask import request
from firebase_admin import credentials
from firebase_admin import firestore
try:
firebase_admin.initialize_app(options={
'apiKey': '<appkey>',
'authDomain': '<authdomain>',
'databaseURL': '<url>',
'projectId': '<projID>',
'storageBucket': '<bucket>',
'messagingSenderId': '<id>',
'appId': '<app ID>'
})
except:
print("DB already init")
#end db init
db = firestore.client()
# end db setup
I expect/want the result to be to initialize the DB so I can read/write to it, but I get an error:
Error: function crashed. Details:
403 Missing or insufficient permissions.
You seem to be using the app init settings for web, you need to use the sdk key instead. Go to Settings -> Services Account -> and generate your key.
Include the json file instead of those parameters. Hope this helps!
Related
when I was trying to connect google firebase real time database, I got this error:
ValueError: The default Firebase app already exists. This means you called
initialize_app() more than once without providing an app name as the second argument. In
most cases you only need to call initialize_app() once. But if you do want to initialize
multiple apps, pass a second argument to initialize_app() to give each app a unique name.
Here is my code:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
cred = credentials.Certificate('firebase-sdk.json')
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://test-139a6-default-rtdb.firebaseio.com/'
})
You only need to initialize (create) the app once. When you have created the app, use get_app instead:
# The default app's name is "[DEFAULT]"
firebase_admin.get_app(name='[DEFAULT]')
You need to initialize the Admin SDK only once. You can check if the Admin SDK is already initialized using this if statement:
if not firebase_admin._apps:
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://test-139a6-default-rtdb.firebaseio.com/'
})
I am using firestore in python with firebase_admin and want to access the authentication module of firebase. I have created data in authentication with auth.create_user() by importing auth from firebase_admin.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore, auth
cred = credentials.Certificate("servicesAccountKey.json")
firebase_admin.initialize_app(cred)
db = firestore.client()
# <<<<<<<<<<<<<<<<<<<<******************** SignUp ********************>>>>>>>>>>>>>>>>>>>>
def signUp(userObject):
user = userObject.getUser()
auth.create_user(uid=user['cnic'], email=user['email'], password=user['password']) "
Now I want to authenticate for signIn but not able to find module auth.sign_in_with_email_and_password. This module is available with realtime database which connects with pyerbase but not in firestore connected with firebase_admin.
def signIn(cnic,password):
auth.sign_in_with_email_and_password(cnic, password)
I can use auth with pyrebase but i have to import pyrebase and firebase_admin both which i dont want it.
Is any module available for firebase_admin for authentication to signIN ?
The Admin SDKs for Firebase run with elevated, administrative privileges, and don't have any capability to sign in a user.
You may want to consider your use-case: if you ship the administrative credentials (that the Admin SDK needs/uses) to your regular users they have full access to your Firebase and Google Cloud project. You'll want to separate the administrative functionality of your app from the end-user functionality, and use either the REST SDK or a client-side SDK (like Pyrebase) for the end-user app.
i'm trying to use firebase in colab with Python. But there is unsolvable error,
so i need some help.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
cred = credentials.Certificate('/content/myKey.json')
firebase_admin.initialize_app(cred) # error in this line
db = firestore.client()
ValueError: : The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name.
What can i do for solving this problem?
i also found similar answer with this, so i tried some many tips in there, like below.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
if not firebase_admin._apps:
cred = credentials.Certificate('/content/foodle-94e80-firebase-adminsdk-zr21t- f02504e9fb.json')
firebase_admin.initialize_app(cred)
else:
app = firebase_admin.get_app()
db = firestore.client(app) # new error in this line
but new error is confusing me.
DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started
What can i do?
Looks like there's a default instance of the Firebase app getting initialized somewhere. When the default instance gets created, it uses GOOGLE_APPLICATION_CREDENTIALS instead of the credentials you pass in manually.
You can either provide GOOGLE_APPLICATION_CREDENTIALS to the script, or ignore the default instance of the firebase app and create an explicitly named one.
To create an explicitly named app, change your code to provide a name:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
cred = credentials.Certificate('/content/myKey.json')
firebase_admin.initialize_app(credential=cred, name='myApp')
db = firestore.client()
To provide GOOGLE_APPLICATION_CREDENTIALS and use the default app:
If you're running your python script from the console, you can provide a value for that by running
export GOOGLE_APPLICATION_CREDENTIALS='/content/myKey.json'
In colab, you need to add this to your script:
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/content/myKey.json"
After this you can run your second example.
(To get the credentials JSON go to this page, select your firebase-adminsdk service account, click 'ADD KEY', 'Create new key', select JSON as your option and download the resulting file.)
In my case it worked with
cred = credentials.Certificate("/content/drive/My Drive/Colab Notebooks/LALALA.json")
firebase_admin.initialize_app(cred)
I want to retrieve some data by a firebase database with using the official library for python (firebase_admin) instead of pyrebase or python-firebase.
I try to execute the following lines of code:
from firebase_admin import db
from firebase_admin import credentials
import firebase_admin
cred = credentials.Certificate('https://project_name.firebaseio.com/.json')
firebase_admin.initialize_app(cred)
result = db.Query.get()
but then I get the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'https://project_name.firebaseio.com/.json'
even though when I enter this url on my browser (with project_name replaced with my real project name) I am getting the json of data from the database.
How can I fix this error?
The Certificate should point to a local file with your credentials/certificate. You are instead pointing it to your database URL, which is not a local file, so the library throws an error.
From the documentation on initializing the Python SDK:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
# Fetch the service account key JSON file contents
cred = credentials.Certificate('path/to/serviceAccountKey.json')
# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://databaseName.firebaseio.com'
})
# As an admin, the app has access to read and write all data, regardless of Security Rules
ref = db.reference('restricted_access/secret_document')
print(ref.get())
Try this ,this works for me
import os
from firebase_admin import credentials, firestore, initialize_app
# Initialize Firestore DB
data = os.path.abspath(os.path.dirname(__file__)) + "/serviceAccountKey.json"
cred = credentials.Certificate(data)
default_app = initialize_app(cred)
db = firestore.client()
I need to update certain node in my Firebase DB, so this is what I'm doing:
from firebase_admin import db
def update_data_in_firebase(gid, account_id, location_id, data_to_update):
firebase_url = 'saved_locations/{}/accounts/{}/locations/{}'.format(gid, account_id, location_id)
ref = db.reference(path=firebase_url)
ref.update(data_to_update)
So, the code above is what I'm trying to do to update the data in the Firebase node, but I'm getting this error:
Invalid databaseURL option: "None". databaseURL must be a non-empty URL string.
Of course, I checked out the firebase URL and it matches, so the problem is not the URL, or, I'm missing something with the path, I mean, should I use absolute insted of relative path.
As mentioned in the comments of the question, the databaseURL was not defined.
Answer:
cred = credentials.Certificate('your_config.json')
firebase_admin = firebase_admin.initialize_app(cred, {'databaseURL': 'https://your-firebase-db'})
In the main docs of Firebase, I couldn't find the error on my app initialization:
Firebase Admin Docs
But in the Realtime Database - Admin (Get Started), there is a snippet where they initialize the Firebase App defining the databaseURL