2
app = Flask(__name__)
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
db = firebase.database()

@app.route('/login', methods=["POST", "GET"])
    def login():
        message = ""
        if request.method == "POST":
            email = request.form["login_email"]
            password = request.form["login_password"]
            try:
                user = auth.sign_in_with_email_and_password(email, password)
                user = auth.refresh(user['refreshToken'])
                user_id = user['idToken']
                return redirect(url_for('admin'))
            except:
                message = "Incorrect Password!"
        return render_template("login.html", message=message)

@app.route('/admin')
def admin():
    return render_template("admin.html")

if __name__ == '__main__':
    app.run()

How can I only load /admin page when the user is logged in? I know it has something to do with the user token, but I'm still not sure about how I could use the token to identify whether the user is logged in or not. Also, the user and user_id are not defined in admin()and only in login() since they're in a function.

So what do I need to change in my code in order to only load the /admin page when the user is logged in?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Thomas Tseng
  • 53
  • 1
  • 8

1 Answers1

2

use flask session to store your key,if key exist then user is logged,

also you can access all session variables globally for individual session

from flask import Flask, session, request
import requests
import os

app = Flask(__name__)
app.secret_key = os.urandom(24)
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
db = firebase.database()

@app.route('/login', methods=["POST", "GET"])
def login():
    message = ""
    try:
        print(session['usr'])
        return redirect(url_for('admin'))
    except KeyError:
        if request.method == "POST":
            email = request.form["login_email"]
            password = request.form["login_password"]
            try:
                user = auth.sign_in_with_email_and_password(email, password)
                user = auth.refresh(user['refreshToken'])
                user_id = user['idToken']
                session['usr'] = user_id
                return redirect(url_for('admin'))
            except:
                message = "Incorrect Password!"
        return render_template("login.html", message=message)

@app.route('/admin')
def admin():
    try:
        print(session['usr'])
        return render_template("admin.html")
    except KeyError:
        return redirect(url_for('login'))


if __name__ == '__main__':
    app.run()

if session['usr'] is not assigned then it will give key error which means that usr in not logged in. but note that in the process of logout you need to delete the session for that usr.

Thomas Tseng
  • 53
  • 1
  • 8
Nihal
  • 5,262
  • 7
  • 23
  • 41
  • Thank you for replying. I am wondering how I could use flask session to know whether the user is logged in or not in `admin()`. Should I use `if session['usr'] == "":` or something else? The token would expire too, so I'm not sure what to do in `admin()` yet. Thank you! – Thomas Tseng Mar 20 '19 at 13:30
  • Sorry, but how about in `admin()`? – Thomas Tseng Mar 20 '19 at 13:33
  • Sorry, I think there is a problem logging in. So after I removed the `try` and `except` from `try: user = auth.sign_in_with_email_and_password(email, password) , I got an error: RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret. @Nihal Thank you! – Thomas Tseng Mar 20 '19 at 13:53
  • 1
    Thank you for helping, @Nihal, I finally figured it out. – Thomas Tseng Mar 20 '19 at 14:12
  • sry i forgot you have to set secretkey for having session – Nihal Mar 20 '19 at 19:22