Firebase Realtime Database stopped working - javascript

For the past month or so I have been developing an app with Firebase's Real-time Database. It has been working great until today. For some reason, the database querying stopped working entirely. The authentication (email and password login, create an account, forgot password) all seem to work fine but for some reason, my app cannot retrieve the Firebase data.
Keep in mind that it was working for a whole month and I have changed nothing.
I even went to previous builds of my app to test them out. They worked when tested and they also cannot connect to the database.
Has anybody ever faced this problem before and if so how did you manage to fix it?
This is my code by the way but it was working moments ago so I doubt anything is wrong with it.
var firebaseResponse = firebase.database().ref().orderByChild("country").equalTo(country)
fireBaseResponse.once('value').then(snapshot => {
snapshot.forEach(item => {
const temp = item.val();
data1.push(temp);
});

There was a Firebase service disruption started today at 12:20 (US/Pacific).
For more info you can track Firebase Status here

Weird timestamp rule in Firebase console
I faced a similar problem in one of my projects. It was loading data since yesterday but today it does not return anything.
I don't know how but this weird timestamp rule got added by default when I created the rule in my Firebase project.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.time < timestamp.date(2020,8, 22);
}
}
}
So I just removed the request.time < timestamp.date(2020,8, 22) rule and replaced it with this.
allow read, write: if true;
Note:
allow read, write: if true; make your database public for read/write request. Add some security rules.
Funny note:
I was pretty sure that the problem was with my service.json file. So I checked everything but the rules because firebase does not add timestamp rule by default. Maybe I copied the rule from somewhere.
How did I figure out this?
By luck and by logcat.
When I deep dived into logcat I found this warning message
[Firestore]: Listen for Query(deck_collection order by name) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}

Related

Creating A 'User Only' Section In A Firebase Site

I'm hoping to be able to create a section of a site that is unable to be read/seen by anyone that's not logged in... I am using Firebase and Javascript
I have read that you are unable to set permissions for files (.htmls ect) so i wont be able to block people from seeing the pages as a whole... Ive also read that this isn't the best practice anyway... So my question is...
What is the protocol for doing this sort of thing? And how can this be done in Firebase?
I have managed to create a user only page before from a tutorial, but this was just done by hiding the content of the page with Javascript and also blocking the permissions to the displayed data through Firestore permissions.
But I don't feel this is adequate for my site as I don't want people being able to read the code in the background or get access to the page at all to begin with.
I have also read that a way to go about doing this is to use Firebase Cloud Functions to check weather the user is logged in and if they are then it spits out the code for the pages from the google servers. Is this a good idea? Or is there a better way?
Any help, tips or insights would be greatly appreciated.
Just trying to get a feel for where to begin with this problem.
Hoping there is a solution.
Thanks
Yes, its a good practice hiding or preventing the UI to be rendered for unauthorize users.
Yes, its also a good practice setting the permissions accessing your data from the database.
You should also consider middleware, navigation guards or route guards for preventing unauthorized users to visit the restricted page. It would depend on the stack, or what frontend technology you are using. You can find whatever navigation guard you chosse. For vuejs there is vue-router. Also you can use firebase authState listener. Depends on your choice.
Use firebase auth to signInWithEmailAndPassword, or whatever your authentication method was. Then, you can check the auth state in onAuthStateChange, and set your new userId state:
// somewhere...
const [currentUserId, setCurrentUserId] = useState(null)
// later..
onAuthStateChanged(auth, (user) => {
if (user && user.uid) {
setUserId(user.uid)
}
});
// even later in this component:
return (<Layout userId={currentUserId} />);
// in wherever you have links, I assumed you passed currentUserId to here:
return (
currentUserId != null ? (Give content pls) : routeToLogin();
);
Something like this should be fine and secure enough. Noone is gonna go and flip a variable in your extremely obfuscated, transpiled javascript code generated by your bundler, and even if they did find a place to flip a variable, the code would probably throw an error anyway.
You could lazy load that certain page as well once authenticated, then the code for it it wouldn't even be loaded into the users disk until they've successfully signed in.

Basic Firebase Rules [duplicate]

