picture of a laptop keyboard

Add Firebase login to python app

2024-02-18
Mark Hughes

This post briefly explains how to use Firebase email and password authentication in a Flask app to prevent unauthorized users from accessing certain pages

Assuming a basic app exists

import pyrebase4 in requirements.txt add pyrebase4==4.7.1 and setuptools==69.1.0

For my use case I don’t want the home page behind an auth flow, just a page for adding posts so I’ll add this code to the specific route for login

First add a user in the firebase console

If you’re going to allow users to sign up in your app, this isn’t strictly necessary, but my app isn’t allowing sign-ups.

in app.py

import pyrebase

... 

config = {
    'apiKey': "AIzaSyCMsYDdaXUzA5p6jgsSGsNqm5sO9Q2c2YQ",
    'authDomain': "markblog-7a692.firebaseapp.com",
    'projectId': "markblog-7a692",
    'storageBucket': "markblog-7a692.appspot.com",
    'messagingSenderId': "719594945838",
    'appId': "1:719594945838:web:3aa2a88ceef7b8f1428ebf",
    'measurementId': "G-2PZ6BNMGVY",
    'databaseURL': ''
}
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()

app.secret_key = 'secret'
...

@app.route('/manage', methods=["GET", "POST"])
def manage():
    if 'user' in session:
        return 'Hi, {}'.format(session['user'])
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        try:
            user = auth.sign_in_with_email_and_password(email, password)
            session['user'] = email
            print(user)
        except:
            return "Failed to log in"
    return render_template('manage.html')

create login.html

{% include "snippets/header.html" %}
<body>
   <form action="{{ url_for('manage') }}" method="POST">
       Email: <input type="email" name="email"><br>
       Password: <input type="password" name="password">
       <input type="submit">
   </form>
{% include "snippets/firebase.html" %}
</body>
{% include "snippets/footer.html" %}

(this is specific to my page layout)

To allow users to sign up, add a form with username and email and call this method, but I don’t want to on this app (later I want to add comments where I’ll probably include google sign up)

#user = auth.create_user_with_email_and_password(email, password)

But for signing a user in, this method is called

user = auth.sign_in_with_email_and_password(email, password)
session['user'] = email

Setting the session is important because it’s how your app knows you’re signed in to access restricted pages.

When running locally, you can test this has worked with the following command

info = auth.get_account_info(user['idToken'])
print(info)

You'll see the information returned from firebase for the logged in user.