Rectangle 27 7

1.Create a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google project associated with your app, click Import Google Project. Otherwise, click Create New Project.

3.Select Service accounts from the menu on the left.

  • Enter a name for your service account.
  • You can optionally customize the ID from the one automatically generated from the name.
  • Select Furnish a new private key and leave the Key type as JSON.

This might be what you're looking for. This was in the tutorial on the site

This for the officially supported firebase SDKs. Where in the doc it says, Java and nodejs.

Where can I find the API KEY for Firebase Cloud Messaging? - Stack Ove...

firebase google-cloud-messaging firebase-cloud-messaging
Rectangle 27 5

You need to setup an authentication server which can create Firebase custom tokens, using the accountkit user id or phone number as the uid.

Once you receive the custom token from the authentication server, you then use it to sign into firebase like this:

mAuth.signInWithCustomToken(mCustomToken)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                Log.d(TAG, "signInWithCustomToken:onComplete:" + task.isSuccessful());
                if (!task.isSuccessful()) {
                    Log.w(TAG, "signInWithCustomToken", task.getException());
                    Toast.makeText(CustomAuthActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

android - Firebase: Can I use Facebook's new Account Kit to authentica...

android ios facebook firebase firebase-authentication
Rectangle 27 1

The rules in your screenshot are different from the ones you posted before.

In Firebase Database security model, permissions cascades down: once you give a user read or write permission on a node, you cannot take that permission away on a lower level. See the documentation on security rules for more information.

If you remove the top-level ".write": "auth !== null", you will find that you can no longer write to /users and can only write to /users/uid123 if you're user uid123.

Why can I write to `/users` with these Firebase Database rules? - Stac...

firebase firebase-database firebase-security
Rectangle 27 0

[Disclosure: I work for Firebase] We do root for you reaching that number of course. :-)

Firebase - How many databases can be created? - Stack Overflow

firebase
Rectangle 27 0

Firebase does not store arrays when you use push() 1 2. Instead, it creates a unique, time-based id and stores the value in an object using that ID. They look something like this:

There are a lot of reasons why this approach was chosen, and why it's a bad idea to utilize arrays in a real-time data store 1.

One nicety is that all modern browsers properly order objects in every case, excluding the highly contested numeric sorting of chrome 1 2 3.

Given these facts, and the fact that Firebase's push ids are strings that sort lexicographically, the REST API will return the records in the same order they are pushed, and as they appear in Forge, which a quick curl test will confirm.

The only place you could get into trouble would be by using numeric ids, which could naturally cause some mahem in Chrome. Of course, those are easily fixed by putting a "0" or a string prefix on each id to force Chrome to sort them lexicographically as well 1.

var a = {"foo":"bar", "03": "3", "02":"2", "01":"1"};
for(var i in a) { print(i) };

produces following output as expected:
foo
3
2
1

How can I read Firebase ordered data via the REST API? - Stack Overflo...

firebase
Rectangle 27 0

Firebase client libraries are generally not meant to be repackaged for use in other libraries. They're meant to be used at the app level.

A unique SHA-1 key is required on Android for Authentication to work with a particular app identified by package name. This requirement will definitely become a problem for you if you want this to work with arbitrary apps, since you would have to manually enter one for each app that wants to integrate.

Can Firebase Database be set up to host data for 3rd party client? (e....

firebase firebase-database firebase-authentication
Rectangle 27 0

For the moment that is not possible. Firebase set an uuid for each facebook account when login for first time.

Can we merge an account of many users in the same service into one fir...

firebase firebase-authentication
Rectangle 27 0

Yes, Firebase Auth supports that via the Account Linking API.

I know there are Account Linking API. My point is, is it possible to link multiple facebook account into one firebase account

As you might know, a person could have multiple twitter account. Some people may have 2 facebook accounts reserved for one got banned or hacked. Something like that

Multiple facebook accounts can be linked into the same Firebase account. Same for Twitter or Google accounts. If you have tried and it does not work, please file a bug report to Firebase.

Can we merge an account of many users in the same service into one fir...

firebase firebase-authentication
Rectangle 27 0

Your myArray is not array of string, it's dictionary. So if you want value of a,b and c in cell.myTestView.text. Then you need to run loop to get all a,b and c in cell.myTestView.text.

var string = ""

for (key, value) in arrayList[hh].myArray
{
    print("\(key) -> \(value)")
    string = string + "\n\(key) -> \(value)"
}

cell.myTestView.text = string
cell.myTestView.text = (arrayList[hh].myArray as AnyObject) as? String

I have error in this line (for (key, value) in arrayList[hh].myArray) says [Ambiguous reference to member 'subscript']

add 'as! [String:String]' to arrayList[hh].myArray. Or make myArray as [String:String]. replace line var myArray : NSArray = [] in text class to var myArray = [String:String]()

ios - How can I store object has a multiple strings from firebase data...

ios firebase swift3 firebase-database
Rectangle 27 0

I've asked the same question previously, because my engineer instincts tell me I can never duplicate data. The conclusion that I came to after I thought this through to the logical end, is that even in a SQL database there exists tons of duplication. It's simply hidden under the covers (as indices, temporary tables, and memory caches). This is a part of large and active data.

So drop the timestamp in the data and go have lunch; save yourself some energy :)

Alternately, skip the timestamp entirely. You know that the records are stored by timestamp already, assuming you haven't provided your own priority, so you should be good to go.

Firebase IDs - can I extract the date/time generated? - Stack Overflow

firebase
Rectangle 27 0

You need to POJO/Custom class to efficiently write/read to a Firebase database. Idealy, you have created a class Message with setters and getters and a default constructor defined:

class Message {
  private String message;

  public Message() {
  }
  public Message(String message) {
    this.message = message;
  }

  public void getMessage() {
    return message;
  }
  public void setMessage(String message) {
    this.message = message;
  }
}
{
 "rules": {
   "message": {
    "$uid": {
      ".write": "$uid === auth.uid",
      ".read": "$uid === auth.uid"
   }
  }
 }
}

Then in your java code do this:

DatabaseReference mDatabaseReference;
FirebaseUser firebaseUser;

 mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            firebaseUser = firebaseAuth.getCurrentUser();
            if (firebaseUser != null) {
                // User is signed in
            } else {
                // User is signed out
            }
        }
    };
