Created
June 2, 2022 13:01
-
-
Save twyle/a34ac74d021e4bd83c9c655c475f3291 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
"""This module contains the routes associated with the auth Blueprint.""" | |
import os | |
from flask_dance.contrib.github import make_github_blueprint, github | |
from flask_dance.consumer.storage.sqla import SQLAlchemyStorage | |
from flask_login import current_user | |
from .models import OAuth, User | |
from ..extensions import db | |
from flask_dance.consumer import oauth_authorized | |
from sqlalchemy.orm.exc import NoResultFound | |
from flask_login import login_user | |
from flask import redirect, url_for | |
auth = make_github_blueprint( | |
client_id=os.getenv('CLIENT_ID'), | |
client_secret=os.getenv('CLIENT_SECRET'), | |
storage=SQLAlchemyStorage( | |
OAuth, | |
db.session, | |
user=current_user, | |
user_required=False, | |
), | |
) | |
@oauth_authorized.connect_via(auth) | |
def github_logged_in(blueprint, token): # pylint: disable=W0613 | |
"""Automatically log in a user after authentication.""" | |
info = github.get('/user') | |
if info.ok: | |
account_info = info.json() | |
username = account_info['login'] | |
query = User.query.filter_by(username=username) | |
try: | |
user = query.one() | |
except NoResultFound: | |
user = User(username=username) | |
db.session.add(user) | |
db.session.commit() | |
login_user(user=user) | |
return redirect(url_for('default.dashboard')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment