Giter VIP home page Giter VIP logo

firebase / firebase-js-sdk Goto Github PK

View Code? Open in Web Editor NEW
4.7K 195.0 864.0 130.89 MB

Firebase Javascript SDK

Home Page: https://firebase.google.com/docs/web/setup

License: Other

JavaScript 5.54% HTML 1.32% TypeScript 92.41% Shell 0.05% CSS 0.49% Handlebars 0.07% HCL 0.12%
firebase firebase-database firebase-auth firebase-authentication firebase-storage firebase-messaging firebase-cloud-messaging firebase-db firebase-realtime-database javascript typescript real-time

firebase-js-sdk's Introduction

Firebase Javascript SDK

Build Status Version Coverage Status

The Firebase JavaScript SDK implements the client-side libraries used by applications using Firebase services. This SDK is distributed via:

To get started using Firebase, see Add Firebase to your JavaScript Project.

Release Notes

Upgrade to Version 9

Version 9 has a redesigned API that supports tree-shaking. Read the Upgrade Guide to learn more.

Supported Environments

Please see Environment Support.

SDK Dev Workflow

Prerequisites

Node.js

Before you can start working on the Firebase JS SDK, you need to have Node.js installed on your machine. As of April 19th, 2024 the team has been testing with Node.js version 20.12.2, but the required verison of Node.js may change as we update our dependencies.

To download Node.js visit https://nodejs.org/en/download/.

NOTE: You can use a tool like NVM or N to install and manage multiple node versions

Yarn

In addition to Node.js we use yarn to facilitate multi package development.

To install yarn follow the instructions listed on their website: https://yarnpkg.com/en/docs/install

This repo currently supports building with yarn 1.x. For instance, after installating yarn, run

$ yarn set version 1.22.11

Java

The closure compiler requires a modern Java installation. Java 11+ should be installed: https://www.oracle.com/java/technologies/downloads/#java11

Verify Prerequisites

You can verify your setup by running the following commands in your terminal:

$ node -v
$ yarn -v
$ java -version

Your node version should be 20.12.2, your yarn version should be between 1.0.0 and 1.22.11, and your java version should be 11.0 or greater.

NOTE: We will update the documentation as new versions are required, however for continuing development on the SDK, staying up to date on the stable versions of these packages is advised

Install Dependencies

Once you have Node.js and yarn installed on your machine and have validated that you are running the proper version, you can set up the development environment by running the following at the root of the SDK:

$ yarn

Once you have installed all the dependencies, you can build the entire SDK by running the following command the root of the SDK:

$ yarn build

Testing the SDK

Test Setup

A production project is required to test the Firebase JS SDK. You can create a new project by visiting the Firebase Console.

Web App Setup

Visit the "Project Overview" and select "Add app" under your project name. Register the app with a nickname and click through the remaining steps. Without performing this step, you will encounter the error in the test setup:

FirebaseError: There are no WEB apps associated with this Firebase project

Firestore Database Setup

Visit the "Firestore Database" section of the console and create a Cloud Firestore database. When prompted to select the set of initial security rules, select any option (e.g. "Start in Production Mode") since these permission settings will be overwritten below.

Realtime Database Setup

Visit the "Realtime Database" section of the console and create a realtime database. When prompted to select the set of initial security rules, select any option (e.g. "Start in Locked Mode") since these permission settings will be overwritten below.

Storage Setup

Visit the "Storage" section of the console and create a storage bucket. In order to run the tests, you will need to update your bucket's CORS rules.

  1. Create a new file called cors.json with the contents:
[
    {
        "origin": ["http://localhost:8089"],
        "method": ["GET"],
        "maxAgeSeconds": 3600
    }
]
  1. Install gsutil from https://cloud.google.com/storage/docs/gsutil_install
  2. You will need to login if this is your first time using gsutil. Run gcloud auth login and follow the instructions to login.
  3. Run gsutil cors set cors.json gs://<your-cloud-storage-bucket>

For more information, visit https://firebase.google.com/docs/storage/web/download-files#cors_configuration

Authentication Support

Visit the authentication config in your project and enable the Anonymous sign-in provider to complete your project config.

Automated Setup

The tests need to be configured to use the Firebase production project that you created in the "Test Setup" section above. To do this, run the yarn test:setup command, as follows:

# Select the Firebase project via the text-based UI. This will run tools/config.js
# and deploy from config/ to your Firebase project.
$ yarn test:setup

# Specify the Firebase project via the command-line arguments.
$ yarn test:setup --projectId=<test_firebase_project_id>

If you see an error like

HTTP Error: 404, Project '<test_firebase_project_id>' does not exist.

then make sure that you have created the database as specified in the "Firestore Database Setup" section above.

Running the tests

Each of the directories in the integration directory as well as the packages directory have their own test suites. You will need to build the SDK before running tests. Test suites can be run all together by running the following command at the root of the package:

$ yarn test

In addition, you can run any of the tests individually by running yarn test in an individual package directory.

Building the SDK

Introduction

The Firebase JS SDK is built with a series of individual packages that are all contained in this repository. Development is coordinated via yarn workspaces and Lerna (a monorepo management tool).

Each package in the packages directory, constitute a piece of our implementation. The SDK is built via a combination of all of these packages which are published under the firebase scope on NPM.

Testing the SDK Locally

Please be sure your product's package has been built before proceeding any further. (If you haven't built this repo before, make sure to run yarn build at the root) In order to manually test your SDK changes locally, you must use yarn link:

$ cd packages/firebase
$ yarn link # initialize the linking to the other folder
$ cd ../packages/<my-product> # Example: $ cd packages/database
$ yarn link # link your product to make it available elsewhere
$ cd <my-test-app-dir> # cd into your personal project directory
$ yarn link firebase @firebase/<my-product> # tell yarn to use the locally built firebase SDK instead

This will create a symlink and point your <my-test-app-dir> to the locally built version of the firebase SDK.

Helper Scripts

Each package in the packages directory exposes a dev script. This script will set up a watcher for development on the individual piece of the SDK. In addition, there is a top level dev script that can be run to start all of the watch tasks as well as a sandbox server.

You can run the dev script by running the following at the root of the package:

$ yarn dev

Prepush Hooks

As part of this repo, we use the NPM package husky to implement git hooks. We leverage the prepush hook to do two things:

  • Automated code styling (using prettier)
  • Automated LICENSE header insertion

Contributing

See Contributing for more information on contributing to the Firebase JavaScript SDK.

Big Thanks

Cross-browser Testing Platform and Open Source <3 Provided by Sauce Labs

firebase-js-sdk's People

Contributors

avolkovi avatar bojeil-google avatar davideast avatar dconeybe avatar dellabitta avatar dependabot[bot] avatar dwyfrequency avatar ehsannas avatar feiyang1 avatar google-oss-bot avatar hsubox76 avatar jshcrowthe avatar maneesht avatar markduckworth avatar mikelehen avatar milaggl avatar mmermerkaya avatar prameshj avatar renovate-bot avatar renovate[bot] avatar ryanpbrewster avatar sam-gc avatar samtstern avatar schmidt-sebastian avatar wilhuff avatar wti806 avatar wu-hui avatar yifanyang avatar yuchenshi avatar zwu52 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-js-sdk's Issues

nextOrObserver:Object type definition in typescript doesn't allow type inference

