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)
def test_blueprint_factory(): facebook_bp = make_facebook_blueprint( client_id="foo", client_secret="bar", scope="user:email", redirect_to="index" ) assert isinstance(facebook_bp, OAuth2ConsumerBlueprint) assert facebook_bp.session.scope == "user:email" assert facebook_bp.session.base_url == "https://graph.facebook.com/" assert facebook_bp.session.client_id == "foo" assert facebook_bp.client_secret == "bar" assert facebook_bp.authorization_url == "https://www.facebook.com/dialog/oauth" assert facebook_bp.token_url == "https://graph.facebook.com/oauth/access_token"
def test_load_from_config(): app = Flask(__name__) app.secret_key = "anything" app.config["FACEBOOK_OAUTH_CLIENT_ID"] = "foo" app.config["FACEBOOK_OAUTH_CLIENT_SECRET"] = "bar" facebook_bp = make_facebook_blueprint(redirect_to="index") app.register_blueprint(facebook_bp) resp = app.test_client().get("/facebook") url = resp.headers["Location"] client_id = URLObject(url).query.dict.get("client_id") assert client_id == "foo"
def test_blueprint_factory(): facebook_bp = make_facebook_blueprint(client_id="foo", client_secret="bar", scope="user:email", redirect_to="index") assert isinstance(facebook_bp, OAuth2ConsumerBlueprint) assert facebook_bp.session.scope == "user:email" assert facebook_bp.session.base_url == "https://graph.facebook.com/" assert facebook_bp.session.client_id == "foo" assert facebook_bp.client_secret == "bar" assert facebook_bp.authorization_url == "https://www.facebook.com/dialog/oauth" assert facebook_bp.token_url == "https://graph.facebook.com/oauth/access_token"
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__) fbbp1 = make_facebook_blueprint( "foo1", "bar1", redirect_to="url1", backend=MemoryBackend({"access_token": "app1"}), ) app1.register_blueprint(fbbp1) app2 = Flask(__name__) fbbp2 = make_facebook_blueprint( "foo2", "bar2", redirect_to="url2", backend=MemoryBackend({"access_token": "app2"}), ) app2.register_blueprint(fbbp2) # outside of a request context, referencing functions on the `facebook` object # will raise an exception with pytest.raises(RuntimeError): facebook.get("https://google.com") # inside of a request context, `facebook` should be a proxy to the correct # blueprint session with app1.test_request_context("/"): app1.preprocess_request() facebook.get("https://google.com") request = responses.calls[0].request assert request.headers["Authorization"] == "Bearer app1" with app2.test_request_context("/"): app2.preprocess_request() facebook.get("https://google.com") request = responses.calls[1].request assert request.headers["Authorization"] == "Bearer app2"
def register_facebook_blueprint(app): # Facebook client_id = app.config.get('OAUTH_CONFIG')['FACEBOOK']['client_id'] client_secret = app.config.get('OAUTH_CONFIG')['FACEBOOK']['client_secret'] facebook_blueprint = make_facebook_blueprint( client_id=client_id, client_secret=client_secret, scope=["public_profile", "email"]) facebook_blueprint.backend = SQLAlchemyBackend(OAuth, db.session, user=current_user) app_token = get_facebook_app_token(app) if app_token: app.register_blueprint(facebook_blueprint, url_prefix="/login") else: print( "Facebook app token not found in config. Facebook blueprint not configured." ) # create/login local user on successful OAuth login @oauth_authorized.connect_via(facebook_blueprint) def facebook_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("/me?fields=email,name") if resp.ok: print(f"Response from facebook: {resp.json()}") username = resp.json()["email"] 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 Facebook", "success") else: print(resp.text) msg = "Failed to fetch user info from {name}".format( name=blueprint.name) flash(msg, category="error")
def create_module(app, **kwargs): bcrypt.init_app(app) oid.init_app(app) login_manager.init_app(app) jwt.init_app(app) twitter_blueprint = make_twitter_blueprint( api_key=app.config.get("TWITTER_API_KEY"), api_secret=app.config.get("TWITTER_API_SECRET")) app.register_blueprint(twitter_blueprint, url_prefix="/auth/login") facebook_blueprint = make_facebook_blueprint( client_id=app.config.get("FACEBOOK_CLIENT_ID"), client_secret=app.config.get("FACEBOOK_CLIENT_SECRET")) app.register_blueprint(facebook_blueprint, url_prefix="/auth/login") from .controllers import auth_blueprint app.register_blueprint(auth_blueprint)
def load_facebook_authentication(app): blueprint = make_facebook_blueprint( client_id=app.config['FACEBOOK_CLIENT_ID'], client_secret=app.config['FACEBOOK_CLIENT_SECRET'], scope="email" ) app.register_blueprint(blueprint, url_prefix="/login/facebook") # create/login local user on successful OAuth login @oauth_authorized.connect_via(blueprint) def facebook_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("/me?fields=id,name,email,picture") avatar = resp.json()['picture']['data']['url'] app.logger.debug(resp.json()) if resp.ok: email = resp.json()['email'] 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 Facebook", '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] = 'facebook.login' return blueprint
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='https://www.bestchoicehub.com/auth/login_with_google') facebook_bp = make_facebook_blueprint( scope=['email'], redirect_url='https://www.bestchoicehub.com/auth/login_with_facebook', client_id='', client_secret='') 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") app.register_blueprint(facebook_bp, url_prefix="/auth") from .operation import operation as operation_blueprint app.register_blueprint(operation_blueprint) return app
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", "openid" ], redirect_to='google_login') facebook_bp = make_facebook_blueprint( client_id=os.environ.get('FACEBOOK_CLIENT_ID'), client_secret=os.environ.get('FACEBOOK_SECRET'), scope=["public_profile", "email"], redirect_to='facebook_login') app.register_blueprint(google_bp, url_prefix="/google-login") app.register_blueprint(facebook_bp, url_prefix='/facebook-login') db.init_app(app) login_manager.init_app(app) migrate = Migrate(app, db) return app
def test_rerequest_declined_scopes(rerequest): """ Tests that the rerequest_declined_permissions flag in the facebook blueprint sends toggles the header reasking oauth permissions as detailed in the facebook docs https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#reaskperms Tests both that the header is set with the flag (rerequest=True) and that it is missing without the flag (rerequest=False) """ app = Flask(__name__) app.secret_key = "backups" bp = make_facebook_blueprint(scope='user_posts', rerequest_declined_permissions=rerequest) app.register_blueprint(bp) with app.test_client() as client: resp = client.get( "/facebook", base_url="https://a.b.c", follow_redirects=False, ) assert resp.status_code == 302 location = URLObject(resp.headers["Location"]) if rerequest: assert location.query_dict["auth_type"] == "rerequest" else: assert "auth_type" not in location.query_dict
from kimsbible import app import os from flask import Flask, redirect, url_for, session from flask_dance.contrib.facebook import make_facebook_blueprint, facebook app.config["FACEBOOK_OAUTH_CLIENT_ID"] = app.config["FACEBOOK_OAUTH_CLIENT_SECRET"] = os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = facebook_bp = make_facebook_blueprint( redirect_url="/oauth/facebook/" ) app.register_blueprint( facebook_bp, url_prefix="/login", ) def getAuthorizedInfo(): result = '<div id="authorized">' if 'username' in session: result += '<img src="/static/img/' + session['oauth_source'] + '.png" height="18px" width="18px">' + session['username'] + ' (<a href="/oauth/logout/">로그아웃</a>)</div>' return result else: result += '<a href="/oauth/facebook/"><img src="/static/img/facebook.png" height="30px" width="30px"></a></div>' return result @app.route("/oauth/facebook/") def oauth_facebook(): if not facebook.authorized: return redirect(url_for("facebook.login")) resp = facebook.get("/me")
# Twitter connection @app.route("/twitter") def twitter_login(): if not facebook.authorized and not twitter.authorized: return redirect(url_for("twitter.login")) return redirect(url_for("profile")) # FB connector # app.config["FACEBOOK_OAUTH_CLIENT_ID"] = "3468111173224517" # app.config["FACEBOOK_OAUTH_CLIENT_SECRET"] = "7ea8279bf9d5de409cdf843e58ba0409" app.config["FACEBOOK_OAUTH_CLIENT_ID"] = "141269584858" app.config["FACEBOOK_OAUTH_CLIENT_SECRET"] = "f9343613c08bce71b9540819a11478fd" 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",
import ldap from flask import request, render_template, flash, redirect, url_for, \ session, Blueprint, g from flask_login import current_user, login_user, logout_user, \ login_required from flask_dance.contrib.facebook import make_facebook_blueprint, facebook from flask_dance.contrib.google import make_google_blueprint, google from flask_dance.contrib.twitter import make_twitter_blueprint, twitter from my_app import db, login_manager, get_ldap_connection from my_app.auth.models import User, RegistrationForm, LoginForm auth = Blueprint('auth', __name__) facebook_blueprint = make_facebook_blueprint(scope='email', redirect_to='auth.facebook_login') google_blueprint = make_google_blueprint(scope=[ "openid", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" ], redirect_to='auth.google_login') twitter_blueprint = make_twitter_blueprint(redirect_to='auth.twitter_login') @auth.route("/ldap-login", methods=['GET', 'POST']) def ldap_login(): if current_user.is_authenticated: flash('Your are already logged in.', 'info') return redirect(url_for('auth.home')) form = LoginForm() if form.validate_on_submit():
blueprint = make_github_blueprint( client_id='3191f9252554d100aab6', client_secret='14262898173171c1b700098aa585a937dadfd53f') app.register_blueprint(blueprint, url_prefix='/login') google_blueprint = make_google_blueprint( client_secret='4PWNSUIOUAv8bH6GbTjRkLEP', client_id= '38792819611-bh2nbr8nml0iiilvltgu3vga0jh74cp9.apps.googleusercontent.com', scope=["profile", "email"]) app.register_blueprint(google_blueprint, url_prefix="/login") facebook_blueprint = make_facebook_blueprint( client_id='675029432922733', client_secret='1686fe832c931fa99b199e6431618e00') app.register_blueprint(facebook_blueprint, url_prefix="/login") # @app.route('/github', methods=['GET', 'POST']) # def 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() # login_name = account_info_json["login"] # return "hello {}".format(login_name)
Oauth, db.session, user=current_user, user_required=False) google_blueprint = make_google_blueprint( client_id=GOOGLE_CLIENT_ID, client_secret=GOOGLE_CLIENT_SECRETS, scope=['profile', 'email']) google_blueprint.backend = SQLAlchemyBackend( Oauth, db.session, user=current_user, user_required=False) facebook_blueprint = make_facebook_blueprint( client_id=FACEBOOK_OAUTH_CLIENT_ID, client_secret=FACEBOOK_OAUTH_CLIENT_SECRET, scope=['profile', 'email']) facebook_blueprint.backend = SQLAlchemyBackend( Oauth, db.session, user=current_user, user_required=False) client = boto3.client('s3', aws_access_key_id=AWS_CLIENT_ACCESS_KEY, aws_secret_access_key=AWS_CLIENT_SECRET_KEY) @staticPages.route('/') def home(): wine_list = db.session.query(Wine).order_by(Wine.created_on.desc()).limit(6)
) @Auth.route('/logout') def logout(): current_app.logger.debug("UUID:{} logged out.".format(current_user.UUID)) logout_user() flash("Logged out.") return redirect(url_for('pages.index')) # Facebook OAuth blueprint FacebookOAuth = make_facebook_blueprint( scope=[ 'email', 'user_friends', 'user_education_history', ], redirect_to='dashboard.me' ) FacebookOAuth.url_prefix = '/auth' # create/login local user on successful OAuth login @oauth_authorized.connect_via(FacebookOAuth) def facebook_logged_in(blueprint, token): db = g.db if not token: msg = "Failed to log in with {name}".format(name=blueprint.name) flash(msg) current_app.logger.error(msg)
users_blueprint = Blueprint('auth', __name__, template_folder='templates') github_blueprint = make_github_blueprint( client_id=app.config.get('GITHUB_ID'), client_secret=app.config.get('GITHUB_SECRET'), ) google_blueprint = make_google_blueprint( client_id=app.config.get('GOOGLE_ID'), client_secret=app.config.get('GOOGLE_SECRET'), scope=["profile", "email"]) twitter_blueprint = make_twitter_blueprint( api_key=app.config.get('TWITTER_API_KEY'), api_secret=app.config.get('TWITTER_API_SECRET')) facebook_blueprint = make_facebook_blueprint( client_id=app.config.get('FACEBOOK_APP_ID'), client_secret=app.config.get('FACEBOOK_APP_SECRET')) # setup SQLAlchemy backend github_blueprint.backend = SQLAlchemyBackend(models.OAuth, db.session, user=current_user) google_blueprint.backend = SQLAlchemyBackend(models.OAuth, db.session, user=current_user) twitter_blueprint.backend = SQLAlchemyBackend(models.OAuth, db.session, user=current_user, user_required=False) facebook_blueprint.backend = SQLAlchemyBackend(models.OAuth, db.session,
from flask import Flask, flash, redirect from flask_login import current_user, login_user from flask_dance.contrib.facebook import make_facebook_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 src import db from src.models import Member, OAuth, Token import uuid blueprint = make_facebook_blueprint( storage=SQLAlchemyStorage(OAuth, db.session, user=current_user)) # create/login local user on successful OAuth login @oauth_authorized.connect_via(blueprint) def facebook_logged_in(blueprint, token): if not token: flash("Failed to log in.", category="error") return False resp = blueprint.session.get("/me") if not resp.ok: msg = "Failed to fetch user info." flash(msg, category="error") return False info = resp.json() user_id = info["id"] print('info', info)
from flask import Flask, redirect, url_for, render_template, flash from flask_dance.contrib.facebook import make_facebook_blueprint from flask_dance.contrib.google import make_google_blueprint import os from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user 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)
from flask import session, redirect, url_for from flask_dance.consumer import OAuth2ConsumerBlueprint from flask_dance.contrib.facebook import make_facebook_blueprint,facebook from flask import Blueprint appfile6 = Blueprint('appfile6', __name__) batman_example = make_facebook_blueprint( client_id="432901240580973", client_secret="7378ae063eb18e3f3d40893c95c3ef0c", redirect_url=('/facebook') ) @appfile6.route("/logoutfacebook") def logoutfacebook(): token = batman_example.token["access_token"] if (facebook.token): resp = facebook.post( # "https://graph.facebook.com/oauth/access_token/DELETE", "https://www.facebook.com/v3.2/dialog/oauth/DELETE", params={"access_token": token, "redirect_uri": "http://localhost:5000", "client_id":session["username"]}, headers={"Content-Type": "application/x-www-form-urlencoded"} ) del facebook.token
from flask import Flask, redirect, url_for, jsonify from werkzeug.contrib.fixers import ProxyFix from flask_dance.contrib.facebook import make_facebook_blueprint, facebook app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) app.secret_key = "supersekrit" #Just your personal App key. blueprint = make_facebook_blueprint( client_id="*************", #Put Your App ID client_secret="***************", #Put Your App Secret scope=[ 'user_birthday' ] #Define the list you want to access of user's info they will be prompted to allow. Get the list from fb developer's page ) app.register_blueprint(blueprint, url_prefix="/login") @app.route("/signup/fb") def fbSignup(): if not facebook.authorized: return redirect(url_for("facebook.login")) else: return "<h2>logged in to fb</h2>" @app.route('/', methods=['GET']) def getUserNameOfGithub(): if facebook.authorized: resp = facebook.get("/me?fields=gender,birthday")
google_blueprint = make_google_blueprint( client_id="640840633381-8rrcgg5r9hru2al5e853jq95valimmd5.apps.googleusercontent.com", client_secret="YvDSgKVfGEM_nLblFbBPESZp", scope=[ "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ], offline=True, ) facebook_blueprint = make_facebook_blueprint( client_id="1145745515594684", client_secret="350d8feaa14aa1a37212a8b3d4dd2694", scope=[ "public_profile", "email" ], ) app.register_blueprint(google_blueprint, url_prefix="/google_login") app.register_blueprint(facebook_blueprint, url_prefix="/facebook_login") pusher = Pusher( app_id='660232', key='9ced8d8f4b58d86d28c2', secret='8b3a15b1a4e6f0334ba6', cluster='us2', ssl=True )
from flask import Flask, url_for, redirect,render_template from flask_dance.contrib.facebook import make_facebook_blueprint,facebook import ast app = Flask(__name__) app.config['SERVER_NAME'] = 'localhost:5000' app.secret_key = "<ISHOULDBESOMETHING>" batman_example = make_facebook_blueprint( client_id="432901240580973", client_secret="7378ae063eb18e3f3d40893c95c3ef0c", ) app.register_blueprint(batman_example, url_prefix="/login") print(dir(make_facebook_blueprint())) @app.route("/") def index(): if not batman_example.session.authorized: return redirect(url_for("facebook.login")) resp = batman_example.session.get("me") dic=ast.literal_eval(resp.text) print(dic) print(dic['name']) assert resp.ok return render_template("home.html") import os os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' if __name__ == "__main__": app.run( debug=True)
from flask_dance.consumer import oauth_authorized, oauth_error from flask_dance.consumer.backend.sqla import SQLAlchemyBackend from flask_dance.contrib.facebook import make_facebook_blueprint from flask_dance.contrib.github import make_github_blueprint from flask_dance.contrib.twitter import make_twitter_blueprint 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):
def _make_app(*args, **kwargs): app = Flask(__name__) app.secret_key = "whatever" blueprint = make_facebook_blueprint(*args, **kwargs) app.register_blueprint(blueprint) return app
from flask_dance.contrib.facebook import make_facebook_blueprint, facebook from models.users.views import user_blueprint from models.users.user import User from models.admins.views import admin_blueprint from common.database import Database from common.utils import login_required, admin_required, get_items_from_ajax import time import os import json os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1" app = Flask(__name__) app.secret_key = "secret" blueprint = make_facebook_blueprint(client_id=FACEBOOK_APP_ID, client_secret=FACEBOOK_APP_SECRET) app.register_blueprint(user_blueprint, url_prefix="/user") app.register_blueprint(blueprint, url_prefix="/login") app.register_blueprint(admin_blueprint, url_prefix="/admin") # this function will run initially (i.e when the app is executed) @app.before_first_request def init_db(): Database.init() @app.route("/") @login_required def index():
def create_app(test_config=None): os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # create and configure the app app = Flask(__name__, instance_relative_config=True) with open("credentials/JWTSecretKeys.txt", 'r') as f: data = f.read() app.config.from_mapping( SECRET_KEY=data, DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) app.config['PROPAGATE_EXCEPTIONS'] = True app.config['JWT_TOKEN_LOCATION'] = ['headers', 'cookies'] app.config['JWT_COOKIE_CSRF_PROTECT'] = False app.config['JWT_COOKIE_SECURE'] = False app.config['JWT_SESSION_COOKIE'] = False jwt_manager = JWTManager(app) with open("credentials/DatabaseConnectionString.txt", 'r') as f: data = f.read() data = json.loads(data) app.config['MYSQL_USER'] = data['DB_USERNAME'] app.config['MYSQL_PASSWORD'] = data['DB_PASSWORD'] app.config['MYSQL_HOST'] = data['DB_HOST'] app.config['MYSQL_DB'] = data['DB_NAME'] 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) '''facebook_bp = make_facebook_blueprint( client_id = '', client_secret = '', #redirect_url = '' scope='email' ) app.register_blueprint(facebook_bp,url_prefix='/login') ''' with open("credentials/GoogleAPIkeys.txt", 'r') as f: data = f.read() info = data.splitlines() google_bp = make_google_blueprint( client_id=info[0], client_secret=info[1], scope=["https://www.googleapis.com/auth/userinfo.email", "openid", "https://www.googleapis.com/auth/userinfo.profile"], ) app.register_blueprint(google_bp, url_prefix='/login') # ensure the instance folder exists ''' @oauth_authorized.connect_via(facebook_bp) def facebook_logged_in(blueprint, token): if facebook.authorized: fb=facebook.get('me?fields=id,email,name,picture').json() return auth.new_facebook_login(fb['id'], fb['name'], fb['email'], fb['picture']['data']['url']) ''' from . import auth app.register_blueprint(auth.bp) @oauth_authorized.connect_via(google_bp) def logged_in(blueprint, token): resp_json = google.get("/oauth2/v2/userinfo").json() return auth.new_google_login(resp_json["name"], token["id_token"], resp_json["email"], resp_json['picture'], resp_json['id']) with open("credentials/FacebookAPIkeys.txt", 'r') as f: data = f.read() infofb = data.splitlines() facebook_bp = make_facebook_blueprint( client_id=infofb[0], client_secret=infofb[1], scope='email' ) app.register_blueprint(facebook_bp, url_prefix='/login') @oauth_authorized.connect_via(facebook_bp) def facebook_logged_in(blueprint, token): if facebook.authorized: fb = facebook.get('me?fields=id,email,name,picture').json() return auth.new_facebook_login(fb['id'], fb['name'], fb['email'], fb['picture']['data']['url']) try: os.makedirs(app.instance_path) except OSError: pass from . import db db.init_app(app) from . import leaderboard app.register_blueprint(leaderboard.bp) from . import index app.register_blueprint(index.bp) from . import dailychallenge app.register_blueprint(dailychallenge.bp) from . import puzzleRush app.register_blueprint(puzzleRush.bp) @jwt_manager.expired_token_loader def my_expired_token_callback(): current_app.logger.warning('expired_loader activated with JWT token\n') if 'access_token_cookie' in request.cookies or 'refresh_token_cookie' in request.cookies: flash("Access Token has expired") if len(request.url) >= 16 and ('invite' in request.url or 'submit' in request.url): index = request.url.find('potm.rocks') link = request.url[index + 11:] session['url_saved'] = link if 'AJAX' in request.headers: current_app.logger.warning('AJAX called in expired') session.clear() response = redirect(url_for('index.index')) unset_refresh_cookies(response) unset_jwt_cookies(response) return response session.clear() response = redirect(url_for('index.index')) unset_refresh_cookies(response) unset_jwt_cookies(response) return response @jwt_manager.invalid_token_loader def my_invalid_token_callback(msg): current_app.logger.warning('invalid_loader activated with JWT token\n') if 'access_token_cookie' in request.cookies or 'refresh_token_cookie' in request.cookies: flash("Access Token is invalid") if len(request.url) >= 16 and ('invite' in request.url or 'submit' in request.url): index = request.url.find('potm.rocks') link = request.url[index + 11:] session['url_saved'] = link if 'AJAX' in request.headers: current_app.logger.warning('AJAX called in invalid') return jsonify(redirect=url_for('index.index')), 200 session.clear() response = redirect(url_for('index.index')) unset_refresh_cookies(response) unset_jwt_cookies(response) return redirect(url_for('index.index'), 302) @jwt_manager.unauthorized_loader def my_unauthorized_callback(msg): current_app.logger.warning('unauthorized_loader activated with JWT token\n') if 'access_token_cookie' in request.cookies or 'refresh_token_cookie' in request.cookies: flash("Unauthorized") if len(request.url) >= 16 and ('invite' in request.url or 'submit' in request.url): index = request.url.find('potm.rocks') link = request.url[index + 11:] session['url_saved'] = link if 'AJAX' in request.headers: current_app.logger.warning('AJAX called in unauthorized') return jsonify(redirect=url_for('index.index')), 200 session.clear() response = redirect(url_for('index.index')) unset_refresh_cookies(response) unset_jwt_cookies(response) return redirect(url_for('index.index'), 302) return app
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 this API will likely be used. """ def login_test_user_using_session(user_id): session['id'] = user_id user = current_user() login_user(user, 'password_authenticated')
from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from flask_dance.contrib.facebook import make_facebook_blueprint, facebook from flask_dance.contrib.google import make_google_blueprint, google app = Flask(__name__) app.config.from_object(Config) login = LoginManager(app) login.login_view = 'login' facebook_blueprint = make_facebook_blueprint( client_id='433391737423638', client_secret='19ecf5a071d73202cb10701c94dfe5de', redirect_url='https://cs4398-final-project.herokuapp.com/facebook_login') google_blueprint = make_google_blueprint( client_id= '535013055834-9jk2rccnrb4cr2a4equ3st7ov7fkbqur.apps.googleusercontent.com', client_secret='cKhV7gREwZ7S_MnoPjZeiuD2', redirect_url='https://cs4398-final-project.herokuapp.com/google_login') db = SQLAlchemy(app) migrate = Migrate(app, db) from app import routes, models
def init_auth_controller(app, login_manager): login_manager = login_manager fb_key = app.config['FACEBOOK_OAUTH_CLIENT_ID'] fb_secret = app.config['FACEBOOK_OAUTH_CLIENT_SECRET'] facebook_bp = make_facebook_blueprint(client_id=fb_key, client_secret=fb_secret, scope=['email'], redirect_url='/callback/facebook') app.register_blueprint(facebook_bp, url_prefix='/login') @login_manager.user_loader def load_user(id): current_app.logger.info('loading user %s', id) database = current_app.cache.get('db') if database is None: current_app.logger.error('unable to retrieve database') raise Exception('database not found') users = database.get_user(id) user = None if users is not None and len(users) != 0: current_app.logger.info('user found') db_user = users[0] user = AppUser(db_user.id, db_user.username) else: current_app.logger.info('user not found in database') return user @app.route('/logout') @login_required def logout(): logout_user() return redirect('/') @app.route('/callback/<provider>') def callback(provider): current_app.logger.info('callback/provider') if not current_user.is_anonymous: return redirect('/') oauth = OAuthSignIn.get_provider(provider) social_id, username, email = oauth.callback() if social_id is None: flash('Authentication failed.') return redirect('/') resp = facebook.get('/me?fields=id,name,email,picture') def dump(obj): for attr in dir(obj): current_app.logger.info('obj.%s = %r' % (attr, getattr(obj, attr))) dump(resp) current_app.logger.info(social_id) current_app.logger.info(username) current_app.logger.info(email) if not is_in_whitelist(email): raise NotAuthorizedException(username) user = None database = current_app.cache.get('db') users = database.get_user(social_id) if users is not None and len(users) != 0: user = users[0] if not user: current_app.logger.info( 'create the user and insert it into the database.') current_app.logger.info('profile: username:%s\nsocial_id:%s\n', username, social_id) user = AppUser(social_id, username) current_app.logger.info('updating cache with user') database.insert_user(user) current_app.cache.set('db', database) login_user(AppUser(social_id, username), True) return redirect('/') @app.route('/api/username') @login_required def get_username(): try: current_app.logger.info('auth.get_username') oauth = OAuthSignIn.get_provider('facebook') social_id, username, email = oauth.callback() current_app.logger.info( 'from callback id: %s username: %s email: %s', social_id, username, email) resp = facebook.get('/me?fields=id,name,email,picture') def dump(obj): 'dump object attributes' for attr in dir(obj): current_app.logger.info('obj.%s = %r' % (attr, getattr(obj, attr))) dump(resp) if resp.status_code != 200: logout_user() return 'Unauthorized', 401 return jsonify({'username': username}) except Exception as ex: current_app.logger.info( 'failed to get username for current user %s', ex) raise ex
def generate_short_link(): return str(uuid.uuid4())[:7] class User(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer) email = db.Column(db.String, unique=True) campaigns = db.relationship('Campaign', backref='user', lazy='dynamic') def __init__(self, user_id, email): self.user_id = user_id self.email = email FB_BLUEPRINT = make_facebook_blueprint( client_id=FB_CLIENT_ID, client_secret=FB_CLIENT_SECRET, scope=['email'], login_url="/facebook") #FB_BLUEPRINT.backend = SQLAlchemyBackend(OAuth, db.session, user=current_user) class Campaign(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text) links = db.relationship('Link', backref='campaign', lazy='dynamic') user_id = db.Column(db.Integer, db.ForeignKey('user.id')) def __init__(self, name, user_id): self.name = name self.user = user_id
from flask import Flask, redirect, url_for from flask_dance.contrib.facebook import make_facebook_blueprint, facebook from flask_login import login_user, current_user from flask_dance.consumer.storage.sqla import OAuthConsumerMixin, SQLAlchemyStorage from flask_dance.consumer import oauth_authorized from sqlalchemy.orm.exc import NoResultFound from quandromy.database import OAuth from quandromy import db facebook_blueprint = make_facebook_blueprint() facebook_blueprint.storage = SQLAlchemyStorage(OAuth, db.session, user=current_user) @oauth_authorized.connect_via(facebook_blueprint) def facebook_logged_in(blueprint, token): account_info = blueprint.session.get('/me') if account_info.ok: account_info_json = account_info.json() username = account_info_json['name'] query = User.query.filter_by(username=username) try: user = query.one() except NoResultFound: user = User(username=username)
#Google Login google_blueprint = make_google_blueprint( client_id=Config.OAUTH_CREDENTIALS['google']['client_id'], client_secret=Config.OAUTH_CREDENTIALS['google']['client_secret'], scope=[ 'openid', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email', ], redirect_to='google.login', ) #Facebook Login facebook_blueprint = make_facebook_blueprint( client_id=Config.OAUTH_CREDENTIALS['facebook']['id'], client_secret=Config.OAUTH_CREDENTIALS['facebook']['secret'], scope='email', redirect_to='facebook.login') #GIthub Login github_blueprint = make_github_blueprint( client_id=Config.OAUTH_CREDENTIALS['github']['client_id'], client_secret=Config.OAUTH_CREDENTIALS['github']['client_secret'], scope=['user, repo'], redirect_to='github.login') #Twiter Login twitter_blueprint = make_twitter_blueprint( api_key=Config.OAUTH_CREDENTIALS['twitter']['id'], api_secret=Config.OAUTH_CREDENTIALS['twitter']['secret'], redirect_to='login_twitter', )
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)) @oauth_authorized.connect_via(github_blueprint) def github_logged_in(blueprint, token): if not token: flash("Failed to log in with GitHub.", category = "error") return resp = blueprint.session.get("/user") if not resp.ok:
# DATABASE INITITAL basedir = os.path.abspath(os.path.dirname(__file__)) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join( basedir, 'db.sqlite') app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) ma = Marshmallow(app) app.config["FACEBOOK_OAUTH_CLIENT_ID"] = "472717633470175" app.config["FACEBOOK_OAUTH_CLIENT_SECRET"] = "c209f953d18ee26f1deeb9d8e234622c" app.config["GOOGLE_OAUTH_CLIENT_ID"] = os.environ.get( "892442284955-66p4eln67in1pm6h9hhd0e804gdcrgpb.apps.googleusercontent.com") app.config["GOOGLE_OAUTH_CLIENT_SECRET"] = os.environ.get( "Dq55Z9CZTnmxg-Qram0EpMOi") facebook_bp = make_facebook_blueprint(scope='email', redirect_url='/facebook') app.register_blueprint(facebook_bp, url_prefix="/login") google_bp = make_google_blueprint( client_id= "892442284955-66p4eln67in1pm6h9hhd0e804gdcrgpb.apps.googleusercontent.com", client_secret="Dq55Z9CZTnmxg-Qram0EpMOi", scope=[ "https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email", ], redirect_url='/google') app.register_blueprint(google_bp, url_prefix="/login") class Job(db.Model):