how do I wait for a response from FireBase Kotlin Android Studio - firebase

Screenshot-1
Screenshot-2
I am trying to check in the database whether there is a user with such a login or not. If it exists, then display an error.How can I get a response from the database before I create a user

That's not an efficient way of handling authentication. The best option that you have in my opinion, would be to implement Firebase Authentication. Once you do that, you can simply check if the user is authenticated or not. How? By simply checking if the FirebaseUser object is null or not. Please also note that this operation is not asynchronous.
If you however need to get something from the Realtime Database, then please note that that is indeed an asynchronous operation. Since you're using Kotlin, the following article will help for sure:
How to read data from Firebase Realtime Database using get()?
Edit:
If you want to check if a user already exists, then please check my answer from the following post:
Checking if a particular value exists in the Firebase database
Besides that, never store credentials in plain text. I highly recommend you implement Firebase Authentication so you can secure your database using Firebase Security Rules. If you want to keep your own authentication mechanism, please see the official document regarding that:
https://firebase.google.com/docs/auth/android/custom-auth

Related

Flutter - Understanding Firebase Admin and how to get a user's information from email/uid/name

I'm making a little Snapchat clone, and a part of this app I'm trying to build is the ability to add a friend and start a conversation with them. I'm using Firebase to manage my users and I'm a little stuck now trying to figure out what works and why I'm getting problems trying to use some methods or functions.
What I want is this simple line of code to work:
var userByEmail = await _admin.app().auth().getUserByEmail("b#gmail.com");
print(userByEmail.toString());
However this has been giving my some problems, most recently, the following error message:
Unhandled Exception: FirebaseAuthError(auth/invalid-credential): Must initialize app with a cert credential or set your Firebase project ID as the GOOGLE_CLOUD_PROJECT environment variable to call verifyIdToken().
Getting to this point made me want to first ask a question about FirebaseAdmin and Auth before continuing and potentially screwing up my app settings.
Is there a simple way to do what I'm trying to do?
I have a Firebase.instance.initializeApp() in my Main function, do I only ever call that once or should I start initilizeApp in the initState of each Stateful Widget where needed?
What does this error message actually mean?
You are trying to use the Firebase Admin SDK in your Flutter code, which is not possible. The Admin SDKs give full administrative access to your Firebase project, which would be a serious security concern if you allow that in your Flutter app.
If you want to allow certain administrative functionality in your application, you will have to make that functionality available yourself. For example, to look up a user by their email address, there are two common approaches:
Store the minimal information about each user in a cloud-accessible database (such as Firebase's Realtime Database or Cloud Firestore) when each user registers with your app, and then look it up from there.
Wrap the getUserByEmail from the Admin SDK in a custom API that you make for yourself, on a server you control or in Cloud Functions. In that API you validate that the user making the call is authorized to do so, then call Firebase through the API you were trying to use, and return the minimal result back to the caller.
Both of these are feasible and can work to solve a variety of use-cases. But if you've never built backend code before, you might find the first approach easier to get started with.
Also see:
How to get Firebase UID knowing email user?
Flutter get User Data from Firebase
The right way to do what you want is using Firebase auth, authenticating your user and using a collection to store and retrieve users information. That auth information provided by firebase should only be used for authentication and security purposes.
The Firebase admin must have a user logged in to work properly, but its purpose is to provide a more administration environment and should not be used inside a clients app, unless its an admin app.
With all that said, lets go for the rescue:
Authenticate your user (using firebase auth);
After auth, save all the user information you want to share with other user inside its own collection (you will need to create one);
When an authenticated user (this is important) 'request any other users data, you query for the data in the previous created collection.

Firebase functions: Custom auth endpoint

I want to login using custom auth endpoint in firebase admin.
For example using email and password.
http://firebasefunctionsaddres.com/loginUsingEmail
So from client I want to make request with email and password(and maybe some other info) and on firebase functions side (maybe save some data to firestore) and response with auth token.
Is it possible?
I personally didn't use the auth token, because I found an easier approach by using Firestore and just storing the user information there. It is a very simple database to use. No queries, it works just like a JavaScript Object!! And encrypt/hash the password of the user by using something like MD5, or SHA 256 before storing it!!
Here is a link to the JavaScript Firestore Documentation that'll teach you to store and retrieve data (it works super fast): Firestore JavaScript Docs
Also in this way, you have to load less Firebase Resources and all user data is stored in one place! I really like the simplicity of Google Firestore! (In my opinion, soooo much better than PHP and MySQL!)

Hashing algorithm support in firebase real-time database security rules

I would like to compute hash functions inside security rules.
md5hash(auth.token.email) === $hashedvalue
Is there a way for me to do that in bolt? or natively in firebase real-time database?
Use Case:
Basically I would like to store the email as the key in the firebase real-time database and use it in the firebase security rules for authentication and authorization. Since few special characters like dots (.) are not supported in keys I was thinking of using some hashing algorithm which is available in firebase real-time database.
auth.id doesn't work in my case as I'm not giving any sign up option as I have a pre defined set of users with pre-defined profile details accessing my application through their Google login (which I know the email ID of) to start with and since they haven't yet logged into my application I don't have a corresponding ID to authenticate or authorize them on their first attempt.
This page of documentation shows all the functions available in Realtime Database security rules. There are no hashing functions there. You could file a feature request to explain you use case.
For the sake of posterity, I got this working with a small workaround (Yay!).
From the fire firebase real-time database documentation I found out that firebase security rules supports an amazing string function called "replace" xD.
So now I pre process the email Ids by replacing all the characters not supported as database key with their url encoding equivalent before creating the key and use the same set of replacements in my firebase security rules.

Firebase's version of SQL Injection

Using firebase for the first time after a strong background of SQL. I'm used to using functions like addslashes() to sanitize user input into queries.
Is there any standard way of doing the similar thing with Firebase lookups?
For example:
// expected a key, not a path
var userProvidedKey = "3/malicious"
// will not be a ref to what I expect
var ref = firebase.database().ref(`something/${userProvidedKey}`)
I don't know how malicious it can be for a user to be able to search further down in a ref, but maybe this problem is solved? Or do I need to .split('/').shift() any inputs that I receive?
Note: Using the JS SDK for my examples.
Input/output should always be sanitized and validated before entering the database.
Firebase provides security and data validation checks to be used in your application. Firebase also provides rules in its database to determine which users have write/read access to which data in the database.
For more information read the documentation about the Firebase realtime database.
Found this thread Adding Firebase data, dots and forward slashes that may answer some practical questions on Firebase specific sanitation.

Can somebody get Firebase credentials from my apk and use them?

Can somebody else get the Firebase credentials from my APK and use them? Is this prevented by adding the SHA-1 keys for Android?
If it is prevented, what do I need security rules for since only code from my app with my SHA-1 can manipulate database at all?
If it is not prevented, can somebody else use my Firebase database as long as his requests fit the security rules? (Write 2nd client, which actually cannot do bad things but should not be allowed at all.)
Im not sure how I should think about security rules:
A) Protecting data against access and manipulation from bad guys + B?
B) Just a set of rules to keep data in a certain state and prevent my software from doing invalid database request?
A Firebase Database can be accessed via the REST API, or any of the client libraries. The decision about whether a client can or can't do something is entirely based on the rules.
You can even just access the Database URL in a web browser and see a JSON response by putting .json on the end, e.g. https://[YOUR_PROJECT_ID].firebaseio.com/.json
So the answer is definitely B! The default rules in a new Firebase project are that read and write to the database require auth, but you can configure them to provide whatever levels of protection you need.
Take a look at the Database Rules quickstart to see what you can do!
We don't ship the Realtime Database secret (or any other "secret" material) in the json file that gets baked into your app. That file simply contains resource identifiers that allow us to know which resources (database, storage bucket, analytics, etc.) to properly authenticate to (we use Firebase Authentication for these purposes), and we handle server side authorization to ensure that users are properly logged in.
If you are authorizing your requests properly (using Firebase Realtime Database Rules, for instance), your data is secure!
I'd recommend watching The Key to Firebase Security, one of our I/O talks, which talks in greater detail about how this works.
firebaser here
Thanks to the new feature called Firebase App Check, it is now actually possible to limit calls to your Realtime Database to only those coming from iOS, Android and Web apps that are registered in your Firebase project.
You'll typically want to combine this with the user authentication based security that Mike and Ian describe in their answers, so that you have another shield against abusive users that do use your app.

Resources