コード例 #1
1
ファイル: test_github.py プロジェクト: psykzz/flask-dance
def test_context_local():
    responses.add(responses.GET, "https://google.com")

    # set up two apps with two different set of auth tokens
    app1 = Flask(__name__)
    ghbp1 = make_github_blueprint("foo1", "bar1", redirect_to="url1")
    app1.register_blueprint(ghbp1)
    ghbp1.token_getter(lambda: {"access_token": "app1"})

    app2 = Flask(__name__)
    ghbp2 = make_github_blueprint("foo2", "bar2", redirect_to="url2")
    app2.register_blueprint(ghbp2)
    ghbp2.token_getter(lambda: {"access_token": "app2"})

    # outside of a request context, referencing functions on the `github` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        github.get("https://google.com")

    # inside of a request context, `github` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        github.get("https://google.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"


    with app2.test_request_context("/"):
        app2.preprocess_request()
        github.get("https://google.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
コード例 #2
0
ファイル: app.py プロジェクト: Alwaz18/dribdat
def register_oauthhandlers(app):
    blueprint = None
    if not app.config["OAUTH_TYPE"]: return
    if app.config["OAUTH_TYPE"] == 'slack':
        blueprint = slack.make_slack_blueprint(
            client_id=app.config["OAUTH_ID"],
            client_secret=app.config["OAUTH_SECRET"],
            scope="identity.basic,identity.email",
            redirect_to="auth.slack_login",
            login_url="/login",
            # authorized_url=None,
            # session_class=None,
            # storage=None,
            subdomain=app.config["OAUTH_DOMAIN"],
        )
    elif app.config["OAUTH_TYPE"] == 'azure':
        blueprint = azure.make_azure_blueprint(
            client_id=app.config["OAUTH_ID"],
            client_secret=app.config["OAUTH_SECRET"],
            tenant=app.config["OAUTH_DOMAIN"],
            scope="profile email User.ReadBasic.All openid",
            redirect_to="auth.azure_login",
            login_url="/login",
        )
    elif app.config["OAUTH_TYPE"] == 'github':
        blueprint = github.make_github_blueprint(
            client_id=app.config["OAUTH_ID"],
            client_secret=app.config["OAUTH_SECRET"],
            # scope="user,read:user",
            redirect_to="auth.github_login",
            login_url="/login",
        )
    if blueprint is not None:
        app.register_blueprint(blueprint, url_prefix="/oauth")
コード例 #3
0
def register_github_oauth(app):
    app.config["GITHUB_OAUTH_CLIENT_ID"] = os.environ.get(
        "GITHUB_OAUTH_CLIENT_ID")
    app.config["GITHUB_OAUTH_CLIENT_SECRET"] = os.environ.get(
        "GITHUB_OAUTH_CLIENT_SECRET")
    github_bp = make_github_blueprint()
    app.register_blueprint(github_bp, url_prefix="/login")
コード例 #4
0
def create_module(app, **kwargs):
    from .models import User
    login_manager.init_app(app)
    bcrypt.init_app(app)
    openid.init_app(app)
    jwt.init_app(app)

    facebook_blueprint = make_facebook_blueprint(
        client_id=app.config.get("FACEBOOK_CLIENT_ID"),
        client_secret=app.config.get("FACEBOOK_CLIENT_SECRET"),
        scope=["email"])

    github_blueprint = make_github_blueprint(
        client_id=app.config.get("GITHUB_CLIENT_ID"),
        client_secret=app.config.get("GITHUB_CLIENT_SECRET"),
        scope=["user:email"])

    gitlab_blueprint = make_gitlab_blueprint(
        client_id=app.config.get("GITLAB_CLIENT_ID"),
        client_secret=app.config.get("GITLAB_CLIENT_SECRET"),
        scope=["read_user email"])
    from .routes import auth_blueprint
    app.register_blueprint(auth_blueprint)
    app.register_blueprint(facebook_blueprint, url_prefix="/auth/login")
    app.register_blueprint(github_blueprint, url_prefix="/auth/login")
    app.register_blueprint(gitlab_blueprint, url_prefix="/auth/login")

    event.listen(User, "after_insert", greeting_sender)
コード例 #5
0
ファイル: __init__.py プロジェクト: acbilson/chaos-auth
def create_app():
    """Initialize the core application"""
    app = Flask(__name__, instance_relative_config=False)
    app.config.from_object('config.Config')
    app = config_log(app)

    # required to encrypt session
    app.secret_key = app.config['SECRET_KEY']

    # initialize plugins
    cache = Cache(app)

    with app.app_context():
        # import parts of the app
        from .core import core
        from .api import api

        # register blueprints
        app.register_blueprint(core.core_bp)
        app.register_blueprint(api.api_bp)

        # registers github blueprint from flask-dance
        github_blueprint = make_github_blueprint(
            client_id=app.config['CLIENT_ID'],
            client_secret=app.config['CLIENT_SECRET'],
        )
        app.register_blueprint(github_blueprint, url_prefix="/login")

        app.logger.info('initialized auth app')
        return app
コード例 #6
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)

    if app.config['SSL_REDIRECT']:
        from flask_sslify import SSLify
        sslify = SSLify(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api/v1')

    app.config["GITHUB_OAUTH_CLIENT_ID"] = os.environ.get(
        "GITHUB_OAUTH_CLIENT_ID")
    app.config["GITHUB_OAUTH_CLIENT_SECRET"] = os.environ.get(
        "GITHUB_OAUTH_CLIENT_SECRET")
    github_bp = make_github_blueprint(redirect_to='auth.github')
    app.register_blueprint(github_bp, url_prefix="/login")
    from .models import OAuth
    #    github_bp.backend = SQLAlchemyBackend(OAuth, db.session, user=current_user)

    return app
コード例 #7
0
def register_github_oauth(app):
    app.config['GITHUB_OAUTH_CLIENT_ID'] = os.environ.get(
        'GITHUB_OAUTH_CLIENT_ID')
    app.config['GITHUB_OAUTH_CLIENT_SECRET'] = os.environ.get(
        'GITHUB_OAUTH_CLIENT_SECRET')
    github_bp = make_github_blueprint(scope='read:user,user:email',
                                      redirect_to='auth.login_oauth')
    app.register_blueprint(github_bp, url_prefix='/login')
コード例 #8
0
def test_blueprint_factory():
    github_bp = make_github_blueprint(
        client_id="foo", client_secret="bar", scope="user:email", redirect_to="index"
    )
    assert isinstance(github_bp, OAuth2ConsumerBlueprint)
    assert github_bp.session.scope == "user:email"
    assert github_bp.session.base_url == "https://api.github.com/"
    assert github_bp.session.client_id == "foo"
    assert github_bp.client_secret == "bar"
    assert github_bp.authorization_url == "https://github.com/login/oauth/authorize"
    assert github_bp.token_url == "https://github.com/login/oauth/access_token"
コード例 #9
0
    def __init__(self):
        super().__init__(__name__, template_folder="static")

        self.url_map.strict_slashes = False
        self.secret_key = os.getenv("SECRET_KEY", "skeleton-key")
        self.load_config()

        github_bp = make_github_blueprint(scope="public_repo,read:user",
                                          login_url="/",
                                          authorized_url="/authorized")
        self.register_blueprint(github_bp, url_prefix="/login")
コード例 #10
0
def test_load_from_config():
    app = Flask(__name__)
    app.secret_key = "anything"
    app.config["GITHUB_OAUTH_CLIENT_ID"] = "foo"
    app.config["GITHUB_OAUTH_CLIENT_SECRET"] = "bar"
    github_bp = make_github_blueprint(redirect_to="index")
    app.register_blueprint(github_bp)

    resp = app.test_client().get("/github")
    url = resp.headers["Location"]
    client_id = URLObject(url).query.dict.get("client_id")
    assert client_id == "foo"
コード例 #11
0
ファイル: test_github.py プロジェクト: jd/flask-dance
def test_blueprint_factory():
    github_bp = make_github_blueprint(client_id="foo",
                                      client_secret="bar",
                                      scope="user:email",
                                      redirect_to="index")
    assert isinstance(github_bp, OAuth2ConsumerBlueprint)
    assert github_bp.session.scope == "user:email"
    assert github_bp.session.base_url == "https://api.github.com/"
    assert github_bp.session.client_id == "foo"
    assert github_bp.client_secret == "bar"
    assert github_bp.authorization_url == "https://github.com/login/oauth/authorize"
    assert github_bp.token_url == "https://github.com/login/oauth/access_token"
コード例 #12
0
ファイル: test_github.py プロジェクト: yuvadm/flask-dance
def test_context_local():
    responses.add(responses.GET, "https://google.com")

    # set up two apps with two different set of auth tokens
    app1 = Flask(__name__)
    ghbp1 = make_github_blueprint(
        "foo1",
        "bar1",
        redirect_to="url1",
        backend=MemoryBackend({"access_token": "app1"}),
    )
    app1.register_blueprint(ghbp1)

    app2 = Flask(__name__)
    ghbp2 = make_github_blueprint(
        "foo2",
        "bar2",
        redirect_to="url2",
        backend=MemoryBackend({"access_token": "app2"}),
    )
    app2.register_blueprint(ghbp2)

    # outside of a request context, referencing functions on the `github` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        github.get("https://google.com")

    # inside of a request context, `github` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        github.get("https://google.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"

    with app2.test_request_context("/"):
        app2.preprocess_request()
        github.get("https://google.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
コード例 #13
0
ファイル: __init__.py プロジェクト: bopopescu/QUB-CS-Project
def create_app():
    ''' Initialise the application with necessary extensions '''
    app = Flask(__name__)
    app.config.from_object(Config)
    app.app_context().push()

    bootstrap.init_app(app)

    db.init_app(app)

    login_manager.init_app(app)

    app.register_blueprint(main)
    app.register_blueprint(auth)
    app.register_blueprint(jinja_templates)
    app.register_blueprint(errors)

    github_blueprint = make_github_blueprint(
        client_id=Config.client_id, client_secret=Config.client_secret)
    github_blueprint.backend = SQLAlchemyBackend(OAuth,
                                                 db.session,
                                                 user=current_user,
                                                 user_required=False)
    app.register_blueprint(github_blueprint, url_prefix='/login')

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    @oauth_authorized.connect_via(github_blueprint)
    def github_logged_in(blueprint, token):
        account_info = blueprint.session.get('/user')

        if account_info.ok:
            account_info_json = account_info.json()
            username = account_info_json['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)
            flash("Successfully signed in with GitHub.", 'success')

    return app
コード例 #14
0
ファイル: application.py プロジェクト: cdvx/github_tool
def create_app(ENV):
    app = Flask(__name__)
    app.config.from_object(config.get(ENV))
    blueprint = make_github_blueprint(
        client_id=config.get(ENV).GITHUB_CLIENT_ID,
        client_secret=config.get(ENV).GITHUB_CLIENT_SECRET)
    app.register_blueprint(blueprint, url_prefix="")

    # setup_db
    db.init_app(app)

    # Register Blueprints
    app.register_blueprint(user_app)

    return app
コード例 #15
0
def app():
    _app = flask.Flask(__name__)
    _app.secret_key = "secret"
    github_bp = make_github_blueprint(
        storage=MemoryStorage({"access_token": GITHUB_ACCESS_TOKEN}))
    _app.register_blueprint(github_bp, url_prefix="/login")

    @_app.route("/")
    def index():
        if not github.authorized:
            return redirect(url_for("github.login"))
        resp = github.get("/user")
        assert resp.ok
        return "You are @{login} on GitHub".format(login=resp.json()["login"])

    return _app
コード例 #16
0
def create_app():
    app = Flask(__name__)

    app.config['SECRET_KEY'] = 'superdupersecretkey'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@db/db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db.init_app(app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from .models import User

    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    github_blueprint = make_github_blueprint(
        client_id=os.environ.get('GITHUB_OAUTH_CLIENT_ID'),
        client_secret=os.environ.get('GITHUB_OAUTH_CLIENT_SECRET'))
    app.register_blueprint(github_blueprint, url_prefix='/github_login')

    @app.route('/github')
    def github_login():
        if not github.authorized:
            return redirect(url_for('github.login'))

        account_info = github.get('/user')

        if account_info.ok:
            account_info_json = account_info.json()
            return "You are @{login} on Github".format(
                login=account_info.json()["login"])

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

        return redirect(url_for('auth.login'))

    return app
コード例 #17
0
def app():
    _app = flask.Flask(__name__)
    _app.secret_key = "secret"
    github_bp = make_github_blueprint(
        storage=MemoryStorage({"access_token": GITHUB_ACCESS_TOKEN})
    )
    _app.register_blueprint(github_bp, url_prefix="/login")

    @_app.route("/")
    def index():
        if not github.authorized:
            return redirect(url_for("github.login"))
        resp = github.get("/user")
        assert resp.ok
        return "You are @{login} on GitHub".format(login=resp.json()["login"])

    return _app
コード例 #18
0
ファイル: __init__.py プロジェクト: ejemtegaard/juleol
def create_app(test_config=None):
    app = Flask(__name__)
    app.config.from_object('juleol.default_config')
    if 'JULEOL_SETTINGS' in os.environ:
        app.config.from_envvar('JULEOL_SETTINGS')

    if test_config:
        app.config.from_object(test_config)

    from juleol import admin, db, view, oauth_generic
    app.register_blueprint(admin.bp)
    app.register_blueprint(view.bp)

    if app.config.get('ADMIN_OAUTH_PROVIDER', 'github') == 'oauth-generic':
        admin_oauth_bp = oauth_generic.make_oauth_blueprint(
            redirect_to="admin.admin_index")
        app.config['admin_oauth'] = juleol.oauth_generic.oauth
        app.config['admin_oauth_login'] = '******'
    elif app.config.get('ADMIN_OAUTH_PROVIDER', 'github') == 'github':
        admin_oauth_bp = make_github_blueprint(redirect_to="admin.admin_index")
        app.config['admin_oauth'] = github
        app.config['admin_oauth_login'] = '******'
    else:
        raise Exception('Unknown admin oauth provider configured')
    app.register_blueprint(admin_oauth_bp, url_prefix="/admin/login")

    if app.config.get('USER_OAUTH_PROVIDER', 'google') == 'google':
        user_oauth_bp = make_google_blueprint(
            redirect_to='view.login',
            scope="openid https://www.googleapis.com/auth/userinfo.email")
        app.config['user_oauth'] = google
        app.config['user_oauth_login'] = '******'
    else:
        raise Exception('Unknown user oauth provider configured')
    app.register_blueprint(user_oauth_bp, url_prefix="/login")

    db.db.init_app(app)
    Migrate(app, db.db)

    return app
コード例 #19
0
ファイル: app.py プロジェクト: sharmaudi/catalog-udacity
def register_github_blueprint(app):
    # Facebook
    client_id = app.config.get('OAUTH_CONFIG')['GITHUB']['client_id']
    client_secret = app.config.get('OAUTH_CONFIG')['GITHUB']['client_secret']

    github_blueprint = make_github_blueprint(client_id=client_id,
                                             client_secret=client_secret,
                                             scope=["public_profile", "email"])
    github_blueprint.backend = SQLAlchemyBackend(OAuth,
                                                 db.session,
                                                 user=current_user)
    app.register_blueprint(github_blueprint, url_prefix="/login")

    # create/login local user on successful OAuth login
    @oauth_authorized.connect_via(github_blueprint)
    def github_logged_in(blueprint, token):
        if not token:
            flash("Failed to log in with {name}".format(name=blueprint.name))
            return
        # figure out who the user is
        resp = blueprint.session.get("/user")
        if resp.ok:
            print(f"Response from github: {resp.json()}")
            username = resp.json()["login"]
            query = User.query.filter_by(username=username)
            try:
                user = query.one()
            except NoResultFound:
                # create a user
                user = User()
                user.username = username
                user.save()
            login_user(user)
            flash("Successfully signed in with Github", "success")
        else:
            print(resp.text)
            msg = "Failed to fetch user info from {name}".format(
                name=blueprint.name)
            flash(msg, category="error")
コード例 #20
0
def make_github_blueprint():
    """ Following the instructions at
https://flask-dance.readthedocs.io/en/latest/providers.html#module-flask_dance.contrib.github
"""

    arg_name2config_key = {
        "client_id": "GITHUB_OAUTH_CLIENT_ID",
        "client_secret": "GITHUB_OAUTH_CLIENT_SECRET",
    }

    config_kwargs = populate_config_kwargs(arg_name2config_key, app.config)

    kwargs = {
        #"scope": ["read:user"],
        "scope": ["user:email"],
        "redirect_to": "oauth_status",
    }

    blueprint = github_dance.make_github_blueprint(**config_kwargs, **kwargs)

    blueprint.storage = flask_dance.consumer.storage.sqla.SQLAlchemyStorage(fra_back.models.OAuth, master_session)

    return blueprint
コード例 #21
0
def create_app(config_name, github_api=github):
    app = Flask(__name__)

    app_config = config.get_app_config(os.environ)
    app.secret_key = app_config['app_secret']
    blueprint = make_github_blueprint(
        client_id=app_config['github_client_id'],
        client_secret=app_config['github_client_secret'],
        scope='public_repo',
        redirect_url='/replicate'
    )
    app.register_blueprint(blueprint, url_prefix='/replicate')

    @app.route('/', methods=['GET'])
    def index(**kwargs):
        return render_template('index.html'), 200

    @app.route('/replicate', methods=['GET'])
    def replicate(**kwargs):
        if not github_api.authorized:
            return redirect(url_for('github.authorized'))

        user_response = github_api.get('/user')
        target_user = user_response.json()['login']

        response = github_api.post(
            f'/repos/{app_config["repo_owner"]}/{app_config["repo_name"]}/forks'
        )
        repo_link = config.get_url_to_repo(target_user, app_config['repo_name'])

        if response.status_code == 202:
            return render_template('success.html', repo_link=repo_link)
        else:
            return render_template('failure.html', response=response.json())

    return app
コード例 #22
0
from flask_dance.contrib.google import make_google_blueprint, google
from flask_dance.contrib.github import make_github_blueprint, github
from flask_dance.consumer import oauth_authorized

from flask import Blueprint
auth_bp = Blueprint('auth',
                    __name__,
                    template_folder='')

google_bp = make_google_blueprint(client_id=config['GOOGLE_CLIENT_ID'],
                                  client_secret=config['GOOGLE_CLIENT_SECRET'],
                                  scope=["https://www.googleapis.com/auth/userinfo.profile",
                                         "https://www.googleapis.com/auth/userinfo.email"],
                                  offline=True)
github_bp = make_github_blueprint(client_id=config['GITHUB_CLIENT_ID'],
                                  client_secret=config['GITHUB_CLIENT_SECRET'],
                                  scope="user:email")
# dropbox_bp = make_dropbox_blueprint()


@auth_bp.route("/login/select", methods=['GET'])
def choose_login(error=None):
    # Relax scope for Google
    if not (session.get("login_referrer", "/").endswith("/login/select")):
        session["login_referrer"] = request.referrer
    os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = "true"
    VARS = {'page_title': 'Choose Login'}
    if error:
        flash(error, 'danger')
    return render_template('login.html', **VARS)
コード例 #23
0
from flask import Flask, request, render_template, redirect, session, url_for
from flask_dance.contrib.github import make_github_blueprint, github
from github import Github, GithubException

import json
import base64
import bcrypt

from .models import User, Lab, db, Solve
from .util import decrypt_flag, encrypt_flag

from dashboard import app

github_bp = make_github_blueprint()
app.register_blueprint(github_bp, url_prefix="/login")

github_sdk = Github()


def fetch_user(func):
    def wrapper_fetch_user(*args, **kwargs):
        if github.authorized:
            if not session.get("user_id"):
                r = github.get("/user")
                github_user = json.loads(r.text)
                user = User.query.filter(User.id == github_user["id"]).first()

                if user:
                    user.github_login = github_user["login"]
                else:
                    user = User(github_user["id"], github_user["login"],
コード例 #24
0
ファイル: oauth.py プロジェクト: dan-f/openedx-webhooks
)
jira_bp.set_token_storage_sqlalchemy(OAuth, db.session)


@oauth_authorized.connect_via(jira_bp)
def jira_logged_in(blueprint, token):
    if token:
        flash("Successfully signed in with JIRA")
    else:
        flash("You denied the request to sign in with JIRA")

## GITHUB ##

github_bp = make_github_blueprint(
    client_id=os.environ["GITHUB_CLIENT_ID"],
    client_secret=os.environ["GITHUB_CLIENT_SECRET"],
    scope="admin:repo_hook,repo,user",
    redirect_to="index",
)
github_bp.set_token_storage_sqlalchemy(OAuth, db.session)


@oauth_authorized.connect_via(github_bp)
def github_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in with Github")
    if "error_reason" in token:
        msg = "Access denied. Reason={reason} error={error}".format(
            reason=request.args["error_reason"],
            error=request.args["error_description"],
        )
        flash(msg)
コード例 #25
0
ファイル: test_github.py プロジェクト: jd/flask-dance
 def _make_app(*args, **kwargs):
     app = Flask(__name__)
     app.secret_key = "whatever"
     blueprint = make_github_blueprint(*args, **kwargs)
     app.register_blueprint(blueprint)
     return app
コード例 #26
0
def jira_logged_in(blueprint, token):
    if token:
        flash("Successfully signed in with JIRA")
    else:
        flash("You denied the request to sign in with JIRA")


@oauth_error.connect_via(jira_bp)
def jira_error(blueprint, message, response=None):
    flash(message, category="error")


## GITHUB ##

github_bp = make_github_blueprint(
    scope="admin:repo_hook,repo,user",
    backend=SQLAlchemyBackend(OAuth, db.session),
)


@oauth_authorized.connect_via(github_bp)
def github_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in with Github")
    if "error_reason" in token:
        msg = "Access denied. Reason={reason} error={error}".format(
            reason=request.args["error_reason"],
            error=request.args["error_description"],
        )
        flash(msg)
    else:
        flash("Successfully signed in with Github")
コード例 #27
0
from flask_login import current_user

from project.utils.login import general_logged_in, general_error

from project.models import OAuth, db

facebook_blueprint = make_facebook_blueprint(
    backend=SQLAlchemyBackend(OAuth, db.session, user=current_user, user_required=False)
)

twitter_blueprint = make_twitter_blueprint(
    backend=SQLAlchemyBackend(OAuth, db.session, user=current_user, user_required=False)
)

github_blueprint = make_github_blueprint(
    backend=SQLAlchemyBackend(OAuth, db.session, user=current_user, user_required=False)
)


@oauth_authorized.connect_via(twitter_blueprint)
def twitter_logged_in(blueprint, token):
    return general_logged_in(blueprint, token, 'account/settings.json')


@oauth_error.connect_via(twitter_blueprint)
def twitter_error(blueprint, error, error_description=None, error_uri=None):
    return general_error(blueprint, error, error_description, error_uri)


@oauth_authorized.connect_via(facebook_blueprint)
def facebook_logged_in(blueprint, token):
コード例 #28
0
import json
from time import time
from random import random
from flask import Flask, render_template, make_response, Response
from flask_dance.contrib.github import make_github_blueprint, github
import io
import cv2
import os

os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

app = Flask(__name__, static_folder='static')
app.config["SECRET_KEY"] = "secretkey"
vc = cv2.VideoCapture(0)

github_blueprint = make_github_blueprint(client_id='client_id',
                                         client_secret='celinet_secrect')

app.register_blueprint(github_blueprint, url_prefix='/github_login')


@app.route('/')
def github_login():

    if not github.authorized:
        return redirect(url_for('github.login'))
    else:
        account_info = github.get('/user')
        if account_info.ok:
            account_info_json = account_info.json()
            return render_template('index.html')
コード例 #29
0
from flask import render_template, abort, request
from flask_security import login_required, current_user, login_user
from flask_dance.contrib.github import make_github_blueprint
from flask_dance.consumer.backend.sqla import SQLAlchemyBackend
from flask_dance.consumer import oauth_authorized

from ext import db
from models.user import User, OAuth
from models.core import Post
from models.collect import CollectItem
from models.like import LikeItem
from models.contact import Contact
from corelib.utils import AttrDict

bp = Blueprint("account", __name__)
github_bp = make_github_blueprint(
    backend=SQLAlchemyBackend(OAuth, db.session, user=current_user))


@oauth_authorized.connect_via(github_bp)
def github_logged_in(blueprint, token):
    if not token:
        return False
    resp = blueprint.session.get("/user")
    if not resp.ok:
        return False

    github_info = resp.json()
    github_user_id = str(github_info["id"])
    oauth = OAuth.query.filter_by(provider=blueprint.name,
                                  provider_user_id=github_user_id).first()
    if oauth:
コード例 #30
0
ファイル: myapp.py プロジェクト: huijuannan/mipe
        session, url_for, g, flash, abort)
from flask_dance.contrib.github import make_github_blueprint, github

import torndb # A lightweight wrapper around MySQLdb
import config

# configuration
SECRET_KEY = 'secretkey'

# create application
app = Flask(__name__)
app.debug = True
app.secret_key = SECRET_KEY
blueprint = make_github_blueprint(
    client_id=config.OAUTH_CLIENT_ID,
    client_secret=config.OAUTH_CLIENT_SECRET,
    scope=u'user:email',
)

app.register_blueprint(blueprint, url_prefix="/login")

@app.before_request
def before_request():
    '''在 request 之前:
    1、建立 MySQL 数据库连接
    2、检验用户登录状态,若已登录则存入 g.user
    '''
    
    # 建立 MySQL 连接,参数:host:port, database, user, passwd
    # torndb 默认已将 charset 设为 utf-8
    g.db = torndb.Connection(
コード例 #31
0
ファイル: oauth.py プロジェクト: singingwolfboy/webhookdb
    def request(self, method, url, data=None, headers=None, **kwargs):
        resp = super(GithubSession, self).request(
            method=method, url=url, data=data, headers=headers, **kwargs
        )
        self.last_response = resp
        if resp.status_code == 403 and resp.headers.get("X-RateLimit-Remaining"):
            rl_remaining = int(resp.headers["X-RateLimit-Remaining"])
            if rl_remaining < 1:
                raise RateLimited(response=resp)
        return resp


github_bp = make_github_blueprint(
    scope="admin:repo_hook",
    redirect_to="ui.index",
    session_class=GithubSession,
)
github_bp.backend = SQLAlchemyBackend(OAuth, db.session, user=current_user)


@oauth_authorized.connect_via(github_bp)
def github_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in with Github")
    if "error_reason" in token:
        msg = "Access denied. Reason={reason} error={error}".format(
            reason=request.args["error_reason"],
            error=request.args["error_description"],
        )
        flash(msg)
コード例 #32
0
ファイル: __init__.py プロジェクト: opengridcc/website
    from opengrid.library import houseprint
    from opengrid.library import slack

try:
    hp = houseprint.Houseprint()
except:
    print("Connection failed, loading houseprint from cache")
    hp = houseprint.load_houseprint_from_file("cache_hp.hp")
else:
    hp.save("cache_hp.hp")

hp.init_tmpo()

if env == 'prod':
    blueprint = make_github_blueprint(
        client_id=c.get('github', 'clientid'),
        client_secret=c.get('github', 'clientsecret'),
    )
    app.register_blueprint(blueprint, url_prefix="/login")

sandbox_path = os.path.join(os.path.dirname(__file__), "static", "sandbox")
if not os.path.exists(sandbox_path):
    os.mkdir(sandbox_path)
download_path = os.path.join(os.path.dirname(__file__), "static", "downloads")
if not os.path.exists(download_path):
    os.mkdir(download_path)

slack_url = c.get('slack', 'webhook')
slack_username = c.get('slack', 'username')
slack_channel = c.get('slack', 'channel')
slackbot = slack.Slack(url=slack_url, username=slack_username,
                       channel=slack_channel)
コード例 #33
0
try:
    from flask import Flask, render_template, url_for, request, redirect, make_response
    import secrets
    import string
    import json
    from time import time
    from flask_dance.contrib.github import make_github_blueprint, github
except Exception as e:
    print("Some Modules are Missings {}".format(e))

app = Flask(__name__)
res = ''.join(
    secrets.choice(string.ascii_uppercase + string.digits) for i in range(10))
app.config["SECRET_KEY"] = res

github_blueprint = make_github_blueprint(client_id='Enter Key Here',
                                         client_secret='Enter Secret Here')

app.register_blueprint(github_blueprint, url_prefix='/github_login')


@app.route('/')
def github_login():

    if not github.authorized:
        return redirect(url_for('github.login'))
    else:
        account_info = github.get('/user')
        if account_info.ok:
            account_info_json = account_info.json()
            #return format(account_info_json['login'])
            username = format(account_info_json['login'])
コード例 #34
0
import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.github import make_github_blueprint, github

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit")
app.config["GITHUB_OAUTH_CLIENT_ID"] = os.environ.get("GITHUB_OAUTH_CLIENT_ID")
app.config["GITHUB_OAUTH_CLIENT_SECRET"] = os.environ.get("GITHUB_OAUTH_CLIENT_SECRET")
github_bp = make_github_blueprint()
app.register_blueprint(github_bp, url_prefix="/login")

@app.route("/")
def index():
    if not github.authorized:
        return redirect(url_for("github.login"))
    resp = github.get("/user")
    assert resp.ok
    return "You are @{login} on GitHub".format(login=resp.json()["login"])

if __name__ == "__main__":
    app.run()
コード例 #35
0
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_dance.consumer.backend.sqla import SQLAlchemyBackend
from flask_dance.contrib.github import make_github_blueprint
from flask_login import LoginManager
from werkzeug.contrib.fixers import ProxyFix


app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
app.config.from_object(Config)

db = SQLAlchemy(app)
migrate = Migrate(app, db)


github_blueprint = make_github_blueprint(
    client_id="674925257692ed46a38b",
    client_secret="319fb87ac542c68085927440429a968f0bf55dbf",
)

app.register_blueprint(github_blueprint, url_prefix="/login")

login_manager = LoginManager()
login_manager.init_app(app)

from app import routes, models

github_blueprint.backend = SQLAlchemyBackend(models.OAuth, db.session)
コード例 #36
0
#!/usr/bin/env python2
from flask import flash
from flask_login import current_user, login_user
from flask_dance.contrib.github import make_github_blueprint
from flask_dance.consumer import oauth_authorized, oauth_error
from flask_dance.consumer.storage.sqla import SQLAlchemyStorage
from sqlalchemy.orm.exc import NoResultFound
from models import db, User, OAuth

blueprint = make_github_blueprint(
    storage=SQLAlchemyStorage(OAuth, db.session, user=current_user))


# create/login local user on successful OAuth login
@oauth_authorized.connect_via(blueprint)
def github_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in.", category="error")
        return False

    resp = blueprint.session.get("/user")
    if not resp.ok:
        msg = "Failed to fetch user info."
        flash(msg, category="error")
        return False

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

    # Find this OAuth token in the database, or create it
    query = OAuth.query.filter_by(provider=blueprint.name,
コード例 #37
0
facebook_bp = make_facebook_blueprint(rerequest_declined_permissions=True)
facebook_bp.rerequest_declined_permissions = True
app.register_blueprint(facebook_bp, url_prefix="/login")


# FB connection
@app.route("/facebook")
def fb_login():
    if not facebook.authorized and not twitter.authorized:
        return redirect(url_for("facebook.login"))
    return redirect(url_for("profile"))


#GitHub connector
github_blueprint = make_github_blueprint(
    client_id="3fd3ed5da5ba6866d500",
    client_secret="3d9bb861579f18533b71d261628b195205e67388")
app.register_blueprint(github_blueprint, url_prefix='/github_login')


@app.route("/github")
def github_login():
    if not github.authorized:
        return redirect(url_for('github.login'))
    return redirect(url_for("profile"))


#APIs
omdbAPI = "https://www.omdbapi.com/?apikey=65f7361a&"
openLibraryAPI = "http://openlibrary.org/"
openLibraryCoverAPI = "http://covers.openlibrary.org/"
コード例 #38
0
ファイル: run.py プロジェクト: sharqawiDev/Project4-FSND
from sqlalchemy.orm.exc import NoResultFound
# the following imports are to handle authorization and login
from flask_dance.contrib.github import (make_github_blueprint, github)
from flask_dance.consumer.backend.sqla import (OAuthConsumerMixin,
                                               SQLAlchemyBackend)
from flask_dance.consumer import (oauth_authorized, oauth_error)
from flask_login import (LoginManager, UserMixin, current_user, login_required,
                         login_user, logout_user)

# setup Flask application
app = Flask(__name__)
app.config['SECRET_KEY'] = '669cb1481ecf76427f625b5233b0ca'
blueprint = make_github_blueprint(
    # showing these info is not the best practice,
    # but since this project is just for edu purposes,
    # I wrote the clint_id and client_secrets to ease the
    # process of running the file
    client_id="1568a5199334b2604837",
    client_secret="35dbc7f21f1e80b8f5304b46b1bed52fb408dce9",
)
app.register_blueprint(blueprint, url_prefix="/login")
bcrypt = Bcrypt(app)

# setup database models
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
# categories are just an array because we don't want the users
# to be able to add new categories,
# they are only able to add items
categories = [
    'Soccer', 'Basketball', 'Baseball', 'Frisbee', 'Snowboarding',
    'Rock Climbing', 'Foosball', 'Skating', 'Hockey'
コード例 #39
0
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.github import make_github_blueprint, github
from flask_dance.contrib.google import make_google_blueprint, google
from flask_dance.contrib.facebook import make_facebook_blueprint, facebook
from flask_dance.consumer import oauth_authorized, oauth_error
from flask_dance.consumer.storage.sqla import SQLAlchemyStorage
from sqlalchemy.orm.exc import NoResultFound
from . import db
from .models import User, OAuth

github_blueprint = make_github_blueprint(client_id = 'YOUR CLIENT ID', client_secret = 'YOUR CLIENT SECRET')

google_blueprint = make_google_blueprint(client_id= "YOUR CLIENT ID", client_secret= "YOUR CLIENT SECRET",  scope=[
        "openid",
        "https://www.googleapis.com/auth/userinfo.email",
        "https://www.googleapis.com/auth/userinfo.profile",
    ]
)

facebook_blueprint = make_facebook_blueprint(client_id= "YOUR CLIENT ID", client_secret= "YOUR CLIENT SECRET", scope = [
    "email"
    ]
)

github_bp = make_github_blueprint(storage = SQLAlchemyStorage(OAuth, db.session, user = current_user))

google_bp = make_google_blueprint(storage = SQLAlchemyStorage(OAuth, db.session, user = current_user))

facebook_bp = make_facebook_blueprint(storage = SQLAlchemyStorage(OAuth, db.session, user = current_user))
コード例 #40
0
 def _make_app(*args, **kwargs):
     app = Flask(__name__)
     app.secret_key = "whatever"
     blueprint = make_github_blueprint(*args, **kwargs)
     app.register_blueprint(blueprint)
     return app