def config_web(args): from flask import Flask from flask.ext.login import LoginManager from flask.ext.oauth import OAuth global app app = Flask('wikimetrics') web_config = create_object_from_text_config_file(args.web_config) app.config.from_object(web_config) if args.override_config: web_config = create_object_from_text_config_file(args.override_config) app.config.from_object(web_config) global login_manager login_manager = LoginManager() login_manager.init_app(app) global google oauth = OAuth() google = oauth.remote_app( 'google', base_url=app.config['GOOGLE_BASE_URL'], authorize_url=app.config['GOOGLE_AUTH_URI'], request_token_url=None, request_token_params={ 'scope': app.config['GOOGLE_AUTH_SCOPE'], 'response_type': 'code', }, access_token_url=app.config['GOOGLE_TOKEN_URI'], access_token_method='POST', access_token_params={'grant_type': 'authorization_code'}, consumer_key=app.config['GOOGLE_CLIENT_ID'], consumer_secret=app.config['GOOGLE_CLIENT_SECRET'], )
def __init__(self, name, title, key, secret, access_key, access_secret, at_login=True, priority=True): self.name = name self.title = title self.at_login = at_login self.priority = priority self.consumer_key = key self.consumer_secret = secret self.access_key = access_key self.access_secret = access_secret oauth = OAuth() twitter = oauth.remote_app( 'twitter', base_url='https://api.twitter.com/1/', request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authenticate', consumer_key=key, consumer_secret=secret, ) twitter.tokengetter( lambda token=None: None) # We have no use for tokengetter self.callback = twitter_exception_handler( twitter.authorized_handler(self.unwrapped_callback)) self.twitter = twitter
def oauth_app(self, base_url='https://api.twitter.com/1.1/'): oauth = OAuth() twitter = oauth.remote_app( 'twitter', base_url='', request_token_url='https://api.twitter.com/oauth/request_token', access_token_url='https://api.twitter.com/oauth/access_token', authorize_url='https://api.twitter.com/oauth/authenticate', consumer_key=self.app.config.get('TWITTER_CONSUMER_KEY'), consumer_secret=self.app.config.get('TWITTER_CONSUMER_SECRET'), ) twitter.tokengetter(self.token_getter) return twitter
def init_github_oauth_app(github_client_id, github_client_secret): github_oauth_app = OAuth().remote_app( 'github', base_url='https://github.com', request_token_url=None, access_token_url='https://github.com/login/oauth/access_token', authorize_url='https://github.com/login/oauth/authorize', consumer_key=github_client_id, consumer_secret=github_client_secret, request_token_params={'scope': 'repo'}) github_oauth_app.tokengetter(lambda token=None: None) # Hack to avoid the following error: # SSLHandshakeError: [Errno 1] _ssl.c:504: error:14090086:SSL # routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed # See http://stackoverflow.com/a/10393381 for details github_oauth_app._client.ca_certs = certifi.where() # Store OAuth app at the blueprint object to make it available # to the view functions bp.github_oauth_app = github_oauth_app
def get_github_oauth_client(self, scope='', token='github_oauth_token'): """Returns a instance of Github OAuth """ if not all([self.github_id, self.github_secret]): current_app.logger.error("Github api settings are missing") flash(_("Github login is not available at the moment")) return None oauth = OAuth() github = oauth.remote_app('github', base_url='https://github.com', request_token_url=None, access_token_url='/login/oauth/access_token', authorize_url='/login/oauth/authorize', consumer_key=self.github_id, consumer_secret=self.github_secret, request_token_params={'scope': scope}, access_token_method="POST", ) github.tokengetter_func = lambda *a: session.get(token) return github
logging.basicConfig(level=logging.DEBUG) # specific loggers logging.getLogger('requests').setLevel(logging.WARNING) logging.getLogger('urllib3').setLevel(logging.WARNING) logging.getLogger('amqp').setLevel(logging.INFO) app = Flask(__name__, static_folder='../frontend') app.config.from_object(default_settings) app.config.from_envvar('DATAWIRE_SETTINGS', silent=True) app_name = app.config.get('APP_NAME') db = SQLAlchemy(app) migrate = Migrate(app, db, directory=app.config.get('ALEMBIC_DIR')) oauth = OAuth() login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'ui' # queue_name = app_name + '_q' # app.config['CELERY_DEFAULT_QUEUE'] = queue_name # app.config['CELERY_QUEUES'] = ( # Queue(queue_name, Exchange(queue_name), routing_key=queue_name), # ) # celery = Celery(app_name, broker=app.config['CELERY_BROKER_URL']) # celery.config_from_object(app.config) def url_for(*a, **kw):
def init_app(self, app, datastore): """Initialize the application with the Social module :param app: The Flask application :param datastore: Connection datastore instance """ from flask.ext import social as s s.SocialConnection = datastore.get_models() blueprint = Blueprint('social', __name__) configured = {} for key, value in default_config.items(): configured[key] = app.config.get(key, value) app.config.update(configured) # Set the datastore setattr(app, app.config[CONNECTION_DATASTORE_KEY], datastore) # get service provider configurations provider_configs = [] for provider, provider_config in default_provider_config.items(): provider_key = 'SOCIAL_%s' % provider.upper() if provider_key in app.config: d_config = provider_config.copy() try: __import__(d_config['id']) except ImportError: app.logger.error( 'Could not import %s API module. Please install via:\n' '%s' % (d_config['display_name'], d_config['install'])) d_oauth_config = d_config['oauth'].copy() d_config.update(app.config[provider_key]) d_oauth_config.update(app.config[provider_key]['oauth']) d_config['oauth'] = d_oauth_config app.config[provider_key] = d_config provider_configs.append(d_config) app.oauth = OAuth() app.social = self @blueprint.route('/login/<provider_id>', methods=['POST']) def login(provider_id): """Starts the provider login OAuth flow""" if current_user.is_authenticated(): return redirect(request.referrer or '/') callback_url = get_authorize_callback('/login/%s' % provider_id) display_name = get_display_name(provider_id) current_app.logger.debug('Starting login via %s account. Callback ' 'URL = %s' % (display_name, callback_url)) post_login = request.form.get('next', get_post_login_redirect()) session['post_oauth_login_url'] = post_login return get_remote_app(provider_id).authorize(callback_url) @blueprint.route('/connect/<provider_id>', methods=['POST']) @login_required def connect(provider_id): """Starts the provider connection OAuth flow""" callback_url = get_authorize_callback('/connect/%s' % provider_id) ctx = dict(display_name=get_display_name(provider_id), current_user=current_user, callback_url=callback_url) current_app.logger.debug( 'Starting process of connecting ' '%(display_name)s ccount to user account %(current_user)s. ' 'Callback URL = %(callback_url)s' % ctx) allow_view = current_app.config[CONNECT_ALLOW_REDIRECT_KEY] post_connect = request.form.get('next', allow_view) session[POST_OAUTH_CONNECT_SESSION_KEY] = post_connect return get_remote_app(provider_id).authorize(callback_url) @blueprint.route('/connect/<provider_id>', methods=['DELETE']) @login_required def remove_all_connections(provider_id): """Remove all connections for the authenticated user to the specified provider """ display_name = get_display_name(provider_id) ctx = dict(provider=display_name, user=current_user) try: method = connection_datastore.remove_all_connections method(current_user.get_id(), provider_id) current_app.logger.debug('Removed all connections to ' '%(provider)s for %(user)s' % ctx) do_flash("All connections to %s removed" % display_name, 'info') except: current_app.logger.error('Unable to remove all connections to ' '%(provider)s for %(user)s' % ctx) msg = "Unable to remove connection to %(provider)s" % ctx do_flash(msg, 'error') return redirect(request.referrer) @blueprint.route('/connect/<provider_id>/<provider_user_id>', methods=['DELETE']) @login_required def remove_connection(provider_id, provider_user_id): """Remove a specific connection for the authenticated user to the specified provider """ display_name = get_display_name(provider_id) ctx = dict(provider=display_name, user=current_user, provider_user_id=provider_user_id) try: connection_datastore.remove_connection(current_user.get_id(), provider_id, provider_user_id) current_app.logger.debug( 'Removed connection to %(provider)s ' 'account %(provider_user_id)s for %(user)s' % ctx) do_flash("Connection to %(provider)s removed" % ctx, 'info') except ConnectionNotFoundError: current_app.logger.error( 'Unable to remove connection to %(provider)s account ' '%(provider_user_id)s for %(user)s' % ctx) do_flash("Unabled to remove connection to %(provider)s" % ctx, 'error') return redirect(request.referrer) # Configure the URL handlers for each fo the configured providers for provider_config in provider_configs: _configure_provider(app, blueprint, app.oauth, provider_config) url_prefix = app.config[URL_PREFIX_KEY] app.register_blueprint(blueprint, url_prefix=url_prefix)
from flask.ext.oauth import OAuth from google.appengine.api import taskqueue from traveller import settings latitude = Blueprint("latitude", __name__, url_prefix="/latitude") latitude_oauth = OAuth().remote_app( "google", base_url="https://www.google.com/accounts/", authorize_url="https://accounts.google.com/o/oauth2/auth", request_token_url=None, request_token_params={ "scope": "https://www.googleapis.com/auth/latitude.all.best", "response_type": "code", }, access_token_url="https://accounts.google.com/o/oauth2/token", access_token_method="POST", access_token_params={ "grant_type": "authorization_code", }, consumer_key=settings.GOOGLE_CLIENT_ID, consumer_secret=settings.GOOGLE_CLIENT_SECRET, ) @latitude.route("/start") def start(): callback=url_for('.authorized', _external=True) return latitude_oauth.authorize(callback=callback)
def init_app(self, app): if app is None: return blueprint = Blueprint('social', __name__) config = default_config.copy() try: config.update(app.config['SOCIAL']) except: pass app.config['SOCIAL'] = config # Update the service provider configurations social_providers_config = {} if 'SOCIAL_PROVIDERS' in app.config: for provider, provider_config in default_provider_config.items(): if provider in app.config['SOCIAL_PROVIDERS']: d_config = provider_config.copy() d_oauth_config = d_config['oauth'].copy() p_config = app.config['SOCIAL_PROVIDERS'][provider][ 'oauth'] d_config.update(app.config['SOCIAL_PROVIDERS'][provider]) d_oauth_config.update(p_config) d_config['oauth'] = d_oauth_config social_providers_config[provider] = d_config app.config['SOCIAL_PROVIDERS'] = social_providers_config app.logger.debug('Social Configuration: %s' % app.config['SOCIAL']) app.logger.debug('Social Provider Configuration: ' '%s' % app.config['SOCIAL_PROVIDERS']) # Connection service name app.oauth = OAuth() app.social = self @blueprint.route('/login/<provider_id>', methods=['POST']) def login(provider_id): if current_user.is_authenticated(): return redirect("/") callback_url = get_authorize_callback('/login/%s' % provider_id) current_app.logger.debug( 'Starting login via %s account. Callback ' 'URL = %s' % (get_display_name(provider_id), callback_url)) session['post_oauth_login_url'] = request.form.get( 'next', current_app.config['AUTH']['post_login_view']) remote_app = get_remote_app(provider_id).remote_app return remote_app.authorize(callback_url) @blueprint.route('/connect/<provider_id>', methods=['POST']) @login_required def connect(provider_id): callback_url = get_authorize_callback('/connect/%s' % provider_id) current_app.logger.debug( 'Starting process of connecting %s ' 'account to user account %s. Callback URL = %s' % (get_display_name(provider_id), current_user, callback_url)) session['post_oauth_connect_url'] = request.form.get( 'next', current_app.config['SOCIAL']['connect_allow_view']) remote_app = get_remote_app(provider_id).remote_app return remote_app.authorize(callback_url) @blueprint.route('/connect/<provider_id>', methods=['DELETE']) @login_required def remove_all_connections(provider_id): try: display_name = get_display_name(provider_id) connection_service.remove_all_connections( current_user.get_id(), provider_id) current_app.logger.debug('Removed all connections to %s for ' '%s' % (provider_id, current_user)) flash("Connections to %s removed" % display_name) except: current_app.logger.error( 'Unable to remove all connections to ' '%s for %s' % (get_display_name(provider_id), current_user)) flash("Unabled to remove connection") return redirect(request.referrer) @blueprint.route('/connect/<provider_id>/<provider_user_id>', methods=['DELETE']) @login_required def remove_connection(provider_id, provider_user_id): try: display_name = get_display_name(provider_id) connection_service.remove_connection(current_user.get_id(), provider_id, provider_user_id) current_app.logger.debug('Removed connection to %s for ' '%s' % (provider_id, current_user)) flash("Connection to %s removed" % display_name) except: current_app.logger.error( 'Unable to remove connection to %s/%s ' 'for %s' % (get_display_name(provider_id), provider_user_id, current_user)) flash("Unabled to remove connection") return redirect(request.referrer) # Setup handlers for the configured providers for p_id, p_config in app.config['SOCIAL_PROVIDERS'].items(): _configure_provider(app, blueprint, app.oauth, p_id, p_config) app.register_blueprint(blueprint, url_prefix=app.config['SOCIAL']['url_prefix'])
def config_web(args): from flask import Flask, request, json from flask.ext.login import LoginManager from flask.ext.oauth import ( OAuth, OAuthRemoteApp, OAuthException, get_etree ) from werkzeug import url_decode, parse_options_header import flask.ext.oauth as nasty_patch_to_oauth global app app = Flask('wikimetrics') # note absolute_path does not change on the life of the application app.absolute_path_to_app_root = get_absolute_path() # TODO do we need this config to be created like an object instead of a dictionary? web_config = create_object_from_text_config_file(args.web_config) # if args.override_config: # override_config = create_object_from_text_config_file(args.override_config) # TODO override one obj with other, can we use dict? app.config.from_object(web_config) version, latest = get_wikimetrics_version() app.config['WIKIMETRICS_LATEST'] = latest app.config['WIKIMETRICS_VERSION'] = version # configure logging if not app.config['DEBUG']: import logging import sys app.logger.addHandler(logging.StreamHandler(stream=sys.stderr)) global login_manager login_manager = LoginManager() login_manager.init_app(app) # TODO, this does not need to be a # global, could be stored in flask application context global google oauth = OAuth() google = oauth.remote_app( 'google', base_url=app.config['GOOGLE_BASE_URL'], authorize_url=app.config['GOOGLE_AUTH_URI'], request_token_url=None, request_token_params={ 'scope': app.config['GOOGLE_AUTH_SCOPE'], 'response_type': 'code', }, access_token_url=app.config['GOOGLE_TOKEN_URI'], access_token_method='POST', access_token_params={ 'grant_type': 'authorization_code' }, consumer_key=app.config['GOOGLE_CLIENT_ID'], consumer_secret=app.config['GOOGLE_CLIENT_SECRET'], ) global mw_oauth_token mw_oauth_token = ConsumerToken( app.config['META_MW_CONSUMER_KEY'], app.config['META_MW_CLIENT_SECRET'], )