firebase Not saving data - firebase

Im using firebase and for some reason my code is not pushing data and im not seeing the data in the firebase url. My code is this
var chatref = new Firebase('https://flockedin.firebaseio.com/');
chatref.push({ ChatId: $('#conversationId').text(), User: $('#username').html(), Message: $('#txtchat').val() }, function (response) { if (response) { alert('saved'); } });
i get the alert 'saved' but i cant find the data in firebase url.
Also what is the use of API Key that is given for each url in the firebase.
UPDATE:This happens in IE10. In other browsers it works fine

IE10 seems to be working for me. Can you give more details about what version you are using (desktop / tablet / phone?).
Also, is it possible that your jquery selectors were returning null? If all of the values in the object that you set evaluate to null, Firebase treats it like a call to remove. See the note in the docs for set: https://www.firebase.com/docs/javascript-client/firebase/set.html

Try going to your FireBase Console->Database->Rules and set them to:
{
"rules": {
".read": true,
".write": true
}
}
Make sure your app is not public when you do this. Lmk if it helps.

Related

Simple GetItem with ctx.identity.username returns null

I'm using AppSync with IAM auth with a DynamoDB resolver and Cognito. I'm trying to do the following.
{
"version": "2017-02-28",
"operation": "GetItem",
"key": {
"userId": $util.dynamodb.toDynamoDBJson($ctx.identity.username)
}
}
$ctx.identity.username is supposed to contain userId generated by Cognito and I'm trying to use it to fetch current user data.
Client side, I'm using AWS Amplify that tells me I'm currently logged:
this.amplifyService.authStateChange$.subscribe(authState => {
if (authState.state === 'signedIn') {
this.getUserLogged().toPromise();
this._isAuthenticated.next(true);
}
});
getUserLogged is the Apollo query that is supposed to returns user data.
What I've tried:
If I leave it like this, getUserLogged returns null.
If I replace in the resolver $util.dynamodb.toDynamoDBJson($ctx.identity.username) with a known userId like this $util.dynamodb.toDynamoDBJson("b1ad0902-2b70-4abd-9acf-e85b62d06fa8"): It works! I get this user data.
I tried to use the test tool in the resolver page but it only gives fake data so I can't rely on this.
Did I make a mistake? To me everything looks good but I guess I'm missing something?
Can I clearly see what $ctx.identity contains?
You'll want to use $ctx.identity.cognitoIdentityId to identify Cognito IAM users:
https://docs.aws.amazon.com/appsync/latest/devguide/resolver-context-reference.html#aws-appsync-resolver-context-reference-identity
You could see the contents of $ctx.identity by creating a Lambda resolver and logging the event or by creating a local resolver and returning the input that the mapping template receives:
https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-local-resolvers.html
My cognitoIdentityId looks like this: eu-west-1:27ca1e79-a238-4085-9099-9f1570cd5fcf

Firebase rules not working with code

I am not able to make the security rules in Firebase database working although the simulator shows they are in place.
A simple example:
{
"rules": {
"items":{
"$itemid":{
".read":true,
".write":"newData.child('id').isNumber()"
}
}
}
}
For above rules when I try posting an item from simulator with text value in 'id' it gives proper error as expected.
For Url: /items/-sdsd123
And for data: {"id":"MAC1", "name":"Macbook Pro"}
It gives write denied error in simulator as 'id' is not number.
However after publishing the rules and trying from code or browser data editor it allows the id to be text value. Below works:
var key = db.ref("/items").push().key;
db.ref('/items/' + key).set({"id":"MAC1", "name":"Macbook Pro"});
I am missing something basic but not able to figure it out, kindly help.

When using Polymerfire and anonymous login, there is no data in firebase-query object

