Hello friends, and welcome to Obsidian Soft,
Today, I will show you the real power of Firebase using their authentication with their Realtime Database. We will develop a small example of Firebase authentication using email and password, where users can add or view their own notes, but after securely logging in to the app. Firebase authentication also has Google sign up and sign in, but that process is a little complicated and lengthy, so I will cover Google sign up in a later tutorial.
This is the demo of the app at work. I can sign up using any email account. It is so much easier to remember your emails as compared to user names, and everyone has at least one email address. So, you enter an email and provide a password. I will log in as I have already signed up with this account. And you are taken to your notes screen where only your notes are loaded. Let’s go back and try signing up. I will use a different email address and password. And now a new user will be created in the system against this email and this time the notes screen doesn’t have anything as I am a different user now.
So, let’s begin:
First, we need to create our project in Firebase, in which we will have authentication and a realtime database.
Open up the Firebase console: https://console.firebase.google.com/
Create a new project, e.g., NotesProject, and go with the default settings.
Click on Authentication on the left side. If you don’t see it, then click on the build tab on the left side.

Click on Get started button. Choose email/password.

It will take you to another page. Enable only Email/Password sign-in here.

Now, we also need a database in this project, so click on Realtime Database on the left again under the build tab.

Then, click on ‘Create Database’ button and choose the location nearest to you. For example, I chose Singapore. And then start the database in locked mode. Now, you can see the difference. For the Firebase DB component in our earlier tutorials, we started in test mode, and we kept the project in that mode, which was unsafe, as anyone could see our data if they had the link. Locked mode means no one can read/write to our database. After the database is created, you will see the reference URL to your database.
Copy it by clicking on that chain icon and paste it into Notepad or some other text editor.

Now, click on the rules tab. Right now, read and write are both locked. Remove the rules and paste this in its place:
{
"rules": {
"users": {
"$uid": {
".read": "auth != null && auth.uid === $uid",
".write": "auth != null && auth.uid === $uid"
}
}
}
}
and don’t forget to click on the Publish button.

🔍 What do these rules mean?
These are Firebase Realtime Database Security Rules.
Only a logged-in user (auth != null) can access data, and a user can see his or her own data and not anyone else’s (auth.uid === $uid).
We also need the API key for our project. The process was easier before but recently they have changed it but no worries as I have got you covered.
Click on Project Overview on the left.

Now, click on Add App.

Choose Web app (the round button with </> on it)

Give some name to your web app and click on Register app button.

After a few seconds, some details will show up. Copy the apiKey. This is your Web API key.

Paste it where you also pasted the URL for the Firebase Realtime Database. Keep your Web API key secure. Don’t use my API key as it will not work; I have already deleted this project.
Let’s head to MIT App Inventor to make our very awesome notes in the cloud app. Unfortunately, with this project, we cannot use the built-in Firebase DB component, and we will need to post our requests to the Firebase Realtime Database using the web component but don’t worry, I will go slow and explain each step and we have used the web component many times before too when connecting with different APIs.
A simple screen here with align horizontal and align vertical properties both centered. A text box from the UserInterface palette for email. Rename to emailTxt. Make font bold, font size 18, and change hint to Enter email. Add a password textbox below. Make font bold, font size 18, and change hint to Enter password.
A button for sign up. Rename to signupBtn. Duplicate by selecting it and pressing Ctrl + C and Ctrl + V on the keyboard for Windows or Command + C and Command + V for macOS. Rename to loginBtn and change text to “Log In”. Add a notifier from the User Interface palette for error messages and a web component from the Connectivity palette for talking to the Firebase.
Add another screen. Let’s call it mainScreen. In screen properties, make it align horizontal and align vertical both center.
Add a textbox for entering notes. Add a button for saving. Customize them just like the previous screen.
Add a list view for showing previous notes for the user. Also, add a notifier for showing messages. We need another web component for this screen.
Also, add a clock from sensors for storing time with our notes.
Choose screen1 again and go to the blocks section.
Two global variables for containing the user’s unique identifier and token. These are sent by Firebase Authentication after a successful sign-up or login, and we need to store them to access the Realtime Database securely. Also, make a global variable for your API key and paste your Web API key in there that you had copied into your notepad. Don’t share your api key with anyone.



Our sign-up and log-in procedures are almost identical except for the web URL, so it is best to make a procedure. Hence, go to the Procedures section on the left and get the first type of block. Rename to signUpLoginPost. Click on the cog wheel to add an input parameter called url.

Here, we need to do error handling, so from Control, get an IF/ELSE block. In IF, add a condition for checking that the email textbox OR the password textbox isn’t empty. In the IF body, i.e., the place we will go when the IF condition is true, use the notifier to show an alert that both email and password are needed.

