def create_app(config_class=Config): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) login_manager.init_app(app) mail.init_app(app) from iblog.users.routes import users from iblog.posts.routes import posts from iblog.main.routes import main from iblog.errors.handlers import errors app.register_blueprint(users) app.register_blueprint(posts) app.register_blueprint(main) app.register_blueprint(errors) google_bp = make_google_blueprint( offline=True, redirect_url='/google_login', scope=[ "https://www.googleapis.com/auth/plus.me", "openid https://www.googleapis.com/auth/userinfo.email", ]) app.register_blueprint(google_bp, url_prefix="/google_login") return app
def _register_blueprints(app: Flask): if not app.config["CG_ENABLE_ADMIN"]: return oauth_bp = make_google_blueprint( client_id=app.config["GOOGLE_OAUTH_CLIENT_ID"], client_secret=app.config["GOOGLE_OAUTH_CLIENT_SECRET"], scope=["openid", "https://www.googleapis.com/auth/userinfo.email"], ) @oauth_authorized.connect_via(oauth_bp) def logged_in(blueprint, token): """Called when the user logs in via Google OAuth.""" resp = google.get("/oauth2/v1/userinfo?alt=json") assert resp.ok, resp.text user_data = resp.json() session["user_email"] = user_data["email"] app.register_blueprint(api.BLUEPRINT) _register_admin_views() app.register_blueprint(invoices.BLUEPRINT, url_prefix="/invoices") app.register_blueprint(oauth_bp, url_prefix="/login") @app.route("/") def index(): return redirect(url_for("admin.index")) @app.route("/logout") def logout(): """Log out the user.""" session["user_email"] = None return redirect(url_for("index"))
def register_blueprints(app: Flask): oauth_bp = make_google_blueprint( client_id=app.config['GOOGLE_OAUTH_CLIENT_ID'], client_secret=app.config['GOOGLE_OAUTH_CLIENT_SECRET'], scope=['email', 'profile'], ) @oauth_authorized.connect_via(oauth_bp) def logged_in(blueprint, token): """Called when the user logs in via Google OAuth.""" resp = google.get('/oauth2/v1/userinfo?alt=json') assert resp.ok user_data = resp.json() session['user_email'] = user_data['email'] session['user_name'] = user_data['name'] app.register_blueprint(oauth_bp, url_prefix='/login') app.register_blueprint(api.BLUEPRINT) @app.route('/') def index(): return redirect(url_for('admin.index')) @app.route('/logout') def logout(): """Log out the user.""" session['user_email'] = None return redirect(url_for('index'))
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) app.wsgi_app = ProxyFix(app.wsgi_app) 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) # with app.test_request_context(): # db.create_all() sentry = Sentry(app) google_bp = make_google_blueprint(scope=['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'], offline=True, reprompt_consent=True, redirect_url= 'http://localhost:5000/auth/login_with_google') 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') app.register_blueprint(google_bp, url_prefix="/auth") from .operation import operation as operation_blueprint app.register_blueprint(operation_blueprint) return app
def test_blueprint_factory_offline(): google_bp = make_google_blueprint( client_id="foo", client_secret="bar", redirect_to="index", offline=True, ) assert google_bp.auto_refresh_url == "https://accounts.google.com/o/oauth2/token"
def test_blueprint_factory_scope(): google_bp = make_google_blueprint( client_id="foo", client_secret="bar", scope="customscope", redirect_to="index", ) assert google_bp.session.scope == "customscope"
def create_google_blueprint(): """ Google use default config variables GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET https://developers.google.com/identity/protocols/oauth2/scopes#google-sign-in https://flask-dance.readthedocs.io/en/latest/providers.html#module-flask_dance.contrib.facebook Default redirect uri: /google/authorized """ g_blueprint = make_google_blueprint(scope=[ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid' ]) @oauth_authorized.connect_via(g_blueprint) def google_logged_in(bp, token): if not token: flash('Fail to login with facebook') return False # resp = facebook.get('/me?fields=email,name,picture') resp = google.get("/oauth2/v2/userinfo") if resp.status_code != 200: flash('Fail to get user profile form facebook', category='error') return False """ example response { "id": "2942903842893", "email": "*****@*****.**" "name": "Firstname Lastname", "given_name": "firstname", "family_name": "lastname", "link": "https://plus.google.com/3247298347928734", "picture": "https://lh6.googleusercontent.com/asdkfjskfjsdkjf", "gender": "male", "locale": "en" } """ user_info = resp.json() try: ok = _save_and_login_user(user_id=user_info.get('id'), user_name=user_info.get('name'), email=user_info.get('email'), picture=user_info.get('picture'), token=token, provider_name=g_blueprint.name) if ok: flash("Successfully signed in with Google.") except Exception as e: current_app.logger.error( "[Flask Dance: Google] cannot save and login user %s" % str(e)) db.session.rollback() return False return g_blueprint
def test_blueprint_factory_hosted_domain(): google_bp = make_google_blueprint( client_id="foo", client_secret="bar", redirect_to="index", hosted_domain="example.com", ) assert google_bp.authorization_url_params["hd"] == "example.com"
def test_blueprint_factory_hosted_domain(): google_bp = make_google_blueprint( client_id="foo", client_secret="bar", redirect_to="index", hosted_domain="example.com", ) assert google_bp.authorization_url_params["hd"] == "example.com"
def register_blueprints(app): """Register all the blueprints with the app instance.""" app.register_blueprint(ui) app.register_blueprint(make_google_blueprint(scope=[ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/cloud-platform' ]), url_prefix='/login') return None
def __init__(self, sql): self.sql = sql self.bp = make_google_blueprint( client_id=os.environ.get("GOOGLE_OAUTH_CLIENT_ID"), client_secret=os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET"), scope=[ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email" ], hosted_domain=auth.domain)
def _make_google_blueprint(self): """Create the blueprint""" return make_google_blueprint( client_id=self.googleAuthParams.client_id, client_secret=self.googleAuthParams.client_secret, scope=[ "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email", ], offline=True)
def test_load_from_config(): app = Flask(__name__) app.secret_key = "anything" app.config["GOOGLE_OAUTH_CLIENT_ID"] = "foo" app.config["GOOGLE_OAUTH_CLIENT_SECRET"] = "bar" google_bp = make_google_blueprint(redirect_to="index") app.register_blueprint(google_bp) resp = app.test_client().get("/google") url = resp.headers["Location"] client_id = URLObject(url).query.dict.get("client_id") assert client_id == "foo"
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping(SECRET_KEY='dev', ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # configure cache buster cache_buster = CacheBuster(config={ 'extensions': ['.js', '.css'], 'hash_size': 5, }) cache_buster.init_app(app) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass # local blueprints app.register_blueprint(main_bp, url_prefix="/") for ds in datasets: app.register_blueprint(dataset.make_blueprint(ds), url_prefix="/" + ds['id']) # Google login blueprint = make_google_blueprint( client_id=app.config.get('GOOGLE_OAUTH_CLIENT_ID'), client_secret=app.config.get('GOOGLE_OAUTH_CLIENT_SECRET'), ) app.register_blueprint(blueprint, url_prefix="/login") # user handling app.before_request(add_globals) # db teardown app.teardown_appcontext(close_connection) # cli commands for admins app.cli.add_command(importer_cli) # add filter for jinja templating @app.template_filter('capfirst') def capfirst(s): return s[:1].upper() + s[1:] return app
def __init__(self, app, authorized_emails): super(GoogleOAuth, self).__init__(app) google_bp = make_google_blueprint( scope=[ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ], offline=True, reprompt_consent=True, ) app.server.register_blueprint(google_bp, url_prefix="/login") self.authorized_emails = authorized_emails
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__) goog_bp1 = make_google_blueprint( "foo1", "bar1", redirect_to="url1", backend=MemoryBackend({"access_token": "app1"}), ) app1.register_blueprint(goog_bp1) app2 = Flask(__name__) goog_bp2 = make_google_blueprint( "foo2", "bar2", redirect_to="url2", backend=MemoryBackend({"access_token": "app2"}), ) app2.register_blueprint(goog_bp2) # outside of a request context, referencing functions on the `google` object # will raise an exception with pytest.raises(RuntimeError): google.get("https://github.com") # inside of a request context, `google` should be a proxy to the correct # blueprint session with app1.test_request_context("/"): app1.preprocess_request() google.get("https://google.com") request = responses.calls[0].request assert request.headers["Authorization"] == "Bearer app1" with app2.test_request_context("/"): app2.preprocess_request() google.get("https://google.com") request = responses.calls[1].request assert request.headers["Authorization"] == "Bearer app2"
def setup(self): self.blueprint = make_google_blueprint(scope=['profile', 'email']) # setup login manager self.login_manager = LoginManager() self.login_manager.login_view = 'login' self.login_manager.anonymous_user = AnonymousUser @self.login_manager.user_loader def load_user(user_id): return self.User.query.get(int(user_id)) @oauth_authorized.connect_via(self.blueprint) def google_loggedin(blueprint, token, this=self): """Create/login local user on successful OAuth login.""" if not token: flash("Failed to log in with {}".format(blueprint.name), 'danger') return redirect(url_for('index')) # figure out who the user is resp = blueprint.session.get('/oauth2/v1/userinfo?alt=json') if resp.ok: userinfo = resp.json() # check if the user is whitelisted email = userinfo['email'] if not this.confirm(email): flash("email not whitelisted: {}".format(email), 'danger') return redirect(url_for('index')) user = this.User.query.filter_by(google_id=userinfo['id']).first() if user: user.name = userinfo['name'] user.avatar = userinfo['picture'] user.email = email else: user = this.User(google_id=userinfo['id'], name=userinfo['name'], avatar=userinfo['picture'], email=email) this.manager.add(user) this.manager.commit() login_user(user) flash('Successfully signed in with Google', 'success') else: message = "Failed to fetch user info from {}".format(blueprint.name) flash(message, 'danger') next_url = session.pop('next_url', None) return redirect(next_url or url_for('index'))
def __init__(self, app, authorized_emails, additional_scopes=None,redirect_url=None): super(GoogleOAuth, self).__init__(app) google_bp = make_google_blueprint( scope=[ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ] + (additional_scopes if additional_scopes else []), offline=True, reprompt_consent=True, redirect_url=redirect_url, ) app.server.register_blueprint(google_bp, url_prefix="/login") self.authorized_emails = authorized_emails
def __init__(self, app, authorized_emails): Auth.__init__(self, app) app.server.wsgi_app = ProxyFix(app.server.wsgi_app) app.server.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit") app.server.config["GOOGLE_OAUTH_CLIENT_ID"] = os.environ.get("GOOGLE_OAUTH_CLIENT_ID") app.server.config["GOOGLE_OAUTH_CLIENT_SECRET"] = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET") google_bp = make_google_blueprint( scope=["profile", "email"], offline=True, reprompt_consent=True, ) app.server.register_blueprint(google_bp, url_prefix="/login") self.authorized_emails = authorized_emails
def test_blueprint_factory(): google_bp = make_google_blueprint( client_id="foo", client_secret="bar", redirect_to="index", ) assert isinstance(google_bp, OAuth2ConsumerBlueprint) assert google_bp.session.scope == ["profile"] assert google_bp.session.base_url == "https://www.googleapis.com/" assert google_bp.session.client_id == "foo" assert google_bp.client_secret == "bar" assert google_bp.authorization_url == "https://accounts.google.com/o/oauth2/auth" assert google_bp.token_url == "https://accounts.google.com/o/oauth2/token"
def route_factory(): """ Initialize blueprints in a factory in order to not to deal with circular imports """ from cloudcourseproject.src.authorization.routes import authorization from cloudcourseproject.src.user.routes import user from cloudcourseproject.src.article.routes import article from cloudcourseproject.src.admin.routes import admin google_bp = make_google_blueprint(scope=["profile", "email"], redirect_url="/") app.register_blueprint(google_bp, url_prefix="/login") app.register_blueprint(authorization) app.register_blueprint(user) app.register_blueprint(article) app.register_blueprint(admin)
def create_app(): invoice_app = Flask(__name__) invoice_app.config['SECRET_KEY'] = 'secret' blueprint = make_google_blueprint( client_id=os.getenv('CLIENT_ID', 'client_id'), client_secret=os.getenv('CLIENT_SECRET', 'client_secret'), ) invoice_app.register_blueprint(blueprint, url_prefix="/login") Bootstrap(invoice_app) HomeView.register(invoice_app) InvoiceView.register(invoice_app) return invoice_app
def load_google_authentication(app): blueprint = make_google_blueprint( client_id=app.config['GOOGLE_CLIENT_ID'], client_secret=app.config['GOOGLE_CLIENT_SECRET'], scope=["profile", "email"], offline=True) app.register_blueprint(blueprint, url_prefix="/login") # create/login local user on successful OAuth login @oauth_authorized.connect_via(blueprint) def google_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("/plus/v1/people/me") # app.logger.debug(resp.json()) # TODO Extract the position of the account email if resp.ok: email = resp.json()['emails'][0]['value'] avatar = resp.json()['image']['url'] existing_user = user_datastore.find_user(email=email) if not existing_user: # create a user existing_user = user_datastore.create_user(username=email, email=email, password=str( uuid.uuid4())) existing_user.has_auto_generated_password = True existing_user.avatar = avatar user_datastore.commit() login_user(existing_user) flash("Successfully signed in with Google", 'success') else: msg = "Failed to fetch user info from {name}".format( name=blueprint.name) flash(msg, category="error") @blueprint.record_once def on_load(state): """ http://stackoverflow.com/a/20172064/742173 :param state: state """ state.app.login_manager.blueprint_login_views[ blueprint.name] = 'google.login' return blueprint
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__) goog_bp1 = make_google_blueprint( "foo1", "bar1", redirect_to="url1", backend=MemoryBackend({"access_token": "app1"}), ) app1.register_blueprint(goog_bp1) app2 = Flask(__name__) goog_bp2 = make_google_blueprint( "foo2", "bar2", redirect_to="url2", backend=MemoryBackend({"access_token": "app2"}), ) app2.register_blueprint(goog_bp2) # outside of a request context, referencing functions on the `google` object # will raise an exception with pytest.raises(RuntimeError): google.get("https://github.com") # inside of a request context, `google` should be a proxy to the correct # blueprint session with app1.test_request_context("/"): app1.preprocess_request() google.get("https://google.com") request = responses.calls[0].request assert request.headers["Authorization"] == "Bearer app1" with app2.test_request_context("/"): app2.preprocess_request() google.get("https://google.com") request = responses.calls[1].request assert request.headers["Authorization"] == "Bearer app2"
def test_offline(): app = Flask(__name__) app.secret_key = "backups" goog_bp = make_google_blueprint("foo", "bar", offline=True) app.register_blueprint(goog_bp) with app.test_client() as client: resp = client.get( "/google", base_url="https://a.b.c", follow_redirects=False, ) # check that there is a `access_type=offline` query param in the redirect URL assert resp.status_code == 302 location = URLObject(resp.headers["Location"]) assert location.query_dict["access_type"] == "offline"
def __init__(self, application, oauth_client_id=None, oauth_client_secret=None, whitelist=False, domain=None): self.domain = domain self.whitelisted = whitelist application.register_blueprint( make_google_blueprint( client_id=(os.getenv("GOOGLE_OAUTH_CLIENT_ID") if oauth_client_id is None else oauth_client_id), client_secret=(os.getenv("GOOGLE_OAUTH_CLIENT_SECRET") if oauth_client_secret is None else oauth_client_secret), offline=True, scope=["profile", "email"] # TODO: Extract out as a parameter ), url_prefix="/login" ) application.before_request(self.authentication)
def test_hd(): app = Flask(__name__) app.secret_key = "backups" goog_bp = make_google_blueprint("foo", "bar", hosted_domain="example.com") app.register_blueprint(goog_bp) with app.test_client() as client: resp = client.get( "/google", base_url="https://a.b.c", follow_redirects=False, ) # check that there is a `hd=example.com` query param in the redirect URL assert resp.status_code == 302 location = URLObject(resp.headers["Location"]) assert location.query_dict["hd"] == "example.com"
def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) app.logger.info('FLASK_CONFIG %s', os.getenv('FLASK_CONFIG')) app.logger.info('FLASK_DEBUG %s', os.getenv('FLASK_DEBUG')) stripe_mode = 'LIVE!!' if app.config['STRIPE_LIVE'] == '1' else 'TEST' app.logger.info('@@@ Stripe mode @@@ is %s', stripe_mode) app.jinja_env.globals.update(len=len) bootstrap.init_app(app) db.init_app(app) login_manager.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) # google google_blueprint = make_google_blueprint( scope=[ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "openid", ], client_id=app.config['GOOGLE_CLIENT_ID'], client_secret=app.config['GOOGLE_CLIENT_SECRET'], ) app.register_blueprint(google_blueprint, url_prefix="/login") # twitter twitter_blueprint = make_twitter_blueprint( api_key=app.config['TWITTER_API_KEY'], api_secret=app.config['TWITTER_API_SECRET'], ) app.register_blueprint(twitter_blueprint, url_prefix="/login") # app.logger.info('url_map= %s', app.url_map) # app.logger.info('config= %s', app.config) return app
def init_app(app): from backend.schema import schema from backend.models import User @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) google_bp = make_google_blueprint(scope=[ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email", "openid" ]) app.register_blueprint(google_bp, url_prefix="/login") os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' @app.route("/") def index(): if not google.authorized: return redirect(url_for("google.login")) try: resp = google.get("/oauth2/v1/userinfo") except TokenExpiredError: return redirect(url_for("google.login")) assert resp.ok, resp.text auth_email = resp.json()['email'] user = User.query.filter(User.email == auth_email).first() if not user: user = User(name=resp.json()['given_name'], email=auth_email) db.session.add(user) db.session.commit() login_user(user) return render_template('index.html') @app.route("/logout") @login_required def logout(): logout_user() return redirect('/') app.add_url_rule("/graphql", view_func=GraphQLView.as_view("graphql", schema=schema, graphiql=True))
def create_app(object_name=Config): app = Flask(__name__) app.config.from_object(Config) google_bp = make_google_blueprint( client_id=os.environ.get('GOOGLE_CLIENT_ID'), client_secret=os.environ.get('GOOGLE_SECRET'), scope=[ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/plus.me" ]) app.register_blueprint(google_bp, url_prefix="/google-login") db.init_app(app) login_manager.init_app(app) migrate = Migrate(app, db) return app
def test_offline_reprompt(): app = Flask(__name__) app.secret_key = "backups" goog_bp = make_google_blueprint( "foo", "bar", offline=True, reprompt_consent=True, ) app.register_blueprint(goog_bp) with app.test_client() as client: resp = client.get( "/google", base_url="https://a.b.c", follow_redirects=False, ) assert resp.status_code == 302 location = URLObject(resp.headers["Location"]) assert location.query_dict["access_type"] == "offline" assert location.query_dict["approval_prompt"] == "force"
def create_module(app, **kwargs): from app.auth.routes import auth_blueprint login.init_app(app) login.login_view = "/login" login.login_message = "Prosím přihlašte se." google_blueprint = make_google_blueprint( client_id=app.config.get("GOOGLE_CLIENT_ID"), client_secret=app.config.get("GOOGLE_CLIENT_SECRET"), scope=[ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ], ) app.register_blueprint(google_blueprint, url_prefix="/login") app.register_blueprint(auth_blueprint)
def make_google_blueprint(): """ Following the instructions at https://flask-dance.readthedocs.io/en/latest/providers.html#module-flask_dance.contrib.google """ arg_name2config_key = { "client_id": "GOOGLE_CLIENT_ID", "client_secret": "GOOGLE_SECRET", } config_kwargs = populate_config_kwargs(arg_name2config_key, app.config) kwargs = {"scope": ["profile", "email"], "redirect_to": "oauth_status"} blueprint = google_dance.make_google_blueprint(**config_kwargs, **kwargs) blueprint.storage = flask_dance.consumer.storage.sqla.SQLAlchemyStorage(fra_back.models.OAuth, master_session) return blueprint
def setup(app): blueprint = make_google_blueprint( client_id=app.config['GOOGLE_CLIENT_ID'], client_secret=app.config['GOOGLE_CLIENT_SECRET'], scope=[ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email", ], ) app.register_blueprint(blueprint, url_prefix="/login") # Copied (and modified) from # https://github.com/spotify/gimme/blob/master/gimme/views.py#L52-L94 # I think this shouldn't be necessary. See # https://github.com/singingwolfboy/flask-dance/issues/143#issuecomment-416781772 # for more information. @app.errorhandler(oauthlib.oauth2.rfc6749.errors.TokenExpiredError) def token_expired(_): del app.blueprints['google'].token return redirect(url_for('.index'))
from flask import Flask, redirect, url_for from flask_dance.contrib.google import make_google_blueprint, google import os app = Flask(__name__) app.secret_key = os.environ['FLASK_SECRET'] blueprint = make_google_blueprint( client_id=os.environ['GOOGLE_ID'], client_secret=os.environ['GOOGLE_SECRET'], scope=["profile", "email"] ) app.register_blueprint(blueprint, url_prefix="/login") @app.route("/") def index(): if not google.authorized: return redirect(url_for("google.login")) resp = google.get("/plus/v1/people/me") assert resp.ok, resp.text return "You are {email} on Google".format(email=resp.json()["emails"][0]["value"]) if __name__ == "__main__": app.run(debug=True,)
FacebookFlaskDanceProvider, FlaskProviderUserInfo, GoogleFlaskDanceProvider, MockFlaskDanceProvider, ) from ..models.intervention import Intervention, UserIntervention from ..models.login import login_user from ..models.role import ROLE from ..models.user import User, add_user, current_user, get_user_or_abort from .crossdomain import crossdomain auth = Blueprint('auth', __name__) google_blueprint = make_google_blueprint( scope=[ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'], login_url='/login/google/', ) facebook_blueprint = make_facebook_blueprint( scope=['email', 'user_birthday', 'user_gender'], login_url='/login/facebook/', ) @auth.route('/test/oauth') def oauth_test_backdoor(): """unit test backdoor API that handles oauth related tasks for unit tests. When a test needs to login or test oauth related logic
from oauth import OAuthSignIn os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' app = Flask(__name__) app.config['SECRET_KEY'] = 'top secret!' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' facebook_bp = make_facebook_blueprint( client_id="trololo", client_secret="ololo", scope=['email'], redirect_url="/callback/facebook" ) google_bp = make_google_blueprint( client_id="trololo", client_secret="ololo", offline=True, reprompt_consent=True, scope=["email"], redirect_url="/callback/google" ) app.register_blueprint(facebook_bp, url_prefix="/login") app.register_blueprint(google_bp, url_prefix="/login") db = SQLAlchemy(app) lm = LoginManager(app) lm.login_view = 'index' class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) social_id = db.Column(db.String(64), nullable=False, unique=True)
from flask_dance.consumer.backend.sqla import SQLAlchemyBackend from flask_sqlalchemy import SQLAlchemy from flask_cache import Cache from contextlib import contextmanager from .secrets import * import warnings from flask.exthook import ExtDeprecationWarning warnings.simplefilter('ignore', ExtDeprecationWarning) app = Flask(__name__) # Flask-Dance data app.secret_key = secrets['secret_key'] blueprint = make_google_blueprint( client_id=secrets['login_id'], client_secret=secrets['login_secret'], scope=["profile", "email"], reprompt_consent=True ) # SQLAlchemy Setup app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2:///sortport' database = SQLAlchemy(app, session_options={'expire_on_commit': False}) # Flask Cache cache = Cache(app, config={'CACHE_TYPE': 'simple'}) from app import views, models, api
""" ).format(keys=", ".join(cfg_needs_replacing)) print(message, file=sys.stderr) sys.exit(1) # Use Flask-Dance to automatically set up the OAuth endpoints for Google. # For more information, check out the documentation: http://flask-dance.rtfd.org google_bp = make_google_blueprint( scope=[ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "https://mail.google.com/", "https://www.google.com/m8/feeds", "https://www.googleapis.com/auth/calendar", ], offline=True, # this allows you to get a refresh token from Google redirect_to="after_google", # If you get a "missing Google refresh token" error, uncomment this line: # reprompt_consent=True, # That `reprompt_consent` argument will force Google to re-ask the user # every single time if they want to connect with your application. # Google will only send the refresh token if the user has explicitly # given consent. ) app.register_blueprint(google_bp, url_prefix="/login") # Teach Flask how to find out that it's behind an ngrok proxy app.wsgi_app = ProxyFix(app.wsgi_app) # Define what Flask should do when someone visits the root URL of this website. @app.route("/")
def _make_app(*args, **kwargs): app = Flask(__name__) app.secret_key = "whatever" blueprint = make_google_blueprint(*args, **kwargs) app.register_blueprint(blueprint) return app
def test_blueprint_factory_offline(): google_bp = make_google_blueprint( client_id="foo", client_secret="bar", redirect_to="index", offline=True ) assert google_bp.auto_refresh_url == "https://accounts.google.com/o/oauth2/token"
import os from werkzeug.contrib.fixers import ProxyFix from flask import Flask, redirect, url_for from flask_dance.contrib.google import make_google_blueprint, google from raven.contrib.flask import Sentry app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) sentry = Sentry(app) 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("/plus/v1/people/me") assert resp.ok, resp.text return "You are {email} on Google".format(email=resp.json()["emails"][0]["value"]) if __name__ == "__main__": app.run()