Search code examples
pythonflaskoauthflask-dance

How to identify if Google OAuth was authorized or rejected in Flask-Dance framework


Sorry, new to Flask-Dance. I'm using the template code from: https://github.com/singingwolfboy/flask-dance-google/blob/master/google.py

import os
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google

app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit")
app.config["GOOGLE_OAUTH_CLIENT_ID"] = os.environ.get("GOOGLE_OAUTH_CLIENT_ID")
app.config["GOOGLE_OAUTH_CLIENT_SECRET"] = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET")
google_bp = make_google_blueprint(scope=["profile", "email"])
app.register_blueprint(google_bp, url_prefix="/login")

@app.route("/")
def index():
    if not google.authorized:
        return redirect(url_for("google.login"))
    resp = google.get("/oauth2/v1/userinfo")
    assert resp.ok, resp.text
    return "You are {email} on Google".format(email=resp.json()["email"]) 

As I understand , if google.authorized is NOT true, it redirects to the route "google.login". I'm wondering is there a way to know if I have been redirected as a result of being unauthorized from O-auth vs just being directed to the login url.

Thanks


Solution

  • Since you are new to Flask-Dance, I would like to recommend my library Authlib instead. You can check the Google login example for Flask at:

    https://github.com/authlib/demo-oauth-client/tree/master/flask-google-login