-1

I want some of my flask routes to be authenticated before accessing, meaning any routes with the decorator @check_token will have to have a valid token prior to accessing the route.

I have a login_or_create route where users can either login or create an account onto Firebase.

From the login logic, a token is generated, and I want to pass that token to the home route. I feel my code is almost there, but I'm not sure how to persist the token into the next route.


def check_token(f):
    @wraps(f)
    def wrap(*args,**kwargs):
        if not request.headers.get('authorization'):
            return {'message': 'No token provided'},400
        try:
            user = auth.verify_id_token(request.headers['authorization'])
            request.user = user
        except:
            return {'message':'Invalid token provided.'},400
        return f(*args, **kwargs)
    return wrap

@app.route("/", methods=['GET', 'POST'])
def login_or_create():
    if request.method == 'POST':
        #Handle login form
        if request.form['action'] == 'login':
            data = request.form
            email = data.get('user_email')
            password = data.get('user_password')
            try:
                signin_user = pb.auth().sign_in_with_email_and_password(email, password)
                token = signin_user['idToken']
                return redirect(url_for('home'))
            except:
                return {'message':'There was an error logging in'}, 400



@app.route("/home")
@check_token
def home():
    return render_template('home_page.html)'
Ryan Tom
  • 195
  • 3
  • 14

1 Answers1

0

I ended up saving the token in a session variable. I think there are drawbacks to this, but this has been my solution thus far.

Ryan Tom
  • 195
  • 3
  • 14