...


//To save a message associated to only the signed in user
Message message = new Message();
message.setMessage("a message");
mDatabaseReference = FirebaseDatabase.getInstance().getReference(); 
mDatabaseReference.child("message").child(firebaseUser.getUid())
     .setValue(message)
     .addOnCompleteListener(DetailsCaptureActivity.this, new OnCompleteListener<Void>() {
     ...
  });
//Set up an AuthStateListener that responds to changes in the user's sign-in state:
    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            firebaseUser = firebaseAuth.getCurrentUser();
            if (firebaseUser != null) {

                   databaseReference = firebaseDatabase.getReference().child("message").child(firebaseUser.getUid());
                   databaseReference.addValueEventListener(new ValueEventListener() {
                      @Override
                      public void onDataChange(DataSnapshot dataSnapshot) {
                          Message message = dataSnapshot.getValue(Message.class);
                          //You can now get your message using message.getMessage();
                      }

                      @Override
                      public void onCancelled(DatabaseError databaseError) {

                          Log.e(TAG, databaseError.getMessage());
                      }
                  });

            } else {
                Log.e(TAG, "onAuthStateChanged:signed_out");
            }
        }
    };

You can now add your own implementation for retrieving a list of messages.Hopefully, that wouldn't be a problem.

android - How to make sure a user can only see and access their own da...

android firebase firebase-security firebase-authentication
Rectangle 27 0

Wow, great question. This is a usage pattern that we've discussed internally so we'd love to hear about your experience implementing it (support@firebase.com). Here are some thoughts on your questions:

If your primary goal is actually authentication, just wait for our security features. :-) In particular, we're intending to have the ability to do auth backed by your own backend server, backed by a firebase user store, or backed by 3rd-party providers (Facebook, twitter, etc.).

Regardless of auth, there's still an interesting use case for using Firebase as the backbone for some sort of workload balancing system like you describe. For that, there are a couple approaches you could take:

  • As you describe, have a single work queue that all of your servers watch and remove items from. You can accomplish this using transaction() to remove the items. transaction() deals with conflicts so that only one server's transaction will succeed. If one server beats a second server to a work item, the second server can abort its transaction and try again on the next item in the queue. This approach is nice because it scales automatically as you add and remove servers, but there's an overhead for each transaction attempt since it has to make a round-trip to the firebase servers to make sure nobody else has grabbed the item from the queue already. But if the time it takes to process a work item is much greater than the time to do a round-trip to the Firebase servers, this overhead probably isn't a big deal. If you have lots of servers (i.e. more contention) and/or lots of small work items, the overhead may be a killer.
  • Push the load-balancing to the client by having them choose randomly among a number of work queues. (e.g. have /queue/0, /queue/1, /queue/2, /queue/3, and have the client randomly choose one). Then each server can monitor one work queue and own all of the processing. In general, this will have the least overhead, but it doesn't scale as seamlessly when you add/remove servers (you'll probably need to keep a separate list of work queues that servers update when they come online, and then have clients monitor the list so they know how many queues there are to choose from, etc.).

In general, your design is definitely on the right track. If you experiment with implementation and run into problems or have suggestions for our API, let us know (support@firebase.com :-)!

@Michael_Lehenbauer thank you for the great explanation. I'm excited to hear about the diversity of options for authentication--sounds great.