I want to create a website using Firebase and Polymer.
There is no need for login (if changed in the Firebase console.firebase.google.com).
Here are the database rules:
{
"rules": {
".read": "true",
".write": "auth != null"
}
}
This should be OK for anyone with access to the app.
Yet, when I try to query an element, I get zero results (an empty array).
In short, the code is like this:
<firebase-app auth-domain="xyz.firebaseapp.com"
database-url="https://xyz.firebaseio.com/"
api-key="AIzaSyB7md4GqkXA-hsEF_CLU3ryHj-xxxxxxxxxx">
</firebase-app>
<firebase-document
path="/organizers/"
data="{{noteData}}">
</firebase-document>
{{noteData}}
<firebase-query
id="query"
path="/organizers/"
data="{{data}}">
</firebase-query>
{{data}}
</template>
<script>
Polymer({
is: 'my-app',
properties :{
data: {
type:Object,
observer: 'dataChanged'
}
},
dataChanged: function (newData, oldData){
console.log('new data: '+ newData);
console.log('old data: '+ oldData);
}
});
</script
There is data in the database.
I don't get why no data is being retrieved. I don't need the firebase-auth element, since I'm doing an anonymous access off the data, right?
I think that with your given code, your data is actually fetched.
You can remove the
<firebase-document>
and in your query add a reference to your firebase app object by specifying an app-name.
There isn't a lot of documentation about the app name but I think it functions as a namespace.
Furthermore, there is a problem with how you log the data. Try removing the "new data:" and "old data:" parts from your logging so that the browser dev tools can infer the datatype and display it correctly (as an object/array in your case).
As for your firebase-document, if you want to keep it, the data attribute is bound to "noteData" and not "data"

How to delete a large node in firebase

I have a Firebase child node with about 15,000,000 child objects with a total size of about 8 GB of data.
exampele data structure:
firebase.com/childNode/$pushKey
each $pushKey contains a small flat dictionary:
{a: 1.0, b: 2.0, c: 3.0}
I would like to delete this data as efficiently and easy as possible. How?
What i Tried:
My first try was a put request:
PUT firebase.com/childNode.json?auth=FIRE_SECRET
data-raw: null
response: {
"error": "Data requested exceeds the maximum size that can be accessed with a single request. Contact support#firebase.com for help."
}
So that didn't work, let's do a limit request:
PUT firebase.com/childNode.json?auth=FIRE_SECRET&orderBy="$key"&limitToFirst=100
data-raw: null
response: {
"error": "Querying related parameters not supported on this request type"
}
No luck so far :( What about writing a script that will get the first X number of keys and then create a patch request with each value set to null?
GET firebase.com/childNode.json?auth=FIRE_SECRET&shallow=true&orderBy="$key"&limitToLast=100
{
"error" : "Mixing 'shallow' and querying parameters is not supported"
}
It's really not going to be easy this one? I could remove the shallow requirement and get the keys, and finish the script. I was just hoping there would be a easier/more efficient way???
Another thing i tried were to create a node script that listen for childAdded and then directly tries to remove those children?
ref.authWithCustomToken(AUTH_TOKEN, function(error, authData) {
if (error) {console.log("Login Failed!", error)}
if (!error) {console.log("Login Succeeded!", authData)}
ref.child("childNode").on("child_added", function(snap) {
console.log(`found: ${snap.key()}`)
ref.child("childNode").child(snap.key()).remove( function(err) {
if (!err) {console.log(`deleted: ${snap.key()}`)}
})
})
})
This script actually hangs right now, but earlier I did receive somethings like a max stack limit warning from firebase. I know this is not a firebase problem, but I don't see any particular easy way to solve that problem.
Downloading a shallow tree, will download only the keys. So instead of asking the server to order and limit, you can download all keys.
Then you can order and limit it client-side, and send delete requests to Firebase in batches.
You can use this script for inspiration: https://gist.github.com/wilhuff/b78e7391396e09f6c614
Use firebase cli tool for this: firebase database:remove --project .
In Browser Console this is fastest way
database.ref('data').limitToFirst(10000).once('value', snap => {
var updates = {};
snap.forEach(snap => {
updates[snap.key] = null;
});
database.ref('data').update(updates);
});

How can i restrict access to my firebase so that only I - the owner can access it

I find my self very confused.
My task is very simple, i want to use Firebase with node.js so that only i will be able to access the base.
Usually services gives a sort of a key so that only the owner can login to the base.
Why isn't this possible? I don't need any authentication for users in my case, so i find the documentation very confusing since i don't need any authentication except for not allowing anyone else than me to access the base.
This is not supposed to be done via a 3rd party provider, this should be allowed directly from your service.
Please help.
Ok. so i managed to find the solution.
In you account you have the tab security rules which you should change to:
{
"rules": {
".read": false,
".write": false
}
}
Now go to the tab Secrets and you will find your auth key.
Now in the node.js code do:
var dataRef = new Firebase("https://<YOUR-FIREBASE>.firebaseio.com/");
// Log me in.
dataRef.auth(AUTH_TOKEN, function(error) {
if(error) {
console.log("Login Failed!", error);
} else {
console.log("Login Succeeded!");
}
});
This is confused me a little since they are talking about users, but i didn't think of my self (owner) as a user accessing the base.

Resources