[REQUIRED] Describe your environment

  • Operating System version: OS X
  • Firebase SDK version: 3.6.8
  • Firebase Product: all (noticeable in auth)

[REQUIRED] Describe the problem

The firebase.d.ts file contains the following type definitions:

onAuthStateChanged (nextOrObserver : Object , error ? : (a : firebase.auth.Error ) => any , completed ? : ( ) => any ) : ( ) => any ;

but this means you can't just pass a function like

.onAuthStateChanged((user) => {
 ...
});

and let |user| by in inferred type, because typescript thinks this method takes an Object. If we look at closure externs they're more specific:

* @param {!Object|function(?firebase.User)}

@param {!Object|function(?firebase.User)}

which would let you pass a callback without explicitly naming the type.

Steps to reproduce:

in typescript write:

firebase.auth().onAuthStateChanged((user) => {
  console.log(user);
});

In general the "Observer" concept is mentioned in the API type definitions and docs, but I don't see anything documented about what an Observer object would be. Everything just passes a function here, is that some Firebase internal type?

Ideally the type definitions here would be specific enough that typescript could infer the argument types of all of the callbacks used in all the various firebase apis. :)

Dummy

[REQUIRED] Describe your environment

  • Operating System version: macOS 12.1.1
  • Firebase SDK version: 4.1.2
  • Firebase Product: messaging (auth, database, storage, etc)

[REQUIRED] Describe the problem

Steps to reproduce:

Relevant Code:

http://jsbin.com/rinilu/edit?js,console

// TODO(you): code here to reproduce the problem

Google Sign In redirects to __auth/handler

Environment

  • Operating System version: Windows
  • Firebase SDK version: 4.1.3
  • Firebase Product: auth

Problem

I implemented Google Sign-In using Firebase Auth by following the instructions here. https://firebase.google.com/docs/auth/web/google-signin. I used .signInWithPopup(provider). Everything seems to work, except after entering my gmail and password, I am redirected to https://mysite.com/__auth/handler, rather than back to the page I was on on my site. Is this the expected behavior?

Reproduction Steps:

Follow the implementation described at https://firebase.google.com/docs/auth/web/google-signin under To sign in by redirecting to the sign-in page, call signInWithRedirect

Relevant Code:

      _googleSignIn() {
        var provider = new firebase.auth.GoogleAuthProvider();
        firebase.auth().signInWithRedirect(provider).then(function(result) {
          console.log('Sign in finished');
          console.log(result);
          // This gives you a Google Access Token. You can use it to access the Google API.
          var token = result.credential.accessToken;
          // The signed-in user info.
          var user = result.user;
          // ...
        }).catch(function(error) {
          console.log(error);
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;
          // ...
        });
      }

chrome apps and database csp

  • Platform: Chrome App
  • Operating System: Ubuntu and Chrome OS
  • Firebase SDK version: 4.1.3
  • Firebase Product: database

When I run the sdk in a chrome app, I get csp errors when using the database. I see you have an example for chrome extensions (https://github.com/firebase/quickstart-js/tree/master/auth/chromextension), but since you can't set the content_security_policy in an chrome app's manifest.json, that example won't work for apps.

Here's an example of the error on stackoverflow: https://stackoverflow.com/questions/29399594/error-using-firebase-from-chrome-app

Refused to load the script 'https://{my firebase id}.firebaseio.com/.lp?start=t&ser=81980096&cb=15&v=5' because it violates the following Content Security Policy directive: "default-src 'self' chrome-extension-resource:". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

I want to solve the above issue but I also want to know why it's only using the https long_polling method for the database and not the websockets wss, which I normally see in my traditional web app. I don't see any reason you can't use wss in a chrome app and it might solve the above issue. It appears the sdk is not even trying to use websockets and just defaults to long polling.

It also seem you're using window.open somewhere which is also causing issues since it's not available in chrome apps.

In short, how can I use the sdk in a chrome app?

//  using custom token
firebase.initializeApp(config);
firebase.auth().signInWithCustomToken(token);

// later on
firebase.database()
        .ref(databaseRefPath())
        .set(getRepresentation())
        .catch(e=>this.log.w(`persist error: ${e}`));

Cannot lazily load firebase components

Describe your environment

  • Operating System version: macOS Sierra
  • Firebase SDK version: 4.0.0
  • Firebase Product: app

Describe the problem

firebase.js is a really large file and while you can load the individual pieces of the SDK (firebase-app, firebase-database, firebase-auth, etc) you have to do so before calling firebase.initializeApp(). This, for most use cases, means that developers load the entire firebase SDK before their app code which results in a lot of time blocking the main thread.

Steps to reproduce:

  1. Load firebase-app.js
  2. Initialize an app with firebase.initializeApp()
  3. Load firebase-database.js
  4. Try and call firebase.database()
  5. Observe error

Relevant Code:

http://jsbin.com/tovayaz/2/edit?js,console

Safari bug causing Firebase write to fail

Hello,

I'm attempting to write a large amount of data to Firebase in a single write (I inspected the WS messages through Charles to make sure, meaning it is being sent in big chunks). There are some WebSocket errors in the console, data isn't written, and the error callback is not called.

I believe it is related to this bug: https://bugs.webkit.org/show_bug.cgi?id=170463

Errors:
Failed to send WebSocket frame.
Failed to send WebSocket frame.
INTERNAL ASSERT FAILED: sendRequest call when we're not connected not allowed.

Allow SDK to auto initializeApp when hosted on Firebase

[REQUIRED] Step 2: Describe your environment

  • Operating System version: Firebase Hosting
  • Firebase SDK version: Future with lazy loading - see #15
  • Library version:
  • Firebase Product: All

[REQUIRED] Step 3: Describe the problem

Issue:

  1. Currently when hosted on Firebase a user has to load component scripts in the correct order (auth, database, app)
  2. Then they need to call '/__/firebase/init.js'

These steps do not play well with polymerfire or angularfire. The user still needs to declare the config properties either directly or by setting up their own secrets.

Request:

  1. Add a test to check if app is hosted on Firebase.
var _isFirebaseHosted = fetch('/__/firebase/init.js').then(response => {
  if (response.status == 200) {
    return true;
  }
  return false;
});
  1. Auto initializeApp
if (_isFirebaseHosted) {
 firebase.initializeApp('/__/firebase/init.js');
}

@mbleigh @jshcrowthe

[App] Certain app names cause issues

[REQUIRED] Describe your environment

  • Operating System version: Linux
  • Firebase SDK version: 4.1.2
  • Firebase Product: app

[REQUIRED] Describe the problem

Using the name of any Object.prototype member as an app name causes issues when trying to initialize or retrieve an app.

Steps to reproduce:

// Here we get an error saying there already is a "valueOf" app
try {
  firebase.initializeApp(options, 'valueOf');
} catch (err) {
  console.error(err.code + ' - ' + err.message);
}

// This simply returns the Object.prototype.toString method
const app = firebase.app('toString');
console.log(app);

Relevant Code:

JSBin reproducing these issues: http://jsbin.com/cohijesema/edit?js,console

Q: How to reverse DataSnapshot?

[REQUIRED] Describe your environment

  • Operating System version: Windows 10
  • Firebase SDK version: 3.6.3
  • Firebase Product: Database

[REQUIRED] Describe the problem

Steps to reproduce:

I need to display information to the contrary.

Relevant Code:

firebase.database()
  .ref('users')
  .on('value')
  .then(snapshot => {
    // Object.keys(snapshot).reverse().forEach( ... )
    // snapshot.reverse().forEach( ... )
    snapshot.forEach(childSnapshot => {
      const key = childSnapshot.key;
      const childData = childSnapshot.val();

      console.log(key, childData.name);
      // xxx, a1
      // xxx, a2
      // xxx, a3

      // Expectation:
      // xxx, a3
      // xxx, a2
      // xxx, a1
  });
});

signInWithCustomToken - auth/invalid-api-key

[REQUIRED] Describe your environment

  • Operating System version: OSX - 10.12.6
  • Firebase SDK version: 3.4.1
  • Firebase Product: auth

[REQUIRED] Describe the problem

Steps to reproduce:

  1. Create a service account via the firebase console. Follow the instructions to generate a custom token on the server.
  2. Attempt to sign in with the token on the client: signInWithCustomToken
  3. This calls the endpoint https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=MYAPIKEY

With the following payload:

{
  "token" : "my_custom_jwt_returned_from_server",
  "returnSecureToken" : true
}
  1. Returns a 400:
"error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "keyInvalid",
    "message": "Bad Request"
   }
  ],
  "code": 400,
  "message": "Bad Request"
 }

