Getting 'permission-denied' while integrating firebase in React web app - javascript

I'm trying to save a documents through react web app, but facing the following issue. I have read the firebase rules documentation.
Here is the code
constructor(props)
{
super(props);
var config = {
apiKey: "<apiKey>",
authDomain: "<authDomain>",
databaseURL: "<databaseURL>",
projectId: "<projectId>",
storageBucket: "",
messagingSenderId: "<messagingSenderId>"
};
firebase.initializeApp(config);
}
and we are triggering button click
onKeyUp(e)
{
if(e.keyCode===13 && trim(e.target.value) !== '')
{
e.preventDefault();
let dbCon=this.props.db.database().ref('/messages');
dbCon.push(
{
message:trim(e.target.value)
}
);
);
}
}
Database rules:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write:if true;
}
}
}
we are facing this issue. What am I doing wrong?
Stack Trace:
Uncaught (in promise) Error: PERMISSION_DENIED: Permission denied
at index.cjs.js:13076
at exceptionGuard (index.cjs.js:690)
at Repo../node_modules/#firebase/database/dist/index.cjs.js.Repo.callOnCompleteCallback (index.cjs.js:13067)
at index.cjs.js:12844
at index.cjs.js:12019
at PersistentConnection../node_modules/#firebase/database/dist/index.cjs.js.PersistentConnection.onDataMessage_ (index.cjs.js:12052)
at Connection../node_modules/#firebase/database/dist/index.cjs.js.Connection.onDataMessage_ (index.cjs.js:11337)
at Connection../node_modules/#firebase/database/dist/index.cjs.js.Connection.onPrimaryMessageReceived_ (index.cjs.js:11331)
at WebSocketConnection.onMessage (index.cjs.js:11232)
at WebSocketConnection../node_modules/#firebase/database/dist/index.cjs.js.WebSocketConnection.appendFrame_ (index.cjs.js:10837)
at WebSocketConnection../node_modules/#firebase/database/dist/index.cjs.js.WebSocketConnection.handleIncomingFrame (index.cjs.js:10887)
at WebSocket.mySock.onmessage (index.cjs.js:10784)

Newbie mistake, was using the newer firestore database instead of using the Realtime database. Changing to the Realtime database fixed the issue.

Related

How to add header value for firebase realtime database js file?

I am having an issue with my site regarding Firebase Realtime Database and Cross Origin Resource Policy. My site already has The Cross Origin Resource Policy header configured and is being served on every asset in my site (js, css, html, etc). But now the js script from firebase.io is being blocked because it doesn't have this header.
I would like to ask, how do I add these headers? Where in the Firebase console should I go to?
Here is the piece of code where the issue is triggered. Basically I initialize the Server object then call changeDb, then call checkAuthor (Where the issue occurs):
window.Server = function () {
const config = {
apiKey: FirebaseApiKey,
authDomain: FirebaseAuthDomain,
projectId: FirebaseProjectId,
storageBucket: FirebaseStorageBucket,
messagingSenderId: FirebaseMessagingSenderId,
appId: FirebaseAppId,
databaseURL: FirebaseDatabaseUrl
};
firebase.initializeApp(config);
};
Server.prototype.changeDb = function (prefix) {
this.annotationsRef = firebase.database().ref().child(prefix + '/annotations');
this.authorsRef = firebase.database().ref().child(prefix + '/authors');
}
Server.prototype.checkAuthor = function (authorId, openReturningAuthorPopup, openNewAuthorPopup) {
this.authorsRef.once('value', authors => { //<== Here is where it is triggered
if (authors.hasChild(authorId)) {
this.authorsRef.child(authorId).once('value', author => {
openReturningAuthorPopup(author.val().authorName);
});
} else {
openNewAuthorPopup();
}
});
};

Firebase anonymous auth data has reset, when using safari in iOS and reload immediately in Nuxt.js

I made a simple code like following in Nuxt.js.
<template>
<div>
uid:{{ user.uid }}
</div>
</template>
<script>
import firebase from "firebase";
export default {
data() {
return {
user: {}
};
},
mounted: function() {
this.initFirebase();
},
methods: {
initFirebase: function() {
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID
});
}
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.user = user
console.log("authed");
} else {
console.log("authing");
firebase.auth().signInAnonymously()
}
});
},
}
};
</script>
I expect this code will auth only one time, and UID will never change in later visit.
It works almost perfect, but combination in iOS and Safari, the UID will change when I visit this page and reload immediately after UID displayed.
I cleared the safari's cache and tried it several times, and notice that this doesn't happen if I wait 10 or 20 seconds. And if UID once changed, it will never change.
I never seen this in Android or any other browser in iOS like chrome for example.
I want these to behave same.
Please let me know if you have any good ideas.

Firebase is already defined in the global scope. Please make sure Firebase library is only loaded once

