Python firebase_admin.initialize_app() Examples

The following are 30 code examples of firebase_admin.initialize_app(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module firebase_admin , or try the search function .
Example #1
Source File: 51.py    From 57_Challenges with MIT License 22 votes vote down vote up
def main():
    config = configparser.ConfigParser()
    config.read("../private/51.ini")

    key = config["firebase"]["key_path"]
    database_url = config["firebase"]["database_url"]
    cred = credentials.Certificate(key)
    myapp = firebase_admin.initialize_app(cred, {"databaseURL": database_url})

    if len(sys.argv) <= 1:
        sys.argv.append("")

    command = sys.argv[1]
    content_list = sys.argv[2:]
    content = " ".join(content_list)
    check_valid_command(command)
    do_command(command, content) 
Example #2
Source File: test_instance_id.py    From firebase-admin-python with Apache License 2.0 6 votes vote down vote up
def test_delete_instance_id_error(self, status):
        cred = testutils.MockCredential()
        app = firebase_admin.initialize_app(cred, {'projectId': 'explicit-project-id'})
        _, recorder = self._instrument_iid_service(app, status, 'some error')
        msg, exc = http_errors.get(status)
        with pytest.raises(exc) as excinfo:
            instance_id.delete_instance_id('test_iid')
        assert str(excinfo.value) == msg
        assert excinfo.value.cause is not None
        assert excinfo.value.http_response is not None
        if status != 401:
            assert len(recorder) == 1
        else:
            # 401 responses are automatically retried by google-auth
            assert len(recorder) == 3
        assert recorder[0].method == 'DELETE'
        assert recorder[0].url == self._get_url('explicit-project-id', 'test_iid') 
Example #3
Source File: test_db.py    From firebase-admin-python with Apache License 2.0 6 votes vote down vote up
def test_listen_error(self):
        test_url = 'https://test.firebaseio.com'
        firebase_admin.initialize_app(testutils.MockCredential(), {
            'databaseURL' : test_url,
        })
        try:
            ref = db.reference()
            adapter = MockAdapter(json.dumps({'error' : 'json error message'}), 500, [])
            session = ref._client.session
            session.mount(test_url, adapter)
            def callback(_):
                pass
            with pytest.raises(exceptions.InternalError) as excinfo:
                ref._listen_with_session(callback, session)
            assert str(excinfo.value) == 'json error message'
            assert excinfo.value.cause is not None
            assert excinfo.value.http_response is not None
        finally:
            testutils.cleanup_apps() 
Example #4
Source File: index.py    From firebase-admin-python with Apache License 2.0 6 votes vote down vote up
def authenticate_with_guest_privileges():
    # [START authenticate_with_guest_privileges]
    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 None auth variable, limiting the server's access
    firebase_admin.initialize_app(cred, {
        'databaseURL': 'https://databaseName.firebaseio.com',
        'databaseAuthVariableOverride': None
    })

    # The app only has access to public data as defined in the Security Rules
    ref = db.reference('/public_resource')
    print(ref.get())
    # [END authenticate_with_guest_privileges]
    firebase_admin.delete_app(firebase_admin.get_app()) 
Example #5
Source File: index.py    From firebase-admin-python with Apache License 2.0 6 votes vote down vote up
def authenticate_with_limited_privileges():
    # [START authenticate_with_limited_privileges]
    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 custom auth variable, limiting the server's access
    firebase_admin.initialize_app(cred, {
        'databaseURL': 'https://databaseName.firebaseio.com',
        'databaseAuthVariableOverride': {
            'uid': 'my-service-worker'
        }
    })

    # The app only has access as defined in the Security Rules
    ref = db.reference('/some_resource')
    print(ref.get())
    # [END authenticate_with_limited_privileges]
    firebase_admin.delete_app(firebase_admin.get_app()) 
Example #6
Source File: index.py    From firebase-admin-python with Apache License 2.0 6 votes vote down vote up
def authenticate_with_admin_privileges():
    # [START authenticate_with_admin_privileges]
    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, regradless of Security Rules
    ref = db.reference('restricted_access/secret_document')
    print(ref.get())
    # [END authenticate_with_admin_privileges]
    firebase_admin.delete_app(firebase_admin.get_app()) 
Example #7
Source File: test_token_gen.py    From firebase-admin-python with Apache License 2.0 6 votes vote down vote up
def test_sign_with_discovered_service_account(self):
        request = testutils.MockRequest(200, 'discovered-service-account')
        options = {'projectId': 'mock-project-id'}
        app = firebase_admin.initialize_app(testutils.MockCredential(), name='iam-signer-app',
                                            options=options)
        try:
            _overwrite_iam_request(app, request)
            # Force initialization of the signing provider. This will invoke the Metadata service.
            client = auth._get_client(app)
            assert client._token_generator.signing_provider is not None

            # Now invoke the IAM signer.
            signature = base64.b64encode(b'test').decode()
            request.response = testutils.MockResponse(
                200, '{{"signature": "{0}"}}'.format(signature))
            custom_token = auth.create_custom_token(MOCK_UID, app=app).decode()
            assert custom_token.endswith('.' + signature.rstrip('='))
            self._verify_signer(custom_token, 'discovered-service-account')
            assert len(request.log) == 2
            assert request.log[0][1]['headers'] == {'Metadata-Flavor': 'Google'}
        finally:
            firebase_admin.delete_app(app) 
Example #8
Source File: test_db.py    From firebase-admin-python with Apache License 2.0 6 votes vote down vote up
def test_multi_db_support(self):
        default_url = 'https://test.firebaseio.com'
        firebase_admin.initialize_app(testutils.MockCredential(), {
            'databaseURL' : default_url,
        })
        ref = db.reference()
        assert ref._client.base_url == default_url
        assert 'auth_variable_override' not in ref._client.params
        assert ref._client is db.reference()._client
        assert ref._client is db.reference(url=default_url)._client

        other_url = 'https://other.firebaseio.com'
        other_ref = db.reference(url=other_url)
        assert other_ref._client.base_url == other_url
        assert 'auth_variable_override' not in ref._client.params
        assert other_ref._client is db.reference(url=other_url)._client
        assert other_ref._client is db.reference(url=other_url + '/')._client 
Example #9
Source File: test_app.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_app_init_with_invalid_name(self, name):
        with pytest.raises(ValueError):
            firebase_admin.initialize_app(CREDENTIAL, name=name) 
Example #10
Source File: test_app.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_app_init_with_invalid_credential(self, cred):
        with pytest.raises(ValueError):
            firebase_admin.initialize_app(cred) 
Example #11
Source File: test_app.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_app_init_with_invalid_config_string(self):
        config_old = set_config_env('{,,')
        with pytest.raises(ValueError):
            firebase_admin.initialize_app(CREDENTIAL)
        revert_config_env(config_old) 
Example #12
Source File: test_app.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_app_init_with_default_config(self, env_test_case):
        app = firebase_admin.initialize_app(CREDENTIAL, options=env_test_case.init_options)
        assert app.options._options == env_test_case.want_options 
Example #13
Source File: test_app.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_project_id_from_options(self, app_credential):
        app = firebase_admin.initialize_app(
            app_credential, options={'projectId': 'test-project'}, name='myApp')
        assert app.project_id == 'test-project' 
Example #14
Source File: index.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def initialize_sdk_with_application_default():
    # [START initialize_sdk_with_application_default]
    default_app = firebase_admin.initialize_app()
    # [END initialize_sdk_with_application_default]
    firebase_admin.delete_app(default_app) 
Example #15
Source File: test_messaging.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_no_project_id(self):
        def evaluate():
            app = firebase_admin.initialize_app(testutils.MockCredential(), name='no_project_id')
            with pytest.raises(ValueError):
                messaging.send(messaging.Message(topic='foo'), app=app)
        testutils.run_without_project_id(evaluate) 
Example #16
Source File: test_messaging.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def setup_class(cls):
        cred = testutils.MockCredential()
        firebase_admin.initialize_app(cred, {'projectId': 'explicit-project-id'}) 
Example #17
Source File: test_messaging.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_no_project_id(self):
        def evaluate():
            app = firebase_admin.initialize_app(testutils.MockCredential(), name='no_project_id')
            with pytest.raises(ValueError):
                messaging.send_all([messaging.Message(topic='foo')], app=app)
        testutils.run_without_project_id(evaluate) 
Example #18
Source File: test_messaging.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def setup_class(cls):
        cred = testutils.MockCredential()
        firebase_admin.initialize_app(cred, {'projectId': 'explicit-project-id'}) 
Example #19
Source File: index.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def initialize_sdk_with_service_account_id():
    # [START initialize_sdk_with_service_account_id]
    options = {
        'serviceAccountId': 'my-client-id@my-project-id.iam.gserviceaccount.com',
    }
    firebase_admin.initialize_app(options=options)
    # [END initialize_sdk_with_service_account_id]
    firebase_admin.delete_app(firebase_admin.get_app()) 
Example #20
Source File: test_app.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_app_init_with_invalid_options(self, options):
        with pytest.raises(ValueError):
            firebase_admin.initialize_app(CREDENTIAL, options=options) 
Example #21
Source File: test_token_gen.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def auth_app():
    """Returns an App initialized with a mock service account credential.

    This can be used in any scenario where the private key is required. Use user_mgt_app
    for everything else.
    """
    app = firebase_admin.initialize_app(MOCK_CREDENTIAL, name='tokenGen')
    yield app
    firebase_admin.delete_app(app) 
Example #22
Source File: test_app.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_non_default_app_init(self, app_credential):
        app = firebase_admin.initialize_app(app_credential, name='myApp')
        assert app.name == 'myApp'
        if app_credential:
            assert app_credential is app.credential
        else:
            assert isinstance(app.credential, credentials.ApplicationDefault)
        with pytest.raises(ValueError):
            firebase_admin.initialize_app(app_credential, name='myApp') 
Example #23
Source File: test_app.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_default_app_init(self, app_credential):
        app = firebase_admin.initialize_app(app_credential)
        assert firebase_admin._DEFAULT_APP_NAME == app.name
        if app_credential:
            assert app_credential is app.credential
        else:
            assert isinstance(app.credential, credentials.ApplicationDefault)
        with pytest.raises(ValueError):
            firebase_admin.initialize_app(app_credential) 
Example #24
Source File: test_token_gen.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_project_id_option(self):
        app = firebase_admin.initialize_app(
            testutils.MockCredential(), options={'projectId': 'mock-project-id'}, name='myApp')
        _overwrite_cert_request(app, MOCK_REQUEST)
        try:
            claims = auth.verify_session_cookie(TEST_SESSION_COOKIE, app=app)
            assert claims['admin'] is True
            assert claims['uid'] == claims['sub']
        finally:
            firebase_admin.delete_app(app) 
Example #25
Source File: test_token_gen.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_project_id_option(self):
        app = firebase_admin.initialize_app(
            testutils.MockCredential(), options={'projectId': 'mock-project-id'}, name='myApp')
        _overwrite_cert_request(app, MOCK_REQUEST)
        try:
            claims = auth.verify_id_token(TEST_ID_TOKEN, app)
            assert claims['admin'] is True
            assert claims['uid'] == claims['sub']
        finally:
            firebase_admin.delete_app(app) 
Example #26
Source File: test_token_gen.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_sign_with_discovery_failure(self):
        request = testutils.MockFailedRequest(Exception('test error'))
        options = {'projectId': 'mock-project-id'}
        app = firebase_admin.initialize_app(testutils.MockCredential(), name='iam-signer-app',
                                            options=options)
        try:
            _overwrite_iam_request(app, request)
            with pytest.raises(ValueError) as excinfo:
                auth.create_custom_token(MOCK_UID, app=app)
            assert str(excinfo.value).startswith('Failed to determine service account: test error')
            assert len(request.log) == 1
            assert request.log[0][1]['headers'] == {'Metadata-Flavor': 'Google'}
        finally:
            firebase_admin.delete_app(app) 
Example #27
Source File: test_token_gen.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def test_sign_with_iam_error(self):
        options = {'serviceAccountId': 'test-service-account', 'projectId': 'mock-project-id'}
        app = firebase_admin.initialize_app(
            testutils.MockCredential(), name='iam-signer-app', options=options)
        try:
            iam_resp = '{"error": {"code": 403, "message": "test error"}}'
            _overwrite_iam_request(app, testutils.MockRequest(403, iam_resp))
            with pytest.raises(auth.TokenSignError) as excinfo:
                auth.create_custom_token(MOCK_UID, app=app)
            error = excinfo.value
            assert error.code == exceptions.UNKNOWN
            assert iam_resp in str(error)
            assert isinstance(error.cause, google.auth.exceptions.TransportError)
        finally:
            firebase_admin.delete_app(app) 
Example #28
Source File: test_token_gen.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def env_var_app(request):
    """Returns an App instance initialized with the given set of environment variables.

    The lines of code following the yield statement are guaranteed to run after each test case
    that depends on this fixture. This ensures that the environment is left intact after the
    tests.
    """
    environ = os.environ
    os.environ = request.param
    app = firebase_admin.initialize_app(testutils.MockCredential(), name='env-var-app')
    yield app
    os.environ = environ
    firebase_admin.delete_app(app) 
Example #29
Source File: test_token_gen.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def user_mgt_app():
    app = firebase_admin.initialize_app(testutils.MockCredential(), name='userMgt',
                                        options={'projectId': 'mock-project-id'})
    yield app
    firebase_admin.delete_app(app) 
Example #30
Source File: test_ml.py    From firebase-admin-python with Apache License 2.0 5 votes vote down vote up
def setup_class(cls):
        cred = testutils.MockCredential()
        firebase_admin.initialize_app(cred, {'projectId': PROJECT_ID})