Relevant Code:

function (user, context, callback) {
    var admin = require("firebase-admin");

    var serviceAccount = {
      projectId: "my-fb-project",
      privateKey: "-----BEGIN PRIVATE KEY-----\nMYKEY\n-----END PRIVATE KEY-----\n",
      clientEmail: "[email protected]"
    };

    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "https://my-fb-account.firebaseio.com"
    });

    var uid = "some-uid";

    admin.auth().createCustomToken(uid)
      .then(function(customToken) {
        user.user_metadata = user.user_metadata || {};
        user.user_metadata.fbtoken = customToken;

        return callback(null, user, context);
      })
      .catch(function(error) {
        console.log("Error creating custom token:", error);

        return callback(error, user, context);
      });
}

Is there a way to verify the token manually to see if it is indeed correct? When I put the token this function returns into jwt.io everything looks fine, but obviously something is failing. How can I attempt to validate it the same way the service: https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key=MYAPIKEY

[Messaging] onTokenRefresh never triggers

[REQUIRED] Describe your environment

  • Operating System version: Linux
  • Firebase SDK version: 4.1.2
  • Firebase Product: messaging

[REQUIRED] Describe the problem

I've noticed that nothing ever gets next'ed into tokenRefreshObserver_, meaning that the function or observer passed to firebase.messaging.Messaging#onTokenRefresh() never gets triggered.

See: src/messaging/controllers/window-controller.ts#L72-L75

Is there some process missing that would receive token updates and trigger onTokenRefresh()?

Steps to reproduce:

n/a

Relevant Code:

See linked file.

Firebase same origin policy issue with Chrome 58+ in iOS 10.3.x+

[REQUIRED] Describe your environment

  • Operating System version: iOS 10.3.x +
  • Firebase SDK version: 4.1.2
  • Firebase Product: auth or database (not sure which one is triggering the error)

[REQUIRED] Describe the problem

The problem can be observed by using a Chrome broswer version 58+ in any iOS 10.3.+, the first time the issue was observed were in April 10. Basically i'm getting a console.error that is hapenning only in this specific environment. The error message is as follows:

Blocked a frame with origin "https://superpouco.com.br" from accessing a frame with origin "https://superpouco.firebaseapp.com". Protocols, domains, and ports must match.

Where "superpouco" is the domain i'm currently using, the issue also appears in another app under another domain that is using the same app with firebase.

I couldn't find anything related to this issue online so I wonder if it might be how I set the application or if it is due to the fact that it's hapenning in a very very specific scenario.

Steps to reproduce:

Basically accessing the app using Chrome version in the iOS described version.

auth/network-request-failed with Google signInWithPopup

[READ] Step 1: Are you in the right place?

  • For issues or feature requests related to the code in this repository
    file a Github issue.
    • If this is a feature request make sure the issue title starts with "FR:".
  • For general technical questions, post a question on StackOverflow
    with the firebase tag.
  • For general Firebase discussion, use the firebase-talk
    google group.
  • For help troubleshooting your application that does not fall under one
    of the above categories, reach out to the personalized
    Firebase support channel.

[REQUIRED] Step 2: Describe your environment

  • Operating System version: OSX 10.12.4
  • Firebase SDK version: 4.0.0
  • Library version: _____
  • Firebase Product: auth (auth, database, storage, etc)

[REQUIRED] Step 3: Describe the problem

Steps to reproduce:

What happened? How can we make the problem occur?
This could be a description, log/console output, etc.

On signInWithPopup via Google provider in Chrome 58.0.3029.110 (64-bit), signin popup displays no content (white page at about:blank) and then closes with a message in the console.

Sigin error N {code: "auth/network-request-failed", message: "A network error (such as timeout, interrupted connection or unreachable host) has occurred."}
__stack_frame_overlay_proxy_console__ @ proxyConsole.js:43
(anonymous) @ App.js:96
e.lb @ auth.js:49
Ad @ auth.js:52 
wd @ auth.js:52 
A.Re @ auth.js:51
Xc @ auth.js:43
auth.js:157 Uncaught Error: Network Error
    at auth.js:157

This persists for my Chrome profile both with locally hosted instance and deployed copy of the app. It works normally in Safari and Firefox, so far. It also works (at least initially) in incognito mode for fresh launches, but it has occurred in incognito mode.

I have tried removing local storage, clearing cache, disabling cache via devtools, all with no luck. Something appears to be stored somewhere and is preventing google auth from loading correctly, or even launching the URL for auth.

Relevant Code:

ReactJS (15.5.4) application, with firebase initialized in componentDidMount(). Signin button onClick:

signIn() {
    const provider = new firebase.auth.GoogleAuthProvider();
    this.firebase.auth().signInWithPopup(provider)
        .then((result) => console.log('Signin result', result))
        .catch((error) => console.error('Sigin error', error));
  }

The catch triggers providing the error seen above.

I've verified that the initialization params are same as provided in the firebase console (though I felt they were ok due to it working in other browsers etc).

Google as an Auth provider doesn't work on iOS saved to homescreen

[REQUIRED] Describe your environment

  • Operating System version: iOS 10
  • Firebase SDK version: 4.1.3
  • Firebase Product: auth

[REQUIRED] Describe the problem

Steps to reproduce:

  1. Save the app on the homescreen on iOS
  2. make a redirect or popup login with google Auth provider
  3. if redirect:
    • webview is not a "valid user agent"
  4. if popup:
    • gets stuck in Safari about:blank, doesn't open the app again to pass on the token

Relevant Code:

import firebase from "firebase";

const config = {
//...
};

firebase.initializeApp(config);

const googleAuthProvider = new firebaseAuth.GoogleAuthProvider();

firebase.auth().signInWithRedirect(googleAuthProvider);
// or
firebase.auth().signInWithRedirect(googleAuthProvider);

`startAt()` does not respect 2nd parameter when ordering by child

Describe your environment

  • Operating System version: macOS 10.12.4
  • Firebase SDK version: 4.1.1
  • Firebase Product: database

Describe the problem

Using a query with orderByChild() and startAt(null, 'some-key'), I expect the results to be returned starting with the record with key 'some-key', however returned results start at the very first item to match any given filter.

Steps to reproduce:

Start with this data:

{
  "products" : {
    "-KlsqFgVWwUrA-j0VsZS" : {
      "name" : "Product 4",
      "price" : 666
    },
    "-Klst-cLSckuwAuNAJF8" : {
      "name" : "Product 1",
      "price" : 100
    },
    "-Klst7IINdt8YeMmauRz" : {
      "name" : "Product 2",
      "price" : 50
    },
    "-Klst9KfM2QWp8kXrOlR" : {
      "name" : "Product 6",
      "price" : 30
    },
    "-KlstB51ap1L2tcK8cL6" : {
      "name" : "Product 5",
      "price" : 99
    },
    "-KlstDR5cCayGH0XKtZ0" : {
      "name" : "Product 3",
      "price" : 500
    }
  }
}

I retrieve the first three matching records from this list using this code:

firebase.database().ref('products')
.orderByChild('price')
.limitToFirst(3)
.on('child_added', function (snapshot) {
    var key = snapshot.key;
    var data = snapshot.val();
    console.log(key + ': ' + JSON.stringify(data))
})

Using the key of the 3rd record, I try to retrieve records number 3-5:

firebase.database().ref('products')
.orderByChild('price')
.startAt(null, '-KlstB51ap1L2tcK8cL6')   // this is the key of the 3rd matching record.
.limitToFirst(3)
.on('child_added', function (snapshot) {
    var key = snapshot.key;
    var data = snapshot.val();
    console.log(key + ': ' + JSON.stringify(data))
})

Unfortunately this returns the first 3 items again.

However, if I remove the line .orderByChild('price'), then I am able to use .startAt() to retrieve items starting at the given record, which is very weird, because the default ordering is .orderByKey(), which is not supposed to support startAt's 2nd parameter according to the documentation, and also according to the source code

interface DataSnapshot should have a type param

  • Operating System version: n/a
  • Firebase SDK version: latest
  • Firebase Product: database

Describe the problem

I'd like to define types of things in my firebase repo. DataSnapshot.val() returns any.

Steps to reproduce:

call .val on a DataSnapshot

Potential Fix

  interface DataSnapshot<S> {
    child(path: string): firebase.database.DataSnapshot<any>;
    exists(): boolean;
    exportVal(): S;
    forEach(action: (a: firebase.database.DataSnapshot<S>) => boolean): boolean;
    getPriority(): string | number | null;
    hasChild(path: string): boolean;
    hasChildren(): boolean;
    key: string | null;
    numChildren(): number;
    ref: firebase.database.Reference;
    toJSON(): Object | null;
    val(): S;
  }

Compatibility issues with create-react-app

[REQUIRED] Describe your environment

  • Operating System version: macOS Sierra
  • Firebase SDK version: 4.1.2
  • Firebase Product: core (auth, database, storage, etc)

[REQUIRED] Describe the problem

Cross Posting from #26

I writing some unit for React with the Jest unit test framework but I got the following error while
TypeError: _firebase2.default.storage is not a function

Here the stacktrace :

` FAIL src/components/organisms/PriceSettingsBlock/PriceSettingsBlock.test.js
โ— Test suite failed to run

TypeError: _firebase2.default.storage is not a function

at Object. (src/core/firebase/firebase.js:8:120)
at Object. (src/core/firebase/firebase-list.js:1:815)
at Object. (src/core/chat/eventList.js:30:77)
at Object. (src/core/chat/sagas.js:4:44)
at Object. (src/core/chat/index.js:2:62)
at Object. (src/core/init/sagas.js:3:39)
at Object. (src/core/init/index.js:1:387)
at Object. (src/components/organisms/PriceSettingsBlock/PriceSettingsBlock.js:6:39)
at Object. (src/components/organisms/PriceSettingsBlock/PriceSettingsBlock.test.js:4:53)
at handle (node_modules/worker-farm/lib/child/index.js:41:8)
at process. (node_modules/worker-farm/lib/child/index.js:47:3)
at emitTwo (events.js:106:13)
at process.emit (events.js:194:7)
at process.nextTick (internal/child_process.js:766:12)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)`
Test file is here :
PriceSettingsBlock.js.txt
PriceSettingsBlock.test.js.txt

My configuration is here:
`import firebase from 'firebase';
import { firebaseConfig } from './config';

export const firebaseApp = firebase.initializeApp(firebaseConfig);
export const firebaseAuth = firebaseApp.auth();
export const firebaseDb = firebaseApp.database();
// firebase.storage() seems to be null
export const firebaseStorage = firebase.storage();`

And my configuration ( config.js):

export const firebaseConfig = {
apiKey: 'my api key',
authDomain: 'my-project-id.firebaseapp.com',
databaseURL: 'https://my-project-id.firebaseio.com',
projectId: 'my-project-id',
storageBucket: 'my-project-id.appspot.com',
messagingSenderId: 'my-sender-id'
};

Any idea ?

Steps to reproduce:

@jshcrowthe I have create a new project with create-react-app:
https://github.com/ataliadvanstep/firebase-jest
Just clone the project and run npm test
image

Relevant Code:

https://github.com/ataliadvanstep/firebase-jest

FR: Easy way to compare equivalent Firebase references

  • Operating System version: Ubuntu 16.04
  • Firebase SDK version: 3.9
  • Firebase Product: database

When creating two Firebase database queries, it'd be nice if we could compare said refs for equivalence, like so:

let x = firebase.database().ref('/items').orderByValue();
let y = firebase.database().ref('/items').orderByValue();
x.equiv(y) // => true

The use-case is for something like a React component that takes a Firebase ref as a prop. When we're passed a Firebase reference that's functionally different from the previous ref, we want to unsubscribe from the old ref and start listening to the new one. But if the new ref is essentially the same as (but necessarily === to) the old one, we want to avoid the overhead of unsubscribing and resubscribing.

Problem converting a promise to an observable

Hello,

I was redirected here by the people at Angularfire 2 regarding an issue I opened a few days ago. I'm not sure I should copy-paste the issue content, but here it is. Please feel free to remove everything below if you feel like it's unnecessary to write it all again).

All the best, and thank you for the amazing work.

Version info

Angular: 4.0.0
Firebase: 4.1.2
AngularFire: 4.0.0-rc.1
Other (e.g. Ionic/Cordova, Node, browser, operating system):

  • RxJS 5.4.1
  • OS X 10.12.5
  • Safari 10.1.1

How to reproduce these conditions

public logout1(): Observable<any> {
  return Observable.fromPromise(
    this.afAUth.auth.signOut()
  ).map(() => this.cleardData());
}

public logout2(): Observable<any> {
  return Observable.create(obs => {
    this.afAUth.auth.signOut()
      .then(() => {
        console.log('logged out');
        obs.next();
      })
      .catch(err => {
        throw Error(JSON.stringify(err));
      });
  }).map(() => this.cleardData());
}

public logout3(): Promise<any> {
  return new Promise((reject, resolve) => {

    this.afAUth.auth.signOut()
      .then(() => {
        console.log('logged out');
        this.cleardData();
        resolve();
      })
      .catch(err => {
        reject(err);
      });

  });
}

this.auth.logout1().subscribe(
  () => console.log('Logged out'),
  err => console.error('Could not log out')
);

this.auth.logout2().subscribe(
  () => console.log('Logged out'),
  err => console.error('Could not log out')
);

