1

I used the same code for google oauth and I used flask-dance. This worked with google, but didn't work with discord. I get an error message saying that I need to be logged in to reach the home page, meaning that the discord account hasn't been registered in the sqlite database.

Here is my code

from flask import Flask, render_template, redirect, url_for, flash, Blueprint
from flask_login import current_user, login_user, login_required
from flask_dance.contrib.google import make_google_blueprint, google
from flask_dance.contrib.discord import make_discord_blueprint, discord
from flask_dance.consumer import oauth_authorized, oauth_error
from flask_dance.consumer.storage.sqla import SQLAlchemyStorage
from sqlalchemy.orm.exc import NoResultFound
from __init__ import db
from models import User, OAuth


discord_blueprint = make_discord_blueprint(client_id= "1001891783061553233", client_secret="QMvsUwbFGCLgYWgr8GAQ5ae2WibPTeDB", scope=["identify", "email"])


discord_bp = make_discord_blueprint(storage = SQLAlchemyStorage(OAuth, db.session, user = current_user))

@oauth_authorized.connect_via(discord_blueprint)
def discord_logged_in(blueprint, token):
if not token:
    flash("Failed to log in", category="error")
    return
resp = blueprint.session.get("/users/@me")
if not resp:
    msg = "Failed to fetch user info"
    flash(msg, category="error")
    return
discord_name = resp.json()["name"]
discord_user_id = resp.json() ["id"]

query = OAuth.query.filter_by(
    provider = blueprint.name, provider_user_id = discord_user_id
)

try:
    oauth = query.one()
except(NoResultFound):
    discord_user_login = discord_name

    oauth = OAuth(provider = blueprint.name,
        provider_user_id = discord_user_id,
        provider_user_login = discord_user_login,
        token=token,
        )
if current_user.is_anonymous:
    if oauth.user:
        login_user(oauth.user)
    else:
        user = User(username = discord_name)

        oauth.user = user
        db.session.add_all([user, oauth])
        db.session.commit()
        login_user(user)

else:
    if oauth.user:
        if current_user != oauth.user:
            url = url_for("auth.merge", username = oauth.user.username)
            return redirect(url)
    else:
        oauth.user = current_user
        db.session.add(oauth)
        db.commit()


return redirect(url_for("main.profile"))  

  


  

The google code is the same as the discord one and my redirect uri is localhost:5000/login/"oauthprovider"/authorized. For some reason the discord user isnt registered in the database?

Jeff Bob
  • 11
  • 2
  • I too would like to know. Whatever I use, i get an invalid redirect error. The "redirect_to and redirect_url" args also don't seem to do anything for me, as the redirect url always seems to be /discord/discord :-/ – Db0 Sep 06 '22 at 21:59

1 Answers1

0

I took me many hours to figure it out because there's literally 0 guides for this, but this the approach that worked for me in the end. This is an extract from my source, so you can see the full implementation here. I'm still working out some kinks like trying to be able to turn off os.environ['OAUTHLIB_INSECURE_TRANSPORT'] but I can login at least.


@REST_API.route('/register', methods=['GET', 'POST'])
def register():
    discord_data = None
    if discord.authorized:
        discord_info_endpoint = '/api/users/@me'
        try:
            discord_data = discord.get(discord_info_endpoint).json()
        except oauthlib.oauth2.rfc6749.errors.TokenExpiredError:
            pass

@REST_API.route('/discord')
def discord_login():
    return redirect(url_for('discord.login'))

if __name__ == "__main__":
    discord_client_id = os.getenv("DISCORD_CLIENT_ID")
    discord_client_secret = os.getenv("DISCORD_CLIENT_SECRET")
    REST_API.secret_key = os.getenv("secret_key")
    discord_blueprint = make_discord_blueprint(
        client_id = discord_client_id,
        client_secret = discord_client_secret,
        scope = ["identify"],
    )
    REST_API.register_blueprint(discord_blueprint,url_prefix="/discord")
Db0
  • 151
  • 2
  • 10