I am getting this alert 2 times in the console, I check the network and when loading the home, it registers two identical events, indicated in the image, the only difference between one and the other is the versions, which one is 6.6.1 that It is the one I currently have, and 7.15.4 (Which I do not have installed in my project, nor do I have any configuration with it, I looked for it in the whole project, and it is neither in package.json nor in the lock.json, absolutely nothing about that version, I want you to stop showing me that warning and not that.
The only settings that I have that call the firebase are this file
importScripts('https://www.gstatic.com/firebasejs/6.6.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.6.1/firebase-messaging.js');
firebase.initializeApp({
messagingSenderId: "xxxxxxxxxxx"
});
const messaging = firebase.messaging();
console.log('Handling background message')
messaging.setBackgroundMessageHandler(function(payload) {
console.log('Handling background message ', payload);
return self.registration.showNotification(payload.data.title, {
body: payload.data.body,
icon: payload.data.icon,
data: {
click: payload.data.click,
userId: payload.data.userId,
pushId: payload.data.pushId,
}
});
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(self.clients.openWindow(event.notification.data.click));
})
And this one, which is in the index.html
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-messaging.js"></script>
<script>
try {
window
.firebase
.initializeApp({
apiKey: "%REACT_APP_FIREBASE_ANALYTICS_API_KEY%",
authDomain: "%REACT_APP_FIREBASE_ANALYTICS_AUTH_DOMAIN%",
databaseURL: "%REACT_APP_FIREBASE_ANALYTICS_DATABASE_URL%",
projectId: "%REACT_APP_FIREBASE_ANALYTICS_PROJECT_ID%",
storageBucket: "%REACT_APP_FIREBASE_ANALYTICS_STORAGE_BUCKER%",
messagingSenderId: "%REACT_APP_FIREBASE_ANALYTICS_MESSAGING_SENDER_ID%",
appId: "%REACT_APP_FIREBASE_ANALYTICS_APP_ID%",
measurementId: "%REACT_APP_FIREBASE_ANALYTICS_MEASUREMENT_ID%"
})
} catch (e) {
console.error(e)
}
</script>
I'm not completely sure of how you are loading your files, but if they are independent of each other, both
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-app.js"></script>
and
importScripts('https://www.gstatic.com/firebasejs/6.6.1/firebase-app.js');
are fetching firebase. You should only keep one if both files are being used.

TypeError: firebase.firestore () is not a function web javascript

I am trying to upload an image on firebase cloud storage with web javascript. I am getting "firebase.firestore () is not a function" on my console. Am I going any wrong way?
I have done insert and fetch data on firebase database. But I have to stop for upload image on firebase cloud storage.
<script src="https://www.gstatic.com/firebasejs/6.2.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.2.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.3.0/firebase-firestore.js"></script>
var firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
databaseURL: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX"
};
// Initialize Firebase
var defaultProject = firebase.initializeApp (firebaseConfig);
// Get a reference to the database service
var fileName = selectedFile.name;
var storageRef = firebase.firestore ().ref ('image' + fileName).put (selectedFile);
updating node on the computer seemed to have fixed the issue. I updated it to v16.15.1
change
firebase.firestore ().ref ('image' + fileName).put (selectedFile);
to
firebase.storage().ref('image' + fileName).put (selectedFile);

Getting an Error on console while saving data in firebase firestore

here is my Javascript code. its simply copy from the firebase Docs
<script src="https://www.gstatic.com/firebasejs/5.4.2/firebase.js"/></script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-firestore.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: ".",
authDomain: ".",
databaseURL: ".",
projectId: ".",
storageBucket: ".",
messagingSenderId: ".[enter image description here][1]"
};
firebase.initializeApp(config);
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
function submitCountry(){
console.log('in funtion');
db.collection("cities").doc("asdasLA").set({
name: "Los Angeles",
state: "CasdasA",
stasdaate: "CasdasdasA",
stasaasddaate: "CAasd",
country: "USA"
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
</script>
when i refresh my page it show the uncaught error.
{code: "app/duplicate-service", message: "Firebase: Firebase service
named 'firestore' already registered (app/duplicate-service).", name:
"firestore", stack: "firestore: Firebase: Firebase service named
'fires…m/firebasejs/5.3.0/firebase-firestore.js:1:326255"} firebase #
index.esm.js:17591 (anonymous) # index.esm.js:41 index.esm.js:17591
Uncaught Error: Cannot instantiate firebase-firestore - be sure to
load firebase-app.js first.
after clicking my save button it shows the error mention below.
when i use the same code on simple project without any JS or Bootstrap it works fine but same code i placed in My real project with Bootstrap it shows errors
[Intervention] Slow network is detected. See for more details.
Fallback font will be used while loading:
By doing
<script src="https://www.gstatic.com/firebasejs/5.4.2/firebase.js"/></script>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-firestore.js"></script>
you load the 'firestore' Firebase service twice, see the doc: https://firebase.google.com/docs/web/setup
You should either do
<script src="https://www.gstatic.com/firebasejs/5.4.2/firebase.js"></script>
or
<!-- Firebase App is always required and must be first -->
<script src="https://www.gstatic.com/firebasejs/5.4.2/firebase-app.js"></script>
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.4.2/firebase-firestore.js"></script>
Also note that in your code you have mixed versions (i.e. 5.4.2 and 5.3.0). Most probably something to avoid.
Following your comment below, in order to check that it writes correctly to the db, modify you code as follows and just open the HTML page (the set() method will be triggered automatically)
<script src="https://www.gstatic.com/firebasejs/5.4.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.4.2/firebase-firestore.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: ".",
authDomain: ".",
databaseURL: ".",
projectId: ".",
storageBucket: ".",
messagingSenderId: ".[enter image description here][1]"
};
firebase.initializeApp(config);
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
db.collection("cities").doc("asdasLA").set({
name: "Los Angeles",
state: "CasdasA",
stasdaate: "CasdasdasA",
stasaasddaate: "CAasd",
country: "USA"
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
</script>

Categories