1

I'm making a web dashboard using Flask and it has Discord login (Flask-Dance). The code gives me this error: sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: users.login. The code works completely fine if the user is already logged in. But when someone else who is not logged in tried to log in, the error occurs. This is what I am working with currently:

class User(UserMixin, dbsl.Model):
    id = dbsl.Column(dbsl.Integer, primary_key=True)
    email = dbsl.Column(dbsl.String(256), unique=True)


class OAuth(OAuthConsumerMixin, dbsl.Model):
    user_id = dbsl.Column(dbsl.Integer, dbsl.ForeignKey(User.id), nullable=False)
    user = dbsl.relationship(User)

@oauth_authorized.connect_via(d_oauth)
def discord_logged_in(blueprint, token):
    resp = discord_oauth.discord.get("/api/users/@me").content

    info = json.loads(resp)
    user_id = info["id"]

    query = OAuth.query.filter_by(provider=blueprint.name, user_id=user_id)
    try:
        oauth = query.one()
    except NoResultFound:
        oauth = OAuth(user_id=user_id, token=token)

    if oauth.user:
        login_user(oauth.user)

    else:
        user = User(email=info["email"], id=user_id)
        oauth.user = user
        dbsl.session.add_all([user, oauth])
        dbsl.session.commit()
        login_user(user)

    return False

As I said, the program works completely fine, but it throws this error when someone who is not logged in tries to log in. How can I fix this?

Emir Sürmen
  • 884
  • 3
  • 14
  • 33
  • 1
    This happens when you’re adding a new user object that conflicts with an existing one in the database. So if oath.user is False but the user object it creates actually exists, then you’ll bit this error. – chris.mclennon Apr 08 '21 at 06:26

0 Answers0