Firebase firestore not working react native - javascript

I have a react native project configured with firebase and the firestore db is not working. It doesnt show any errors either.
Here is my firebase config file:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth'
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
databaseURL: "",
};
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig);
app.firestore().settings({ experimentalForceLongPolling: true });
} else {
app = firebase.app();
app.firestore().settings({ experimentalForceLongPolling: true });
}
const db = app.firestore();
const auth = app.auth();
export {db, auth }
Here is my code that i use to authenticate user than save it to firestore:
const signup = dispatch => async (email, password) => {
try {
await auth.createUserWithEmailAndPassword(email, password).then(async resp => {
});
await db.collection('users').add({
email: 'asdas',
uid: 'asdsda',
coins: 0,
}).catch(error => {
console.log(error);
});
} catch (error) {
console.log(error);
alert(error.message);
}
};
Firestore rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read,write: if
request.time < timestamp.date(2022, 9, 21);
}
}
}
The authentication part works perfectly but the firestore code doesnt execute. Any idea why this is happening?

Related

Cannot register user info to firebase database when creating a new user

I am working on a signup form and I can create a new user using firebase auth, but the part where I register informations like the name, email... in a database is not working.
On the firebase side, I created a firestore database and a realtime database, and I don't see anything on them.
I tried to use the firebase documentation but it's still not working so I am probably missing something.
Thanks for your help!
PS: I hidded my firebase config here but it's filled on my code
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js'
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js'
import { getFirestore, doc, getDoc, getDocs, collection } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const app = initializeApp(firebaseConfig);
//const db = getFirestore();
const auth = getAuth();
const db = getDatabase();
submitData.addEventListener('click', (e) => {
e.preventDefault()
var name = document.getElementById('full_name').value
var email = document.getElementById('email').value;
var password = document.getElementById('psw').value;
// do verification
// Move on with Auth
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user
alert("user created")
//add to firebase database
function writeUserData( name, email) {
set(ref(db, 'users/' + userId), {
username: name,
email: email,
});
}
})

Why am I unable to sign in anonymously as an authenticated user in firebase?

I am trying to login as an authenticated user anonymously. Here is my code:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import { getAuth, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-auth.js";
const firebaseConfig = {
apiKey: "key_here",
authDomain: "project.firebaseapp.com",
projectId: "project",
storageBucket: "project.appspot.com",
messagingSenderId: "id_here",
databaseURL: "https://project-default-rtdb.firebaseio.com",
appId: "app_id_here"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
document.getElementById("login").addEventListener("click",function(event){
event.preventDefault();
onAuthStateChanged(auth, (user) => {
if(user){
//user can successfully login
}
else{
console.log("Something went wrong");
}
}, (error) => console.error(error)) //Nothing prints here
}
I was able to successfully log in 'til yesterday. But since this morning I keep getting the error Something went wrong in my console.
I didn't change anything in the code, nor in my firebase credentials. Where am I going wrong?
It was so silly of me to not read the documentation page carefully, I had forgotten to execute the signInAnonymously() method before checking for the user's data, the complete code is as follows:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import { getAuth, onAuthStateChanged, signInAnonymously } from "https://www.gstatic.com/firebasejs/9.14.0/firebase-auth.js";
const firebaseConfig = {
apiKey: "key_here",
authDomain: "project.firebaseapp.com",
projectId: "project",
storageBucket: "project.appspot.com",
messagingSenderId: "id_here",
databaseURL: "https://project-default-rtdb.firebaseio.com",
appId: "app_id_here"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
document.getElementById("login").addEventListener("click",function(event){
event.preventDefault();
signInAnonymously(auth)
.then(() => {
onAuthStateChanged(auth, (user) => {
if(user){
//user can successfully login
}
else{
console.log("Something went wrong");
}
});
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorCode+": "+errorMessage);
});
});

Firebase upload "user does not have permission", rules are set up correctly

I'm working on my first ReactJS project and I'm trying to upload image to firebase but whenever I try to upload I get notification in the browser "Firebase Storage: User does not have permission to access 'images/${image.name}'. (storage/unauthorized)" however, I'm logged in using firebase authenticaion. Any help will be appreciated
My firebase settings are
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
function to upload
const handleUpload = () => {
const uploadTask = storage.ref(`images/${image.name}`).put(image);
uploadTask.on(
"state_changed",
(snapshot) => {
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes * 100)
);
setProgress(progress);
},
(error) => {
console.log(error);
alert(error.message);
},
() => {
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then(url => {
db.collection("posts").add({
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
caption: caption,
imageUrl: url,
username: username
});
setProgress(0);
setCaption("")
setImage(null);
})
}
)
}
This is my firebase function
import firebase from 'firebase/compat';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/compat/storage';
const firebaseConfig = { // Have the firebase config here
apiKey: "XXXXXX",
authDomain: "XXXX",
databaseURL: "XXXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "1:XX:X"
};
// Use this to initialize the firebase App
const firebaseApp = firebase.initializeApp(firebaseConfig);
// Use these for db & auth
const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage();
export { auth, db, storage };
The rules you posted above are cloud firestore rules. Not firebase storage rules.
Your firebase storage rules should look like this:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
This would permit only authenticated access.
To view firebase storage rules: Storage -> Rules.

How to setup Firebase Cloud Messaging v9 in React?

I'm having trouble setting up my firebase environment in React.
I'm going through the firebase documentation, but I can't seem to get the first step of getting permission correct.
I tried looking everywhere to fix these errors, but all attempts failed. Please help!
Errors:
Service worker registration failed, error: TypeError: Failed to register a ServiceWorker for scope ('http://localhost:8080/') with script ('http://localhost:8080/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script.
An error occurred while retrieving token. FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:8080/firebase-cloud-messaging-push-scope') with script ('http://localhost:8080/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).
Code:
src/index.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('../firebase-messaging-sw.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
}).catch(function(err) {
console.log('Service worker registration failed, error:', err);
});
}
src/firebase.js
import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";
const firebaseApp = initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
});
const messaging = getMessaging(firebaseApp);
export const fetchToken = async (setToken) => {
await getToken(messaging, { vapidKey: KEY_PAIR }).then((currentToken) => {
if (currentToken) {
setToken(currentToken)
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
}
public/firebase-messaging-sw.js
import { initializeApp } from "firebase/app";
import { getMessaging, onBackgroundMessage } from "firebase/messaging/sw";
const firebaseApp = initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
});
const messaging = getMessaging(firebaseApp);
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: ''
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
so I did this a few months ago and it worked for me, it should for you as well...
First you need to register de service worker to ger this running so in your index.js you can do the following:
// IMPORTS...
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("../firebase-messaging-sw.js")
.then(function (registration) {
console.log("Registration successful, scope is:", registration.scope);
})
.catch(function (err) {
console.log("Service worker registration failed, error:", err);
});
}
const dashboard = (
<Provider store={MyStore}>
<PersistGate loading={null} persistor={persistor}>
<BrowserRouter>
<App />
</BrowserRouter>
</PersistGate>
</Provider>
);
ReactDOM.render(dashboard, document.getElementById("root"));
reportWebVitals();
Then the sw firebase register looks like this:
importScripts("https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js");
firebase.initializeApp({
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
});
const isSupported = firebase.messaging.isSupported();
if (isSupported) {
const messaging = firebase.messaging();
messaging.onBackgroundMessage(({ notification: { title, body, image } }) => {
self.registration.showNotification(title, {
body,
icon: image || "/assets/icons/icon-72x72.png",
});
});
}
It is important to have a config file for firebase: firebase.js
import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSENGER_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID,
};
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
export { firebaseApp };
export const fetchToken = async (setToken) => {
await getToken(messaging, {
vapidKey: "KEY",
})
.then((currentToken) => {
if (currentToken) {
// setToken(currentToken);
console.log("currentToken: ", currentToken);
} else {
console.log("No registration token available. Request permission to generate one.");
}
})
.catch((err) => {
console.log("An error occurred while retrieving token. ", err);
});
};
After these files configures you can call the fetchToken function from a useEffect inside your main file/navigator/etc and then you can use the onMessage hook/function from firebase/messaging itself

