def upload_data(json_name): cred = credentials.Certificate('./radinmas-info-app-firebase-adminsdk-ntv76-cbef984d38.json') try: firebase_admin.initialize_app(cred, { 'databaseURL': 'https://radinmas-info-app.firebaseio.com/' }) except ValueError as e: firebase_admin.get_app() ref = db.reference('radin_mas/' + str(json_name) + '/') class_file = open(str(json_name) + ".json", "r") for line in class_file.readlines(): data = json.loads(line) ref.set(data)
def firebase_admin_app(service_account): try: return firebase_admin.get_app() except ValueError: pass return firebase_admin.initialize_app( firebase_admin.credentials.Certificate(service_account) )
def __init__(self) -> None: try: self._firebase_app = firebase_admin.get_app(FIREBASE_APP_NAME) except ValueError: firebase_credentials = firebase_admin.credentials.Certificate( api_settings.FIREBASE_SERVICE_ACCOUNT_KEY_FILE_PATH) self._firebase_app = firebase_admin.initialize_app( firebase_credentials, name=FIREBASE_APP_NAME)
def initialize_sdk_with_service_account_id(): # [START initialize_sdk_with_service_account_id] options = { 'serviceAccountId': '*****@*****.**', } firebase_admin.initialize_app(options=options) # [END initialize_sdk_with_service_account_id] firebase_admin.delete_app(firebase_admin.get_app())
def get_firebase_db(): try: firebase_admin.get_app() except ValueError: # If app doesn't exist ValueError is raised. Create app. cred = credentials.ApplicationDefault() try: # Next line throws exception if we don't have default credentials. cred.get_credential() firebase_admin.initialize_app( cred, {'projectId': os.environ.get('GCP_PROJECT')}) except auth_exceptions.DefaultCredentialsError: # Use key file if we don't have default credentials. logger.info('Using key file for credentials') cred = credentials.Certificate('test_serviceAccount.json') firebase_admin.initialize_app(cred) return firestore.client()
def send_order_to_vendor(result, fcm_token): try: app = firebase_admin.get_app() except ValueError as e: cred = credentials.Certificate("serviceAccountKey.json") firebase_admin.initialize_app(cred) msg = messaging.Message(data={'message': 'New Order'}, token=fcm_token) msg_id = messaging.send(msg) return msg_id
def setup(bot: commands.Bot): load_dotenv() try: firebase = firebase_admin.initialize_app() except ValueError: firebase = firebase_admin.get_app() bot.add_cog(Groups(bot, firebase))
def get_db(): try: app = firebase_admin.get_app() except ValueError as e: cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred, { 'projectId': 'lichess-scraping', }) return firestore.client()
def _instrument_iid_service(self, app=None, status=200, payload=_DEFAULT_RESPONSE): if not app: app = firebase_admin.get_app() fcm_service = messaging._get_messaging_service(app) recorder = [] fcm_service._client.session.mount( 'https://iid.googleapis.com', testutils.MockAdapter(payload, status, recorder)) return fcm_service, recorder
def signUp(self): firebase_admin.get_app() user = User(None, None) # print(self.username.get()) # print(self.password.get()) user.uname = self.username.get() user.pswd = self.password.get() # user.showUserDetails() data = user.__dict__ db.collection("User").document().set(data) # print(">> ", user.uname, "Saved in Firebase") self.popUp()
def rtdb_transaction(event, context): """ Attempts a transaction to update the value of the counter, incrementing it by 1. """ # Function's runtime environment service account has the predefined Firebase Admin role cred = credentials.ApplicationDefault() if not firebase_admin._apps: firebase_admin.initialize_app(cred, {'databaseURL': 'MY_FIREBASE_RTDB_URL'}) else: firebase_admin.get_app() # As an admin, the app has access to read and write all data, regardless of Security Rules ref = db.reference('counter') ref.transaction(increment_count) print('Transaction completed') return 'New value: ' + str(ref.get())
def _firebase_app(): from firebase_admin import credentials try: creds = credentials.Certificate('service-account-key.json') except: creds = None try: return firebase_admin.get_app('tbans') except ValueError: return firebase_admin.initialize_app(creds, name='tbans')
def initFirebaseApp(): retval = None try: # just see if the app's already initialised retval = firebase_admin.get_app() except: # nope. Let's initialise it cred = credentials.Certificate('config/firebasekey.json') retval = firebase_admin.initialize_app(cred) return retval
def insert_to_firebase(city, address): try: firebase_admin.get_app() except ValueError: app_id = get_application_id() firebase_admin.initialize_app( options={ 'databaseURL': 'https://{}.firebaseio.com'.format(app_id) }) kv_to_insert = { 'city': city, 'address': address, 'time': { '.sv': 'timestamp' } } ref = db.reference('city-address/latest') ref.update(kv_to_insert)
def initialize(): global app if not app: cred = credentials.Certificate('firebase_adminsdk.json') try: app = firebase_admin.get_app(name="AuthApp") except ValueError: app = firebase_admin.initialize_app(credential=cred, name="AuthApp") return app
def get_bucket(): "Cloud Storage for Firebaseにアクセス" try: app = firebase_admin.get_app() # Appインスタンスを取得 except ValueError as e: # バケットの参照を取得 cred = credentials.Certificate('oral-voice-14555-firebase-adminsdk-9d2a4-895b1df1a3.json') firebase_admin.initialize_app(cred, {'storageBucket': 'oral-voice-14555.appspot.com'}) bucket = storage.bucket() return bucket
def get_firestore(): if "firestore" not in g: if FIREBASE_APP_NAME not in firebase_admin._apps: cred = credentials.Certificate(os.environ["FIREBASE_CREDS"]) firebase_admin.initialize_app(cred, { "projectId": "seahawk-scouter" }, name=FIREBASE_APP_NAME) g.firestore = firestore.client(firebase_admin.get_app(FIREBASE_APP_NAME)) return g.firestore
def __init__(self, key_path, project=None): self.config_path = os.path.join(KEYS_PATH,project + '.json') self.config = json.load(open(self.config_path)) self.project = project if project else self.config['project_id'].split('-')[0] self.credentials = firebase_admin.credentials.Certificate(self.config_path) try: self.app = firebase_admin.initialize_app(self.credentials, { 'databaseURL': 'https://' + self.config['project_id'] + '.firebaseio.com' }, self.project) except: self.app = firebase_admin.get_app(name=project)
def update_recipe(): now = datetime.now(tz=korea_timezone) if not _apps: cred = get_cred() initialize_app(cred) else: get_app() db = firestore.client() # languages = ['ko', 'en', 'zh-CN'] languages = ['ko'] restaurant_list = {"student_seoul_1": "1", "teacher_seoul_1": "2", "sarang_seoul": "3", "teacher_seoul_2": "4", "student_seoul_2": "5", "dorm_seoul_1": "6", "dorm_seoul_2": "7", "hangwon_seoul": "8", "teacher_erica": "11", "student_erica": "12", "dorm_erica": "13", "food_court_erica": "14", "changbo_erica": "15"} for _, (key, value) in enumerate(restaurant_list.items()): restaurant_list = Restaurant(key, value) recipe = get_cafeteria_menu(restaurant=restaurant_list) for language in languages: doc = db.collection(f'cafeteria_{language.split("-")[0]}').document(key) recipe_translated = deepcopy(recipe) if language != 'ko': kinds = [x for x in recipe_translated.keys() if "식" in x] for kind in kinds: for menu in recipe_translated[kind]: menu['menu'] = get_translated_menu(menu['menu'], language) try: snapshot = doc.get() recipe_translated['last_used'] = now menu_keys = ["조식", "중식", "석식"] for key in menu_keys: if key not in recipe_translated.keys(): recipe_translated[key] = [] if not snapshot.to_dict(): doc.set(recipe_translated) else: doc.update(recipe_translated) except NotFound: recipe_translated['last_used'] = now doc.set(recipe_translated)
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_app_identity_stub() self.testbed.init_memcache_stub() self.testbed.setup_env(app_id='your-app-id', overwrite=True) # Stub the FCM admin module try: self._app = firebase_admin.get_app('tbans') except ValueError: self._app = firebase_admin.initialize_app(name='tbans') messaging._get_messaging_service(self._app).send = self._stub_send
def __init__(self, config, log=None): super().__init__(config, log=log) # These queues are meant to ensure the crawl/scrape pumps aren't # requeing articles/feeds that have already been queued to the messge # queue # This values in this dict are not themeselves queues; rather they are # just sets tracking which actions have been sent to the message queue. # These are removed when the action is resolved (e.g. an article that # was queued to be crawled has been crawled). self.queues = defaultdict(set) self.producers = {} # Initialize firebase try: firebase_admin.get_app() except ValueError: # Initialize firebase admin with the credentials from the config file cred = firebase_admin.credentials.Certificate( config.web.firebase.service_account_key_file) firebase_admin.initialize_app(cred, config.web.firebase.app_options)
def init_firebase_app(): cred = credentials.Certificate(FIREBASE_PRIVATE_KEY) try: app = firebase_admin.initialize_app(cred, { 'storageBucket': f'{FIREBASE_APP_NAME}.appspot.com' }) except ValueError: app = firebase_admin.get_app() client = firestore.client() bucket = storage.bucket(app=app) return app, client, bucket
def updateDB(): try: firebase_admin.get_app() except ValueError: DB_URL = '비공개' cred = credentials.Certificate('비공개') firebase_admin.initialize_app(cred, {'databaseURL': DB_URL}) articles_data = scrapy_articles() nike_data = scrapy_shoes('Nike') newbal_data = scrapy_shoes('Newbalance') articles_ref = db.reference('Articles') nike_ref = db.reference('Nike') newbal_ref = db.reference('Newbalance') # Write Articles for i, news in enumerate(articles_data): articles_ref.update({f'Articles{i}': news}) write_data(nike_ref, nike_data) write_data(newbal_ref, newbal_data)
def establish_firebase_connection() -> None: """Establishes the connection to Firebase needed by the rest of the SDK. All Firebase operations require an "app", the abstraction used for a Firebase server connection. The initialize_app() function raises an error when it's called more than once, however, so we make this function idempotent by trying to "get" the app first. Returns: firebase_admin.App. The App being by the Firebase SDK. Raises: Exception. The Firebase app has a genuine problem. """ try: firebase_admin.get_app() except ValueError as error: if 'initialize_app' in python_utils.UNICODE(error): firebase_admin.initialize_app( options={'projectId': feconf.OPPIA_PROJECT_ID}) else: raise
def admin(cls, project_id): admin_app_name = f"{project_id}-admin" try: cred = credentials.ApplicationDefault() return firebase_admin.initialize_app( cred, { "projectId": project_id, }, name=admin_app_name, ) except ValueError: return firebase_admin.get_app(admin_app_name)
def __init__(self, config): self.cred = credentials.Certificate(config) if config.get("project_id") in firebase_admin._apps: self.app = firebase_admin.get_app(config.get("project_id")) else: self.app = firebase_admin.initialize_app( self.cred, name=config.get("project_id")) bucketName = f"{self.cred.project_id}.appspot.com" self.bucket = storage.bucket(bucketName, app=self.app) print(self.bucket)
def init_db(): # Prod env already has access to this, but you'll need to setup the gcloud sdk for local work cred = credentials.ApplicationDefault() # might only apply to dev? - init app if not already in memory if firebase_admin._DEFAULT_APP_NAME not in firebase_admin._apps: app = firebase_admin.initialize_app(cred, { 'projectId': environ['CLOUD_FUNCTION_PROJECT'] }) else: app = firebase_admin.get_app() return firestore.client(app)
def create_custom_token(user_id, role, token_id=None, exp=None, return_payload=False): """ Generate a custom JWT token signed with the Google service account's private key. Before this function can be used, `firebase_admin.initialize_app` must have been called. This implements the process described here: https://firebase.google.com/docs/auth/admin/create-custom-tokens#create_custom_tokens_using_a_third-party_jwt_library We do this manually, because the interface provided by `firebase_admin.auth.create_custom_token` does not allow creating tokens that don't expire. This is because firebase custom tokens are intended for use by apps to authenticate against firebase to retrieve an identity token, and are really not intended to be long-lived. However, we are using the same process to create long-lived tokens for authenticating recsystems. There's no particular harm in doing this since it's just our own JWT for use internally, but signed using our existing private key provided by the Google service account, rather than maintaining a separate key just for signing custom tokens. The other difference is we use the claim ``user_id`` instead of ``uid`` for the user ID, to be consistent with identity tokens generated by firebase. I don't know why the two token formats are inconsistent in this; it seems like a slight oversight on Google's part. """ app = firebase_admin.get_app() payload = { 'iss': app.credential.service_account_email, 'sub': app.credential.service_account_email, 'iat': int(time.time()), # google.auth's token verify requires an expiration time and always # validates it, so we create an exp that effectively never expires # before the heat death of the universe 'exp': exp or 2**64 - 1, 'user_id': user_id, # Prefix our custom claims to avoid potential future clashes 'renewal_role': role, 'renewal_token_id': token_id or secrets.token_hex(20) } token = jwt.encode(app.credential.signer, payload).decode('ascii') if return_payload: return (token, payload) else: return token
def test_custom_token_without_service_account(api_key): google_cred = firebase_admin.get_app().credential.get_credential() cred = CredentialWrapper.from_existing_credential(google_cred) custom_app = firebase_admin.initialize_app( cred, { 'serviceAccountId': google_cred.service_account_email, }, 'temp-app') try: custom_token = auth.create_custom_token('user1', app=custom_app) id_token = _sign_in(custom_token, api_key) claims = auth.verify_id_token(id_token) assert claims['uid'] == 'user1' finally: firebase_admin.delete_app(custom_app)
def book_food(): try: if request.method == "POST": cred = credentials.ApplicationDefault() try: firebase_admin.get_app() print('firebase already intialized.') except ValueError as e: print('firebase not initialized. initialize.') firebase_admin.initialize_app(cred) db = firestore.client() doc_ref = db.collection(request.form["collection_id"]) doc_ref.document(request.form["itemId"]).update({ "available": "False" }) print("sending results") return jsonify({'success': "updated"}) except Exception as e: print(e) return jsonify({'error': "Error while confirming pickup of item"})
def __init__(self): import firebase_admin try: self._firebase_app = firebase_admin.get_app('tbans') except ValueError: self._firebase_app = firebase_admin.initialize_app(name='tbans')
def __init__(self, mapper, creds_path, project_id=None, custom_token=None, api_key=None, validator=None, read_only=False, name=None, namespace=None ): self.mapper = mapper self.validator = validator self.read_only = read_only self.api_key = api_key self.namespace = namespace self.expires = None self.data_adapter = FirestoreDataAdapter() # Use a service account options = {"httpTimeout": 5} app = None if custom_token is not None: # from device client self.user = self.sign_in_with_custom_token(custom_token) self.update_expires() self.creds = CustomToken(self.user["idToken"], project_id) app_name = name if name else firebase_admin._DEFAULT_APP_NAME try: app = firebase_admin.get_app(name=app_name) except ValueError as e: # ugly hack to account for different behaviour of google libs try: app = firebase_admin.initialize_app(self.creds, name=app_name, options=options) except Exception as e: self.creds = self.creds.get_credential() app = firebase_admin.initialize_app(self.creds, name=app_name, options=options) elif creds_path is not None: # in dev with service creds try: self.creds = credentials.Certificate(creds_path) app = firebase_admin.initialize_app(self.creds, options=options) except ValueError as e: print("already initaialised") else: # in app engine environment already_initialised = firebase_admin._DEFAULT_APP_NAME in firebase_admin._apps if not already_initialised: app = firebase_admin.initialize_app(options=options) self.db = firestore.client(app=app) self.app = app