this.auth.logout3()
  .then(() => console.log('Logged out'))
  .catch(err => console.error('Could not log out'));

Expected behavior

All above calls should output something.

Actual behavior

Only that to logout3 does.

CDN webpackJsonp function conflicts with existing webpackJsonp function

[REQUIRED] Describe your environment

  • Operating System version: macOS 10.12
  • Firebase SDK version: 4.1.1 (CDN)
  • Firebase Product: all

[REQUIRED] Describe the problem

Steps to reproduce:

It appears that the client is bundled via webpack and uses the CommonsChunkPlugin. My code is also bundled via webpack uses the same plugin. As a result my code defines webpackJsonp on the window and then later when I load Firebase from the CDN it tries to use my webpackJsonp function which won't work because they are different bundles.

<!-- My Wepback bundles -->
<script src="/assets/bundle/common.js"></script>
<script src="/assets/bundle/app.js"></script>
<!-- Firebase -->
<!-- (throws an error) -->
<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase.js"></script>

Firebase should change the name of the jsonp function used to something like webpackJsonpFirebase to avoid conflicts.

https://webpack.js.org/configuration/output/#output-jsonpfunction

This needs to be changed if multiple webpack runtimes (from different compilation) are used on the same webpage.

Relevant Code:

Firebase js sdk inside of iframe makes desktop safari freezing.

Describe your environment

  • Operating System version: Mac OSX 10.11.6
  • Firebase SDK version: 4.0.0
  • Firebase Product: auth, database

Describe the problem

We use firebase js sdk inside of an iframe element.
That work for almost case but not work for desktop safari(ver 10.0.2).

Steps to reproduce:

In specific,

    1. Open page and connect firebase database.
    1. Open new tab and open same location of 1
    1. Open new tab repeatedly and safari frozen.

Relevant Code:

<!doctype html>
<html>
  <head>
  </head>
  <body>
    <script>
      const iframe = document.body.appendChild(document.createElement('iframe'));
      iframe.onload = () => {
        const doc = iframe.contentDocument;
        doc.open();
        doc.writeln('<!doctype html>');
        doc.writeln('<head>');
        doc.writeln(`<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></s` + `cript>`);
        doc.writeln(`<script>firebase.initializeApp({apiKey: "API_KEY",authDomain: "AUTH_DOMAIN",databaseURL: "DATABASE_URL",storageBucket: "BUCKET"});</s` + `cript>`);
        doc.writeln(`<script>firebase.database().ref('DATABASE_URL').on('value', () => {})</s` + `cript>`);
        doc.writeln('</head>');
        doc.writeln('<body>');
        doc.writeln('<a href="https://www.google.com" target="_top">go to google</a>')
        doc.writeln('</body>');
        doc.close();
      }
      iframe.src = 'javascript:false';
    </script>
  </body>
</html>

In above example, link to google is worked expected, but if more than 3 or more tab opened, link to google is not accessible or iframe is disappeared.

FR: Allow for gradual "firebase.initializeApp"

Hello,
In order to minimize load time, I am trying to build an web-app where I do not include all js files at startup time. Rather, I gradually download the different firebase-js files on a need to have basis.
I only need to interact with the firbase-database after the user has been authenticated. so initially I only includefirebase-app.jsand firebase-auth.js.
After the user had been successfully logged in, I download firebase-database.js and start interacting with the real-time database.
My problem is that I am getting an error:
firebase.database() takes either no argument or a Firebase App instance.
I believe the above error is caused as I call firebase.initializeApp(config); before firebase-database.js is available. Note, that the exception is only thrown when I try to use firebase.database!

I guess it should not be too hard to allow for gradual firebase initialization. For instance, only initializing with the databaseURL after some time (i.e. after firebase-database.js is available).
PS: Obviously, my web-app works without problem if I do include/download all necessary js files at startup (firebase-app.js, firebase-auth.js and firebase-database.js)

npm install error: Cannot read property 'find' of undefined

[REQUIRED] Describe your environment

  • Operating System version: Windows 10
  • Firebase SDK version: N/A
  • Firebase Product: All

[REQUIRED] Describe the problem

Steps to reproduce:

ionic start MyApp blank
cd MyApp
npm install firebase --save

Error:
Cannot read property 'find' of undefined

Complete Log:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\Program Files\nodejs\node.exe',
1 verbose cli 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'install',
1 verbose cli 'firebase',
1 verbose cli '--save' ]
2 info using [email protected]
3 info using [email protected]
4 silly install loadCurrentTree
5 silly install readLocalPackageData
6 http fetch GET 200 https://registry.npmjs.org/firebase 18ms (from cache)
7 silly pacote tag manifest for firebase@latest fetched in 41ms
8 silly install loadIdealTree
9 silly install cloneCurrentTreeToIdealTree
10 silly install loadShrinkwrap
11 silly install loadAllDepsIntoIdealTree
12 silly resolveWithNewModule [email protected] checking installable status
13 http fetch GET 200 https://registry.npmjs.org/base64url/-/base64url-2.0.0.tgz 15ms (from cache)
14 silly pacote remote manifest for base64url@https://registry.npmjs.org/base64url/-/base64url-2.0.0.tgz fetched in 32ms
15 http fetch GET 200 https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz 3ms (from cache)
16 silly pacote remote manifest for buffer-equal-constant-time@https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz fetched in 10ms
17 http fetch GET 200 https://registry.npmjs.org/dom-storage/-/dom-storage-2.0.2.tgz 5ms (from cache)
18 silly pacote remote manifest for dom-storage@https://registry.npmjs.org/dom-storage/-/dom-storage-2.0.2.tgz fetched in 10ms
19 http fetch GET 200 https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.9.tgz 5ms (from cache)
20 silly pacote remote manifest for ecdsa-sig-formatter@https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.9.tgz fetched in 13ms
21 http fetch GET 200 https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.9.3.tgz 2ms (from cache)
22 silly pacote remote manifest for faye-websocket@https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.9.3.tgz fetched in 14ms
23 http fetch GET 200 https://registry.npmjs.org/hoek/-/hoek-2.16.3.tgz 2ms (from cache)
24 silly pacote remote manifest for hoek@https://registry.npmjs.org/hoek/-/hoek-2.16.3.tgz fetched in 9ms
25 http fetch GET 200 https://registry.npmjs.org/isemail/-/isemail-1.2.0.tgz 3ms (from cache)
26 silly pacote remote manifest for isemail@https://registry.npmjs.org/isemail/-/isemail-1.2.0.tgz fetched in 17ms
27 http fetch GET 200 https://registry.npmjs.org/joi/-/joi-6.10.1.tgz 3ms (from cache)
28 silly pacote remote manifest for joi@https://registry.npmjs.org/joi/-/joi-6.10.1.tgz fetched in 20ms
29 http fetch GET 200 https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-7.4.1.tgz 4ms (from cache)
30 silly pacote remote manifest for jsonwebtoken@https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-7.4.1.tgz fetched in 34ms
31 http fetch GET 200 https://registry.npmjs.org/jwa/-/jwa-1.1.5.tgz 2ms (from cache)
32 silly pacote remote manifest for jwa@https://registry.npmjs.org/jwa/-/jwa-1.1.5.tgz fetched in 5ms
33 http fetch GET 200 https://registry.npmjs.org/jws/-/jws-3.1.4.tgz 4ms (from cache)
34 silly pacote remote manifest for jws@https://registry.npmjs.org/jws/-/jws-3.1.4.tgz fetched in 9ms
35 http fetch GET 200 https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz 2ms (from cache)
36 silly pacote remote manifest for lodash.once@https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz fetched in 5ms
37 http fetch GET 200 https://registry.npmjs.org/moment/-/moment-2.18.1.tgz 3ms (from cache)
38 silly pacote remote manifest for moment@https://registry.npmjs.org/moment/-/moment-2.18.1.tgz fetched in 40ms
39 http fetch GET 200 https://registry.npmjs.org/ms/-/ms-2.0.0.tgz 3ms (from cache)
40 silly pacote remote manifest for ms@https://registry.npmjs.org/ms/-/ms-2.0.0.tgz fetched in 6ms
41 http fetch GET 200 https://registry.npmjs.org/promise-polyfill/-/promise-polyfill-6.0.2.tgz 2ms (from cache)
42 silly pacote remote manifest for promise-polyfill@https://registry.npmjs.org/promise-polyfill/-/promise-polyfill-6.0.2.tgz fetched in 6ms
43 verbose stack TypeError: Cannot read property 'find' of undefined
43 verbose stack at opts.integrity.digests.find.hash (C:\Program Files\nodejs\node_modules\npm\node_modules\ssri\index.js:262:33)
43 verbose stack at Array.find (native)
43 verbose stack at Transform.on (C:\Program Files\nodejs\node_modules\npm\node_modules\ssri\index.js:261:15)
43 verbose stack at emitNone (events.js:110:20)
43 verbose stack at Transform.emit (events.js:207:7)
43 verbose stack at endReadableNT (_stream_readable.js:1045:12)
43 verbose stack at _combinedTickCallback (internal/process/next_tick.js:102:11)
43 verbose stack at process._tickCallback (internal/process/next_tick.js:161:9)
44 verbose cwd C:\Users\andre\dev\remindr
45 verbose Windows_NT 10.0.15063
46 verbose argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install" "firebase" "--save"
47 verbose node v8.0.0
48 verbose npm v5.0.0
49 error Cannot read property 'find' of undefined
50 verbose exit [ 1, true ]