Quasar 2.2.2, Vue 3 and Firebase: how to access GlobalProperties from router

I'm implementing for the first time Firebase in my Quasar App (with Vue 3). I've created the boot file firebase.js and this is its content:
import { boot } from 'quasar/wrappers'
import { initializeApp } from 'firebase/app';
import { getAnalytics } from "firebase/analytics";
// "async" is optional;
// more info on params: https://v2.quasar.dev/quasar-cli/boot-files
const firebaseConfig = {
apiKey: 'XXX',
authDomain: 'XXX',
projectId: 'XXX',
storageBucket: 'XXX',
messagingSenderId: 'XXX',
appId: 'XXX',
measurementId: 'XXX'
};
const firebaseApp = initializeApp(firebaseConfig);
const analyticsApp = getAnalytics(firebaseApp);
firebaseApp.getCurrentUser = () => {
return new Promise((resolve, reject) => {
const unsubscribe = firebaseApp.auth().onAuthStateChanged(user => {
unsubscribe();
resolve(user);
}, reject);
})
};
export default boot(({ app }) => {
app.config.globalProperties.$firebase = firebaseApp;
app.config.globalProperties.$analytics = analyticsApp;
})
The initialization seems to work fine. Now I must add a function to my index.ts located into router dirctory which allow me to redirect to a specific page when the user is not authenticated.
Router.beforeEach(async (to, from, next) => {
const auth = to.meta.requiresAuth
if (auth && !await $firebase.getCurrentUser()) {
next('/');
} else {
next();
}
})
$firebase must reference the globalproperties item. But whatever I've changed I'm unable to access the property.
Can you help me?
Roberto
Looking carefully into Quasar documentation I've made all the changes in the firebase.js file which now is like this.
/* eslint-disable */
import { boot } from 'quasar/wrappers'
import { initializeApp } from 'firebase/app';
import { getAnalytics } from "firebase/analytics";
const firebaseConfig = {
apiKey: 'XXX',
authDomain: 'XXX',
projectId: 'XXX',
storageBucket: 'XXX',
messagingSenderId: 'XXX',
appId: 'XXX',
measurementId: 'XXX'
};
const firebase = initializeApp(firebaseConfig);
const analytics = getAnalytics(firebase);
firebase.getCurrentUser = () => {
return new Promise((resolve, reject) => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
unsubscribe();
resolve(user);
}, reject);
})
};
export default boot(({ app, router, store }) => {
app.config.globalProperties.$firebase = firebase;
app.config.globalProperties.$analytics = analytics;
router.beforeEach(async (to, from, next) => {
const auth = to.meta.requiresAuth
if (auth && !await firebase.getCurrentUser()) {
next('/');
} else {
next();
}
})
})
export { firebase, analytics };
Essentially I've changed the export boot clause adding router and store in it and I've added router.beforeEach in the clause.
I've made a debug session and the function is called everytime a route change occurs.
Roberto

Categories

Resources