This question already has answers here:
stop Firestore warning that everyone can read data
(1 answer)
Your Cloud Firestore database has insecure: any user can read your entire database
(2 answers)
Closed 2 years ago.
I am new to firebase, and am a bit stuck with the rules.
My app is essentially a blog-site.
It allows non-logged in to read posts, users, comments.
It also allows logged-in and verified users to create a post.
Here are my rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if request.auth.uid != null;
}
}
}
Firebase sends me emails that these are not secure due to "any user can read your entire database".
Is there something I am missing? As I want people to be able to read the data without being logged in?
I believe you're still getting that due to, based on the "if true" logic, any user has the ability to read anyone else's "stuff." What you could do is add some functions within the match database documents that return more tailored tests. You really want to avoid an open database in Firestore, so part of that is by design, in-terms of that e-mail you're getting. I went through this same issue myself, and ended up moving over to Mongo for that particular use case.
However, if you want to keep it open, you can turn off the alert emails from the console. Click on Firebase alerts in the top-right, click settings (gear), select your project, just choose which you want to receive. I know those alerts can get annoying, haha, but it's Google's way of trying to help :) good luck!
Firebase prefers that you call out each collection individually in your security rules to allow access, rather than use a wildcard to match everything. They have no way of knowing if you actually have some private data in a collection and are accidentally giving access to it. By specifying rules for each collection separately, you are being very clear and specific about the access for each one of them.

Adding a document in Firestore from web app is not working and not returning an error

Suddenly my code for adding new documents to Firestore is not working and not returning an error. I thought perhaps it was a network issue but Authentication and creating new users is working fine. My network connection is also quite solid.
[EDIT] I've switched on debug mode and a call to Firestore is made with a documentChange request and the correct data fields. The document is never created though. I am on the latest Firestore release.
I tried this simplified add to my collection:
firebase.firestore().collection('biff').add({
boff: 0,
baff: 5
}).catch(function(error) {
console.error('There was an error uploading a file to Cloud Storage:', error);
});
Here are my security rules: (I also tried completely public writing)
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
There are no error messages generated and the new document never appears in my collection. I can authenticate and create new users. Is it possible that authentication is live but somehow my firebase SDK thinks that there is no connection to firestore so its queueing up the documnent writes?
[UPDATE] I noticed that an earlier alpha version of my frontend was still able to write new documents. When I listed the projects firebase knew about in the CLI it listed an older firebase project. So I did 'firebase use --add' and chose my new firebase project and then did a 'firebase init' to reset everything except my index.html. I then did a 'firebase deploy' and lo and behold my deployed version is able to write new documents. My localhost version still is not able to write them though. So very odd. So I am half way there with a solution. All ideas welcome on whats happening on my local machine to stop writes still ...
Once I used a button instead of a form submit to trigger the routine with the document.add then it all worked from localhost, server and mobile. In the broken version the form would continue processing and leave the user in the main view in a state where that url and all urls afterwards had a parameter (?topic=Business) appended to them. From then on the document.add would no longer work. By moving to a button and using e.preventDefault it now works every time and all the urls remain clear. (no idea why this side effect wedged firestore add)
var postOfferElement = document.getElementById('postoffer');
postOfferElement.addEventListener('click', function(e) {
e.preventDefault();
saveOffer();
});
In saveOffer:
firebase.firestore().collection('offers').add({
created: firebase.firestore.FieldValue.serverTimestamp(),
owner: getUserID(),
name: getUserName(),
pic: getProfilePicUrl(),
completes: 0,
favs: 0,
offer: offerText,
topic: topicText,
exp: expText
});

How can I Choose Specifc Users to Log Into my Javascript SPA in Azure AD?

I'm using a Javascript SPA to return a query from Microsoft Graph through the Azure AD application, and it works just fine!
The problem is when I try to loggout from the application, it says I was successfully logged out but if try to log in with another user, it logs into the previous one, in this case, me, without even asking for password.
I needed that this application could log in just few people in my organization, but anyone with "#example.com" can access my application, without the need to be signed to it or not.
I've already cleared the browser's cache and cookies and it doesn't work. Already configured the app to store the cache in the session but it also failed.
The code I'm using is available in:
https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-javascript-spa
The only differences are that I'm using another querys instead the "https://graph.microsoft.com/v1.0/me" and the permissions needed to get them.
I just needed a way to choose specific people to log into the application instead of all the organization and to fix this logout problem.
If I understood you well, I believe your solution is the option select_account.
Here is a code snippet to illustrate:
const clientApplication = new Msal.UserAgentApplication(config);
const loginRequest = {
scopes: [config.webApiScope],
prompt: "select_account",
}
clientApplication.loginPopup(loginRequest).then(function (loginResponse) {
//your code
});

firebase database connection error handling

Does anyone know whether there is a way to properly check for errors in the initial connection with the Firebase database? This is my example code
const database = firebase
.initializeApp({ databaseURL: FIREBASE_URL })
.database();
and in order to test that my error handling was correct I tried deleting a character from the URL, but this just prints the following to the console:
FIREBASE WARNING: Firebase error. Please ensure that you spelled the name of your Firebase correctly (FIREBASE_URL)
I looked thoroughly through the documentation, the most relevant page I could find is this one, but even trying to use the enableLogging method and trying to regex whether it's a warning / error seems too flimsy because the above warning isn't even part of that logging.
If there was even just an attribute I could access to check whether the database is online that'd be great, or at best an error callback or something of the like.
Thank you for your time!

Categories