What will happen in ELSE?
We provide the input URL to the web’s URL property. We set the Web’s request headers to a dictionary with key: “Content-Type” and value: “application/json”. And then we send the user-entered data as a dictionary to the Firebase authentication system with returnSecureToken set to true. Please do it the same way, as the spellings of the keys are super important.

Now, what are the actual URLs:
They are different for both sign-up and login button click events.
For the signup button, the URL text box should be equal to a join of two things:
- https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=
- Your API key that you stored in the global variable.

For the login button, the URL text box should be equal to a join of two things:
- https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=
- Your api key that you stored in the global variable.

I will give them in the video description, so copyand paste them carefully.
Both sign-up and login buttons follow the same process of posting to the Web, so both will trigger the Web’s gotText event, so get that.

Again, because of error handling, we need an IF/ELSE block from Control. In IF, we first check that the response code is equal to 200. This is the standard web response for a successful request. If successful, we are going to decode our response content into a dictionary called responseDict.

Now, we have a dictionary in the form of something like this returned by Firebase authentication:
{
"idToken": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjA...",
"email": "[email protected]",
"refreshToken": "AEu4IL3i6K9oZg0zjB0D6VfL9g...",
"expiresIn": "3600",
"localId": "ZxY123abc456def789ghi012jkl",
"kind": "identitytoolkit#SignupNewUserResponse"
}
We are interested in two things. The localId and the idToken (spellings and case are both important here). We are going to use Dictionary’s getValue for the Key block to get these values by specifying exact keys and store them in our global variables uid and token, respectively. And we will open the second screen, passing these values in a dictionary.

Our else is for error handling, considering different situations.
So the final Web.GotText looks like this:

Our screen 1 is done and we have sent the data to the second screen.
So let’s work on the blocks on our second screen.
First, we make a global variable for our notesList.

Then, we make global variables for uid and token and set them to the data sent as a dictionary from the first screen.


Now, in the second screen’s initialize event, we need to load and show the already saved notes, if any.

The URL here is made up of a join of 5 things, and each piece is super important.
- The URL of your real-time database that you had copied and pasted in Notepad earlier.
- users/
- Global variable uid
- /notes.json?auth=
- Global variable token
Make sure that there are no typing mistakes in parts 1,2, and 3.
The web1.get will trigger the gotText event, but before working on that, let’s work on our saveBtn code. We check that the note’s text isn’t empty, and then we set exactly the same URL as we used in the screen’s initialize event, so duplicate from there.
Then we make a dictionary of two things: clock.now and notesTxt.text against their respective keys of “time” and “note”. And we post this as text to the Web. In the else, we show an alert that enter a value for the note.

The postText also triggers the Web’s gotText event, so now, let’s finally work on our final event, i.e., the Web’s gotText event. First, we check that we got a successful response from the server. If not, we show the error using the notifier’s show alert block.

Now, remember that a successful response could be because of two things. Either we loaded data successfully or we saved a new note successfully. How to differentiate?
If responseContent isn’t null and it doesn’t contain the word “name”, then this means that this was a successful load. In the other case, this was a successful save, so we reload the data by calling Web1. Get. No need to set web1.url again as it was set already earlier.

Read the italicized sentences if you want to know more about using “name”.
Why the word “name” for differentiating between save and load?
In case of a successful save, the Firebase Database generates a unique ID for your data, and it sends it back as JSON in the form of a key-value pair, where the key is “name”, so we can assume that if our response content contains “name”, it means a successful save.
{
“name”: “-NxR3C78YZkX5a9Qxyz”
}
And if it doesn’t, then it is a successful load.
Once we know it was a successful load, we set our notesList to an empty list. We decode the response content in a local responseDict variable.

Following is a snapshot of my current state of Realtime Database:
We had sent a dictionary of note and time, and it was saved against a unique key generated by Firebase.
We can get all these “note dictionaries” by using a for each key with value block from Control to go through our responseDictionary. Here each value is a “note dictionary” with two key value pairs. We get these values and join them with a “ – “ in between to make a display string or text and we add it to our notes list.

Once the for loop is finished, we need to give our notes list as elements to our listview.

So, our final gotText looks like this:

And this is done. I hope you liked this tutorial. You can check out my video tutorial for this project split into two videos:
Part 1:
Part 2:
Please like my tutorials and share it with your friends and family. Also, subscribe to my channel and press the bell icon so you don’t miss any of the great projects I have planned for you.
https://www.youtube.com/c/obsidiansofteducation
Please like my Facebook page and Instagram page for more educational resources and tips.
Facebook: https://www.facebook.com/ObsidianSoft/
Instagram: https://www.instagram.com/obsidiansoftapps/
Pinterest: https://www.pinterest.com/obsidiansoft/
For links to free educational apps, have a look at the educational apps page