FR: support remote config

It seems that remote config is only available in the ios, and, c++ and unity sdk.
Could it be possible to implement it in the js sdk as well.
I think having the A/B Testing feature using some analytics for segmentation would be very nice.

I see few project that tried to create some workaround like: cordova-plugin-firebase-remoteconfig and react-native-firestack but I think the right place is in the sdk itself.

Some people where requesting this feature last year already ( https://stackoverflow.com/questions/38321012/firebase-remote-config-feature-for-web-app-after-firebase-expansion ).
What is the problem with adding this feature to the js sdk ?

FR: Source maps for docs

Add a source map to the doc generation process so that reference docs can link directly into source files for each function/constant/etc.

FR: Local development server

Not sure if this should be merged into #6 or treated separately, but I have a few related feature requests:

  • Better integration with urish/firebase-server. It technically mostly works, but having to use 127.0.1 as the address (or edit /etc/hosts) seems like an unnecessary hack.

  • Greater involvement from the Firebase team in firebase-server development (to at least get it feature compatible with the production Firebase environment) or a first-party replacement.

  • Support for locally testing Firebase Storage. At the very least, an equivalent to FirebaseOptions .databaseURL for Storage that would allow me to pass in http://my-gcloud-dev_appserver/_ah/gcs would be very useful.

Erroneous behavior when app is started while offline

[REQUIRED] Describe your environment

  • Operating System version: n/a
  • Firebase SDK version: 4.1.3
  • Firebase Product: database

[REQUIRED] Describe the problem

If a web app is started while the device is offline (for example if it's cached via service workers, or a Cordova app) the SDK doesn't properly initialize.
When the app regains connectivity. all the subsequent long polling requests (https://the-nss-server.firebaseio.com/.lp?...) return with a status of 400 Bad request, and the attempted web socket connection is immediatley closed.

Once the app is in that state, not even refreshing the page fixes it. After a while, though, it seems to sort itself out and reconnects.

Steps to reproduce:

  1. git clone https://github.com/firebase/quickstart-js.git
  2. cd quickstart-js/database
  3. Create a new project, allow write from anyone to the database, enable Google auth
  4. firebase use --add and select the new project
  5. firebase serve
  6. While still online go to http://localhost:5000 and check that everything works as expected
  7. Close the app
  8. Go offline, either by disabling the network adapter or by any other means (checking "Offline" in dev-tools is not an option here since we still want to access the local server)
  9. Open the app again. Long polling connections will fail to connect as expected.
  10. Go online
  11. Notice that all long polling requests fail with a 400 status, websocket is immediately closed

Relevant Code:

n/a

Test the robot - it will close this issue

[READ] Step 1: Are you in the right place?

  • For issues or feature requests related to the code in this repository
    file a Github issue.
    • If this is a feature request make sure the issue title starts with "FR:".
  • For general technical questions, post a question on StackOverflow
    with the firebase tag.
  • For general Firebase discussion, use the firebase-talk
    google group.
  • For help troubleshooting your application that does not fall under one
    of the above categories, reach out to the personalized
    Firebase support channel.

[REQUIRED] Step 2: Describe your environment

  • Operating System version: _____
  • Firebase SDK version: _____
  • Library version: _____
  • Firebase Product: _____ (auth, database, storage, etc)

[REQUIRED] Step 3: Describe the problem

Steps to reproduce:

What happened? How can we make the problem occur?
This could be a description, log/console output, etc.

Relevant Code:

// TODO(you): code here to reproduce the problem

token returned from createCustomToken() not working in REST call

Environment

  • Operating System version: Mac Sierra 10.12.5
  • Firebase SDK version: 3.6.3
  • Firebase Admin SDK version: 4.2.1
  • Firebase Product: auth (auth, database, storage, etc)

Problem

I would like to create a custom token using createCustomToken() , and then I need to make
a REST call using the API like :
http://firebase....com/.json?auth=<ACCESS_TOKEN>
OR
http://firebase....com/.json?access_token=<ACCESS_TOKEN>
(I've tried both)
I am always getting 401, even when there are no rules on the firebase node I'm trying to reach (unprotected).

Steps to reproduce:

use the SDK to create a custom token
take this token and attempt to make a REST call to some firebase node

Relevant Code:

const accessToken = await firebaseAdmin.auth().createCustomToken("SomeIssuer", { scopes: "SomeScope" });
 const axiousReq = await axios.get('http://firebase....com/.json?access_token=' + accessToken);

FR: Ability to contribute to the Auth module

It seems that currently, it is not possible to contribute to the Auth module.
Unless I missed something in my findings, as can be seen at auth.build.js.
The whole of Auth module is already checked in in a post build file.
Thus creating PRs to improve this module is impossible at the moment.
The Auth module is one of the greatest features of Firebase and It a shame that the community can't contribute to improve this important piece of Firebase.
My request is simply to allow a way to contribute to the original pre-built file.
Would very appreciate your feedback on this matter,
Thanks!

Storage: TypeError thrown when UploadTask#on observer is missing some methods

[REQUIRED] Describe your environment

  • Operating System version: Linux & Windows 10
  • Firebase SDK version: 4.1.1
  • Firebase Product: storage

[REQUIRED] Describe the problem

According to the documentation, the nextOrObserver parameter for the firebase.storage.UploadTask#on method should accept an observer with only some of the methods: next, complete, and error.

That means this should be allowed:

uploadTask.on(TaskEvent.STATE_CHANGED, {
  next: (snapshot) => { console.log(snapshot); },
  error: (err) => { console.error(err); }
});

This, though, raises the following error: TypeError: Cannot read property 'bind' of undefined since observer.complete is undefined. Relevant code here.

Currently, the only workaround besides providing an actual method is this:

uploadTask.on(TaskEvent.STATE_CHANGED, {
  next: (snapshot) => { console.log(snapshot); },
  error: (err) => { console.error(err); },
  complete: null
});

Steps to reproduce:

See JS Bin link below.

Relevant Code:

http://jsbin.com/yujaraboma/1/edit?js,console

FR: Ability to intercept and handle message in our code, even if `notification` fields are set

[REQUIRED] Describe your environment

  • Operating System version: win7
  • Firebase SDK version: 3.9.0
  • Firebase Product: messaging

[REQUIRED] Describe the problem

Sending a message with notification payload never triggers the setBackgroundMessageHandler callback.

The guide (but not the reference) hint at this behaviour: "If you set notification fields [...] those values take precedence over any values specified in the service worker."

This makes it impossible to intercept the message if notification fields are set.

Use case: we are sending additional fields in data but are not able to access and use them. We also can't modify the notification fields before displaying them to the user.

Steps to reproduce:

Send a message with notification data. The callback of setBackgroundMessageHandler is never called.

Error: firebase auth/network-request-failed with sw-precache's navigateFallback

[READ] Step 1: Are you in the right place?

  • For issues or feature requests related to the code in this repository
    file a Github issue.
    • If this is a feature request make sure the issue title starts with "FR:".
  • For general technical questions, post a question on StackOverflow
    with the firebase tag.
  • For general Firebase discussion, use the firebase-talk
    google group.
  • For help troubleshooting your application that does not fall under one
    of the above categories, reach out to the personalized
    Firebase support channel.

[REQUIRED] Step 2: Describe your environment

  • Operating System version: Windows 10
  • Firebase SDK version: 3.6.3
  • Library version: 3.6.3
  • Firebase Product: auth

[REQUIRED] Step 3: Describe the problem

Steps to reproduce:

What happened? How can we make the problem occur?
This could be a description, log/console output, etc.

Error: auth/network-request-failed

Relevant Code:

signInButton.onclick = () => {
  const provider = new firebase.auth.GoogleAuthProvider();
  firebase.auth().signInWithPopup(provider);
};

FR: Alternative to getDownloadURL that doesn't expose a public download URL

[REQUIRED] Describe your environment

  • Operating System version: [all]
  • Firebase SDK version: 4.1.3
  • Firebase Product: storage

[REQUIRED] Describe the problem

Currently, the only way to get an image is to call getDownloadUrl. The download URL is unguessable but not affected by security rules, which means that once someone has the download URL, they could theoretically use a bot to create a huge number of downloads and run up a big Cloud Storage bill or hit the project quota.

The Android SDK provides getFile, which downloads the file directly to the device. Each download involves a security rules check (source).

Request

Provide a function like getFile that checks security rules every time.

Alternatively, perhaps a function that returns a signed URL (for example, getSignedUrl(expireTime)) could accomplish a similar goal.

FR: Cache API

Something I had to develop myself when working with Firebase is a small cache API so that users going back to previous views would not have to wait for data.

I implemented a in memory cache with a persistent on() connection in the background completely decoupled from my views. After the initial data download from a database path, this memory cache is only updated with value events so even for large datasets it works great. My users always see the updated data when returning to previous views instantly.

In any case, the Firebase SDK needs to provide a way to cache the data somehow. Maybe this would go hand in hand with the offline functionality, or not.

Error on app.d.ts about static credential

Hello,

In app.d.ts and firebase.d.ts the function credential return a Promise, but when i compile the application i have this error in console: " the function .then() missing".
In the firebase-js-sdk the function "credential" return firebase.auth.AuthCredential ?

static credential (verificationId : string , verificationCode : string ) : firebase.Promise < any > ;
==>
static credential (verificationId : string , verificationCode : string ) : firebase.auth.AuthCredential ;

Is a goog solution?

Thank you!

One more try - bad issue

[READ] Step 1: Are you in the right place?

  • For issues or feature requests related to the code in this repository
    file a Github issue.
    • If this is a feature request make sure the issue title starts with "FR:".
  • For general technical questions, post a question on StackOverflow
    with the firebase tag.
  • For general Firebase discussion, use the firebase-talk
    google group.
  • For help troubleshooting your application that does not fall under one
    of the above categories, reach out to the personalized
    Firebase support channel.

[REQUIRED] Step 2: Describe your environment

  • Operating System version: _____
  • Firebase SDK version: _____
  • Library version: _____
  • Firebase Product: _____ (auth, database, storage, etc)

[REQUIRED] Step 3: Describe the problem

Steps to reproduce:

What happened? How can we make the problem occur?
This could be a description, log/console output, etc.

Relevant Code:

// TODO(you): code here to reproduce the problem

`auth/network-request-failed` being thrown on Cordova app when sign in

Describe your environment

  • Operating System version: Android 7.1.1, iOS 10.3.2
  • Firebase SDK version: 3.9.0
  • Firebase Product: auth

Describe the problem

Cannot reliably sign in using Firebase email and password on cordova app (Android and iOS). When signing in auth/network-request-failed is thrown.

Steps to reproduce:

I can reproduce this 100% of the time on my Nexus 5x phone (also tested on Firefox and Chrome desktop, but never encounter this problem). cordova-plugin-whitelist is configured and has been worked in the past. I experimented a lot, the steps to reproduce is like this:

From Android phone:

  1. Use login form with email, password, and login button
  2. Enter email and password
  3. While device keyboard is still opened, press enter (big right arrow on some keyboards) or the login button and auth/network-request-failed will be thrown
  4. Tap somewhere else to close the keyboard, press the login button and auth/network-request-failed will be thrown again
  5. Tap into email or password input, press enter (big right arrow on some keyboards) or the login button and now it will log in successfully

It should has nothing to do with the keyboard or input focus / refocus but I don't have any clue either.

Related issue: angular/angularfire#581

Downgrading to Firebase SDK 3.3 does solve this issue as mentioned in the above thread.

Relevant Code:

firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
  console.log(error.code);   // `auth/network-request-failed`
});

Auth - Cordova - signInWithRedirect - A network error (such as timeout, interrupted connection or unreachable host) has occurred.

  • Operating System version: Android / Cordova
  • Firebase SDK version: 4.1.3
  • Firebase Product: auth

Followed these instructions, so I assume it is officially supported and this can be a forum to ask: https://firebase.google.com/docs/auth/web/cordova

When using signInWithRedirect in a Cordova environment and regardless of the auth provider (happen in Facebook, Google, Twitter), I receive this error below 90% of the time. Yes, it works perfectly fine around 10% of the time:

auth/network-request-failed
A network error (such as timeout, interrupted connection or unreachable host) has occurred.

My thought is Auth is giving up and failing because the the cordova-browsertab-plugin is taking a few too many milliseconds to respond. The would explain why I am receiving sporadic timeouts/network errors. If not this, any reason why I receive this error?

signInWithEmailAndPassword works perfectly fine, all the time. But, I think it's because there is no use of the Cordova browser tab plugin.

[Bug] signInWithPopup creates new tab instead of popup in Chrome 59

Describe your environment

  • Operating System version: OSX Sierra 10.12.4
  • Firebase SDK version: 4.1.2
  • Firebase Product: Auth

Describe the problem

When using firebase.auth.signInWithPopup(provider) a new tab is created with the auth instead of creating a popup as it did in Chrome 58 and earlier.

https://stackoverflow.com/questions/44417724/facebook-authentication-opening-tab-instead-of-popup-in-chrome-59 seems to say that the parameter 'location=no' needs to be passed in window.open(), but this is not accessible using the SDK.

Steps to reproduce:

Create an auth button with signInWithPopup() and click on it. A new tab will pop up instead of a new popup window.

Relevant Code:

This link describes the problem perfectly.

https://stackoverflow.com/questions/44417724/facebook-authentication-opening-tab-instead-of-popup-in-chrome-59

auth/operation-not-supported-in-this-environment in Cordova application

Environment

  • Operating System version: MacOS Sierra 10.12.5
  • Firebase SDK version: 4.1.3
  • Firebase Product: Authentication

Problem

firebase.auth.Auth is returning this error on both iOS and Android Cordova platforms.

Steps to reproduce / Relevant Code:

A reproducible example with steps is at this repository.

The error occurs when the app loads. The code triggering the error is nearly the same as in the docs at the bottom, "to handle the case where the app activity is destroyed before the sign-in operation completes, call getRedirectResult when your app loads.":

firebase.auth().getRedirectResult().then(result => {
  var user = result.user
  console.log(user)
}).catch(error => {
  this.message = error.message
})

Since the example received this error without providing an API key, I have a full example on the master branch where you can provide an API key and install the plugins, but the error still occurs.

FR: Offline first support for PWAs (RTDB)

While the Firebase JS SDK has support for offline scenarios when the web app goes from online to offline it lacks offline first support.
Offline first is a crucial part of PWAs and should be supported by the Firebase JS SDK directly.

FR: Storage for node.js

There is a way to use it with Google Cloud, but it is a bit complicated and firebase storage directly for web is much easier and convenient to use.

FR: client only mode (db with no remote link)

It would be nice to be able to initiate a client-only database (no url, no remote link). Use cases:

  • viewStore seperate from the datastore
  • prototypes, stubs and testing
  • components with common interfaces

My specific use case is that the model data (what is shared) needs to be heavily transformed on the client side (monte carlo simulations in web worker) so that an internal view DB is needed in addition to the shared model DB.

Given that firebase database lib is already over 100kb it feels akward need another lib (pouch db, lokijs, gun, ...) for internal app use to implement similar functionalities in a different API.

This is partly related to #34 (testing) since it would also facilitate creating and unit-testing independent module and components by removing all of the console registering and development server requirements.

Edit

I found out I can use firebase.initializeApp({databaseURL: 'x.y.z'}, 'local').database().goOffline() but it feels like a bit of hack. Is it the correct way to do it or is this likely to fail in the future?

Partial imports with rollup failing

Following up on #45 and on @jshcrowthe's comment:

Use case: just importing the database layer to develop and unit test individual modules that need a common async data store. They will likely eventually be used in the browser but development, unit testing, and packaging is just so much easier and faster in node.

//app.js
import * as firebase from './node_modules/firebase/app'
import './node_modules/firebase/database'
firebase.initializeApp({databaseURL: 'x.y.z'}, 'local').database().goOffline()
  1. using rollup in the CLI >rollup -o app.bld.js -f cjs app.js
     'initializeApp' is not exported by 'node_modules\firebase\app.js'
     Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification
  1. using rollup in a script with the nodeResolve() and commonjs({include: 'node_modules/**'}) plugins
    'initializeApp' is not exported by 'node_modules\firebase\app.js'
  1. Tried importing from ./node_modules/firebase/firebase-app but being build for the browser I get a navigator error in node

  2. I also tried many a few combinations directly in the firebase/app/ folder with browserify to get an intermediate build that would be easier to consume but the build system looks like it was hacked to suit babel.

I understand I am trying to use the database component in a way that is not the intended typical use but I thought that if there were less frictions in just using the firebase toolset it would be much easier to get there progressively.

fetch is not a function

Describe your environment

  • Operating System version: Ubuntu 14.04.02
  • Firebase SDK version: 4.1.3
  • Firebase Product: messaging

Describe the problem

Firebase messaging doesn't work with latest npm package. It throws:

TypeError: fetch is not a function
    at WindowController.manifestCheck_ (window-controller.js?:149)
    at WindowController.getToken (window-controller.js?:125)

Exact line in code is here

Steps to reproduce:

Install latest firebase package from npm. Follow tutorial given here.

Relevant Code:

      firebase.initializeApp(opts);
      const messaging = firebase.messaging();
      messaging.requestPermission()
        .then(function() {
          console.log('Notification permission granted.');
          return messaging.getToken()
            .then((currentToken) => {
              if (currentToken) {
                console.log("Token is: " + currentToken)
              } else {
                // you don't have permission to show notifications
                // detect whether they are blocked or not, then show your custom UI
              }
            })
            .catch((err) => {
              console.log("Error to get token is: " + err);
              // retrieving token failed, analyze the error
            });
        })
        .catch(function(err) {
          console.log('Unable to get permission to notify.', err);
        });

FR: [Auth] Allow to sign in with a token obtained from another App

[REQUIRED] Describe your environment

  • Operating System version: Linux
  • Firebase SDK version: 4.1.2
  • Firebase Product: auth

[REQUIRED] Describe the problem

In certain scenarios, it could be useful to authenticate a firebase.app.App with a token obtained via firebase.User#getToken() from another App, when both Apps are initialized against the same Firebase project.

My use case for this is as follows: when a certain event happens, I want to close the connection to the database to stop receiving any new updates from whatever listeners I have attached, but I still need to listen to a particular location in the database that will alert me when I need to connect again.

At the moment there's no way to authenticate a second App with the same token/credentials already present in the current App. The only way to achieve this right now would be to either ask the user to reauthenticate when initializing the second App, or to initialize and authenticate both Apps at the same time when the user logs in.

Related firebase-talk discussion: https://groups.google.com/forum/#!msg/firebase-talk/X5ry98EfK-w/8TnY2i8rCgAJ

Steps to reproduce:

n/a

Relevant Code:

A possible solution would be to introduce a new firebase.auth.Auth#signInWithIdToken() method which would allow to do the following:

const options = {/* ... */};
const app1 = firebase.initializeApp(options, 'app1');
const app2 = firebase.initializeApp(options, 'app2');

// Let's assume "app1" is already authenticated
app1.auth().currentUser.getIdToken().then(token => app2.auth().signInWithIdToken(token));

Alternatively, a new IdTokenAuthProvider could be introduced, allowing to authenticate with the already existing firebase.auth.Auth#signInWithCredential():

const options = {/* ... */};
const app1 = firebase.initializeApp(options, 'app1');
const app2 = firebase.initializeApp(options, 'app2');

// Let's assume "app1" is already authenticated
app1.auth().currentUser.getIdToken().then(token => {
  const cred = firebase.auth.IdTokenAuthProvider.credential(token);
  app2.auth().signInWithCredential(cred);
});

Introducing a new AuthProvider for this might be confusing for the end-user though, so my preferred solution would be signInWithIdToken.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.