The random work queues idea is interesting; I suppose it creates a bit of a conundrum if the servers go offline. I suppose we could delete the queue if the server falls offline and hold the clients responsible for tracking their requests and delegating it to a new server.

firebase - How can I create a queue with multiple workers? - Stack Ove...

firebase
Rectangle 27 0

The Firebase update() function will allow you to modify some children of an object while leaving others unchanged. The update function will only trigger one "value" event on other clients for the path being written no matter how many children are changed.

itemRef.update({appreciates:newFlag,id:newId});

Can I prevent Firebase set() from overwriting existing data? - Stack O...

firebase
Rectangle 27 0

The recommended way to get data on an entry in firebase is to create class representing the object you want to pull from the DB, making sure all of the members of that class match exactly the keys of the data you wish to pull (e.g. you would have an object with 5 strings, city, country, state, street, zip_postal_code) and make sure all of these objects have setters and getters (just auto generate these)

Then, you can add a listener for your database reference like so:

mDatabase.child("Addresses").child(user_data.getString("uidkey", null)).addListenerForSingleValueEvent(
        new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Get the address object
                Address address = dataSnapshot.getValue(Address.class);
                // get the string here, using address.getCity() or whatever you called the getter

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

You can also add new address objects to your firebase using the same address class.

Additionally, if you are populating a list view, this can be much simpler and cleaner if you use firebaseListAdapter

This is what I have written: I have written that same code and put it in the onStart(); I use String street = addess.getStreet(). This however causes the app to crash due to a null exception.

thats the address class that I am using and the one above is how I am getting it.

See edits to my answer. You need to add "Addresses" as a child of your DB reference before the user ID child.

android - How can I access the child values in firebase realtime Datab...

android firebase-database
Rectangle 27 0

Let's say you want a user to have read access to posts that are owned by themselves.

We have

"post": [
       {
        key: "post_key_1"
        groupKey: "group_key_2"
        userKey: "user_key_1"
        },
       {
        key: "post_key_2"
        groupKey: "group_key_1"
        userKey: "user_key_2"
        },
       {
        key: "post_key_3"
        groupKey: "group_key_2"
        userKey: "user_key_2"
        }
    ]

user_key_1 wants to access post. But we don't want her to see user_key_2. If we want to use orderBy, we would have to call

...
.child("post").orderBy("userKey").equalTo("user_key_2");

But since we can't give selective validation rule within the value (In this case, the post array), we'd end up having to do the following.

"post":{
   .read:true,
   .write:true
}

A malicious hacker can access other things, so we will end up with a database that can be exposed. So to use validation rule the way it is intended, avoid orderBy and use data replication.

A hint to anyone who thinks it should be done on the server side, Here's how I did one.

fanoutObject['/user-post/'+ post.authorUid+"/"+post.key] = post;
    fanoutObject['/group-post/'+post.groupKey+"/"+post.key] = post;

   return event.data.adminRef.root.update(fanoutObject);

This way is great since you just have to always save onto the "/post/" on the client side and that will update the corresponding locations as well.

database - Can Fanout method be replaced by ref.orderByChild(key).equa...

firebase database nosql
Rectangle 27 0

The flow is different from what you seem to assume. If you use custom authentication, it is up to you to control the authentication flow. Then when you've authenticated the user, you mint a token and pass that back to the app. The app then uses this token to authenticate with Firebase Authentication.

If you mint your own tokens, you fully control the uid of the user. In fact that's the only thing that is really required: a UID to identify the user.

Can we provide our own uid for a Firebase database if we use our own a...

firebase firebase-database firebase-authentication
Rectangle 27 0

If you want to store a type for a user you have to user the database. Like this

When the user logs in, get the value from the database for the path "users/<userId>/type". Then use a switch statement to redirect to the correct view controller.

// Sign in to Firebase
 FIRAuth.auth()?.signIn(withEmail: "ntoonio@gmail.com", password: "Password123", completion: {
     (user, error) in
         // If there's no errors
         if error == nil {
             // Get the type from the database. It's path is users/<userId>/type.
             // Notice "observeSingleEvent", so we don't register for getting an update every time it changes.
             FIRDatabase.database().reference().child("users/\(user!.uid)/type").observeSingleEvent(of: .value, with: {
                 (snapshot) in

                 switch snapshot.value as! String {
                 // If our user is admin...
                 case "admin":
                     // ...redirect to the admin page
                     let vc = self.storyboard?.instantiateViewController(withIdentifier: "adminVC")
                     self.present(vc!, animated: true, completion: nil)
                 // If out user is a regular user...
                 case "user":
                     // ...redirect to the user page
                     let vc = self.storyboard?.instantiateViewController(withIdentifier: "userVC")
                     self.present(vc!, animated: true, completion: nil)
                 // If the type wasn't found...
                 default:
                     // ...print an error
                     print("Error: Couldn't find type for user \(user!.uid)")
                 }
            })
        }
    })

Instead of the whole switch statement you can do

let vc = self.storyboard?.instantiateViewController(withIdentifier: "\(snapshot.value)VC")
self.present(vc!, animated: true, completion: nil)

Warning! This will crash if the type wasn't found. But that's fixable

because i am also new to firebase i am also finding it difficult to add data to the database section as its my first time working with JSON trees. Would it be possible to show me how i could input the types of user in the database.

In the switch statement, if the default block is triggered it means there's no data (since we will only input "admin" or "user", you can add as many types as you want) and it's a new user. Here you can set the type with FIRDatabase.database().reference().child("users").child(user.uid).setValue(["type": "<type here>"])

what if i were to input the data manually into the database through the firebase console? would this still work?

Yes, and that would make more sense since you don't want the user to be able to choose to be admin :)

ios - How can i send different users to separate view controllers usin...

ios swift firebase firebase-authentication
Rectangle 27 0

As far as I know it's not possible to do what you want without creating a proxy, as you mentioned. I assume that firebase has some app validation that make unfeasible to share the Auth/DB. Maybe a solution for you is to make a proxy too to access data: "It looks like in order to access Firebase Analytics data, you export it to BigQuery. This is working for me and is automated."

Can Firebase Database be set up to host data for 3rd party client? (e....

firebase firebase-database firebase-authentication
Rectangle 27 0

This is possible to handle within your security rules but you will have to change your database structure a little bit. Instead of what you have now you have to do somthing like this:

"QuickPlay3hanePlaying" : {
  "ByVmFbUC6HS01v4SASeA2ev33zz1" : {
    "Player1" : {
      "3s6TdUxImrNhMReJbS8kBh4I9im1" : {
        "IQ" : 1350,
        ...
        "uid" : "3s6TdUxImrNhMReJbS8kBh4I9im1"
      },
    },
    "Player2" : {
      "ByVmFbUC6HS01v4SASeA2ev33zz1" : {
        "IQ" : 1280,
        ...
        "uid" : "ByVmFbUC6HS01v4SASeA2ev33zz1"
      },
    },
    "userSayisi" : 2
  }

And your security rules would look like this:

{
"rules": {
  "QuickPlay3hanePlaying": {
    "$id": {
      "player1": {".validate": true},
      "player2":{".validate": true},
      "userSayisi": {".validate": true},
      "$other": {".validate": false}
      }
    }
  }
}

The reason for the change in database structure is because you can only have 1 wildcard key in your security rules at a certain position.

Thanks for your response. player1 is using create room function. player2 is using join room function. So if 2 different users join room at the same time, all player2 users can be joined room. I think, i have to compare child count but i can not get child count in security rule. Thanks.

ios - How can i limit child nodes using security rules in Firebase (Sw...

ios swift firebase firebase-security
Rectangle 27 0

You want to use .key() (.name() before 2.x) to fetch the push id for each record.

var ref = new Firebase(URL);
ref.child('contacts').on('child_added', function(snap) {
   var data = snap.val();
   var name = data.first + ' ' + data.last;

   // some proprietary code to add them to the DOM, the critical part 
   // here being that we include the push id in the data...

   // set the push id as data-id so we can refer to it!
   var html = '<li data-id="' + snap.key() + '">' +
       '<span>' + name + '</span> ' +                  // user's name
       '<button data-event="edit">Edit</button> ' +    // edit button
       '<button data-event="delete">Delete</button>' + // delete button
       '</li>';
   $(html).appendTo('#theList');
});

// handle clicking the delete button
$('[data-event="delete"]').click(function(e) {
   e.preventDefault();

   // fetch the push id from data-id="..." attribute
   var pushId = $(this).closest('li').attr('data-id');

   // remove it from Firebase
   ref.child('contacts').child(pushId).remove();
});

Of course, a good framework can save you a great deal of energy here. For example, I'm a fan of Angular:

<ul>
  <li ng-repeat="user in contacts">
     <span>{{user.first}} {{user.last}}</span>
     <button>Edit</button>
     <button ng-click="users.$remove(user)">Delete</button>
  </li>
</ul>
app.controller('ctrl', function($scope, $firebase, $window) {
   var ref = new $window.Firebase(URL);
   $scope.contacts = $firebase(ref).$asArray();
});

Thing is I don't want an ng-repeat on the list items, I display an li for each letter in the alphabet, and then append the names under the corresponding category depending on what the last name starts with. so I'm not sure what I would put in the ng-click with the structure I have?

That's an entirely different question than how to set a unique id for each person. Entirely, massively different. See this post, which explains how to create a directive with multiple nested layers of data: stackoverflow.com/questions/26047958/

javascript - How to set a unique ID for each person in a Firebase data...

javascript firebase