Exemplo n.º 1
0
    def __init__(self, name, title, key, secret, access_key, access_secret, at_login=True, priority=True, icon=None):
        self.name = name
        self.title = title
        self.at_login = at_login
        self.priority = priority
        self.icon = icon
        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
Exemplo n.º 2
0
    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
Exemplo n.º 3
0
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'],
    )
Exemplo n.º 4
0
def init_oauth(app):
    global o_twitter, o_facebook, oauth_authorized

    oauth = OAuth()
    o_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=app.config["OAUTH_TWITTER_CONSUMER_KEY"],
        consumer_secret=app.config["OAUTH_TWITTER_CONSUMER_SECRET"],
        access_token_method='POST'
    )
    user.add_url_rule('/oauth/twitter', "twitter_authorized", o_twitter.authorized_handler(twitter_authorized))
    o_twitter.tokengetter(oauth_token)

    o_facebook = oauth.remote_app('facebook',
        base_url='https://graph.facebook.com/',
        request_token_url=None,
        access_token_url='/oauth/access_token',
        authorize_url=app.config["OAUTH_FACEBOOK_SITE_URL"],
        consumer_key=app.config["OAUTH_FACEBOOK_CONSUMER_KEY"],
        consumer_secret=app.config["OAUTH_FACEBOOK_CONSUMER_SECRET"],
        request_token_params={'scope': 'email'}
    )
    user.add_url_rule('/oauth/facebook', "facebook_authorized", o_facebook.authorized_handler(facebook_authorized))
    o_facebook.tokengetter(oauth_token)
Exemplo n.º 5
0
 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
Exemplo n.º 6
0
 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.tokengetter)
     return twitter
Exemplo n.º 7
0
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
Exemplo n.º 8
0
    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
Exemplo n.º 9
0
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 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'],
    )
Exemplo n.º 11
0
from flask.ext.wtf import validators
from flask_login import (LoginManager, current_user,
                            login_user, logout_user, login_required)
from werkzeug import check_password_hash, generate_password_hash
from datetime import datetime
from flask.ext.oauth import OAuth
from mongoengine import connect
import os

FACEBOOK_APP_ID = ""
FACEBOOK_APP_SECRET = ""
TWITTER_APP_ID = ""
TWITTER_APP_SECRET = ""

#Defining Remote Applications
oauth = OAuth()
facebook = oauth.remote_app(
    'facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key=FACEBOOK_APP_ID,
    consumer_secret=FACEBOOK_APP_SECRET,
    request_token_params={'scope': 'email',
                          'redirect_uri': 'https://crate.ly/#Dashboard',
                          'display': 'popup'}
)
twitter = oauth.remote_app(
    'twitter',
    base_url='http://api.twitter.com/1/',
Exemplo n.º 12
0
import requests
import os
import opml

from orm import User, Anonymous

app = Flask(__name__)

# import config from $APP_CONFIG file

app.config.from_envvar('APP_CONFIG') 
app.secret_key = app.config['SECRET_KEY']

# google oauth2 setup

oauth = OAuth()
google = 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/userinfo.email \
                          https://www.googleapis.com/auth/userinfo.profile  http://www.google.com/reader/api/0/subscription/list',
                                                 '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=app.config['GOOGLE_CLIENT_ID'],
                          consumer_secret=app.config['GOOGLE_CLIENT_SECRET'])
# login manager

login_manager = LoginManager()
Exemplo n.º 13
0
    from psycogreen.gevent import patch_psycopg
    patch_psycopg()
except:
    pass

app = Flask(__name__)

app.config.from_pyfile('config.py')

csrf = SeaSurf(app)
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.setup_app(app)

oauth = OAuth()
twitter = oauth.remote_app(
    'twitter',
    base_url='https://api.twitter.com/1.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/authorize',
    consumer_key=app.config['TWITTER_CONSUMER_KEY'],
    consumer_secret=app.config['TWITTER_CONSUMER_SECRET'])

from views import *

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
Exemplo n.º 14
0
import json
import os
import urllib2, urllib

from flask import Module
from flask import redirect, request, session, url_for
from flask.ext.oauth import OAuth

from db import Database
from util import *

login = Module(__name__)
oauth = OAuth()

facebook = oauth.remote_app(
    'facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key=os.environ['FACEBOOK_APP_ID'],
    consumer_secret=os.environ['FACEBOOK_APP_SECRET'],
    request_token_params={
        'scope': 'email,user_likes,friends_likes,user_location'
    })


def cookieUser(email, extra_data=None):
    if extra_data is None:
        extra_data = dict()
    userObjData = {'email': email}
Exemplo n.º 15
0
    elif user and g.user != user:
        flash('Your facebook session has expired. ' +
              'Please log in again to continue')
        next = url_for('default.index')
        return redirect(url_for('default.logout', next=next))
    else:
        g.user.set_facebook_info(facebook_info)

    return redirect(close_action or
                    url_for('default.close_redirect', next_url=next_url))

###
# Twitter

# Use Twitter as example remote application
oauth = OAuth()
twitter = oauth.remote_app(
    'twitter',
    # unless absolute urls are used to make requests, this will be added
    # before all URLs.  This is also true for request_token_url and others.
    base_url='https://api.twitter.com/1/',
    # where flask should look for new request tokens
    request_token_url='https://api.twitter.com/oauth/request_token',
    # where flask should exchange the token with the remote application
    access_token_url='https://api.twitter.com/oauth/access_token',
    # twitter knows two authorizatiom URLs.  /authorize and /authenticate.
    # they mostly work the same, but for sign on /authenticate is
    # expected because this will give the user a slightly different
    # user interface on the twitter side.
    authorize_url='https://api.twitter.com/oauth/authenticate',
    # the consumer keys from the twitter application registry.
Exemplo n.º 16
0
from flask import Flask, url_for, session, redirect, render_template, request,jsonify
from flask.ext.oauth import OAuth
from app import app
from app import db, models


app.secret_key = 'my secret-key-!@#$'

oauth = OAuth()
trello = oauth.remote_app('trello',
                          base_url='',
                          request_token_url='https://trello.com/1/OAuthGetRequestToken',
                          access_token_url='https://trello.com/1/OAuthGetAccessToken',
                          authorize_url='https://trello.com/1/OAuthAuthorizeToken',
                          consumer_key='0c967eff30367539f04c711d283aba53',
                          consumer_secret='0a5ad962770bc02019b8f0737c5cb429760e5dadc25236e47067d45db3c1d162')


@trello.tokengetter
def token_getter(token=None):
    return session.get('token')

@app.route('/')
def index():
    return trello.authorize(callback=url_for('authorized'))

@app.route('/authorized/')
@trello.authorized_handler
def authorized(resp):
    session['token'] = (
        resp['oauth_token'],
Exemplo n.º 17
0
from datetime import datetime
from time import time

from flask import redirect, request, url_for, flash
from flask.ext.login import login_required
from flask.ext.oauth import OAuth

import config
import messages
from database import db, Facebook as DBFacebook
from user import get_current_user
from post import Post


oauth = OAuth()

facebook = oauth.remote_app(
                name='facebook',
                base_url='https://graph.facebook.com/',
                request_token_url=None,
                access_token_url='/oauth/access_token',
                authorize_url='https://www.facebook.com/dialog/oauth',
                consumer_key=config.get('facebook_app_id'),
                consumer_secret=config.get('facebook_app_secret'),
                request_token_params={'scope': 'publish_stream'}
            )


@login_required
def authorization():
Exemplo n.º 18
0
    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'])
Exemplo n.º 19
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.oauth import OAuth
from flask.ext.login import LoginManager

from config import SECRET_KEY, SQLALCHEMY_DATABASE_URI, \
    TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
app.secret_key = SECRET_KEY

db = SQLAlchemy(app)

oauth = OAuth()
twitter = oauth.remote_app('twitter',
    base_url = 'http://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 = TWITTER_CONSUMER_KEY,
    consumer_secret = TWITTER_CONSUMER_SECRET
)

login_manager = LoginManager()
login_manager.init_app(app)

from app import views
Exemplo n.º 20
0
# Create application object
app = Flask(__name__)

app.config.from_object('alerting.defaults')
app.config.from_envvar('APPLICATION_SETTINGS', silent=True)

# Create logging
if app.config.get('LOG_FILE') == True:
    import logging
    from logging import FileHandler
    file_handler = FileHandler('log.txt')
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)

oauth = OAuth()

facebook = oauth.remote_app(
    'facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key=app.config.get('FACEBOOK_APP_ID'),
    consumer_secret=app.config.get('FACEBOOK_APP_SECRET'),
    request_token_params={'scope': 'email'})
google = oauth.remote_app(
    'google',
    base_url='https://www.google.com/accounts/',
    request_token_url=None,
    access_token_url='https://accounts.google.com/o/oauth2/token',
Exemplo n.º 21
0
    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)
Exemplo n.º 22
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask.ext.seasurf import SeaSurf
from flask.ext.oauth import OAuth
from vksunshine.config import VK_BASE_URL, VK_ACCESS_TOKEN_URL, VK_AUTHORIZE_URL, \
                              VK_REQUEST_TOKEN_PARAMS, VK_CONSUMER_KEY, VK_CONSUMER_SECRET


__all__ = ['csrf', 'oauth_manager', 'vkontakte']

csrf = SeaSurf()
oauth_manager = OAuth()


vkontakte = oauth_manager.remote_app('vkontakte',
    base_url=VK_BASE_URL,
    authorize_url=VK_AUTHORIZE_URL,
    request_token_url=None,
    request_token_params=VK_REQUEST_TOKEN_PARAMS,
    access_token_url=VK_ACCESS_TOKEN_URL,
    consumer_key=VK_CONSUMER_KEY,
    consumer_secret=VK_CONSUMER_SECRET)
Exemplo n.º 23
0
from flask import session
from flask.ext.oauth import OAuth

from datawire.core import app

oauth = OAuth()

twitter = oauth.remote_app('twitter',
        base_url='https://api.twitter.com/1.1/',
        authorize_url='https://api.twitter.com/oauth/authorize',
        request_token_url='https://api.twitter.com/oauth/request_token',
        access_token_url='https://api.twitter.com/oauth/access_token',
        consumer_key=app.config.get('TWITTER_CONSUMER_KEY'),
        consumer_secret=app.config.get('TWITTER_CONSUMER_SECRET'))

facebook = oauth.remote_app('facebook',
        base_url='https://graph.facebook.com/',
        request_token_url=None,
        access_token_url='/oauth/access_token',
        authorize_url='https://www.facebook.com/dialog/oauth',
        consumer_key=app.config.get('FACEBOOK_APP_ID'),
        consumer_secret=app.config.get('FACEBOOK_APP_SECRET'),
        request_token_params={'scope': 'email'})


@twitter.tokengetter
def get_twitter_token(token=None):
    return session.get('twitter_token')


@facebook.tokengetter
Exemplo n.º 24
0
#imports
from flask import Flask
from flask.ext.oauth import OAuth
from config import *

__author__ = 'ferron'

app = Flask(__name__)
app.secret_key = SECRET_KEY
oauth = OAuth()

carepass = oauth.remote_app('carepass',
                          base_url=BASE_URL,
                          authorize_url=OAUTH_ENDPOINT+'/authorize',
                          request_token_url=None,
                          request_token_params={'scope': SCOPE,
                                                'response_type': 'code'},
                          access_token_url=OAUTH_ENDPOINT + '/token',
                          access_token_method='POST',
                          access_token_params={'grant_type': 'authorization_code'},
                          consumer_key=CLIENT_ID,
                          consumer_secret=CLIENT_SECRET)
Exemplo n.º 25
0
from flask.ext.login import LoginManager, current_user, login_required
from flask.ext.login import logout_user, login_user
from flask.ext.oauth import OAuth
from flask.ext.seasurf import SeaSurf
from munkres import Munkres

app = Flask(__name__)
app.config.from_pyfile('config.py')

csrf = SeaSurf(app)
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.setup_app(app)

oauth = OAuth()
twitter = oauth.remote_app(
    'twitter',
    base_url='https://api.twitter.com/1.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/authorize',
    consumer_key=app.config['TWITTER_CONSUMER_KEY'],
    consumer_secret=app.config['TWITTER_CONSUMER_SECRET']
)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, nullable=False)
    name = db.Column(db.String(24), unique=True, nullable=False)
    oauth_token = db.Column(db.String(200), nullable=False)
Exemplo n.º 26
0
from collections import defaultdict
import feedparser

from mongo_stuff import MongoLib

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

app = Flask(__name__)

# import config from $APP_CONFIG file

app.config.from_envvar("APP_CONFIG")  # export APP_CONFIG=/path/to/settings.cfg
app.secret_key = app.config["SECRET_KEY"]

oauth = OAuth()
google = 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/userinfo.email https://www.googleapis.com/auth/userinfo.profile http://www.google.com/reader/api/0/subscription/list",
        "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=app.config["GOOGLE_CLIENT_ID"],
    consumer_secret=app.config["GOOGLE_CLIENT_SECRET"],
)
Exemplo n.º 27
0
    """Helper to load a configuration from `app.config`, if it
    exists, or from `os.environ` (and saving into `app.config`).
    """
    if key in app.config:
        return app.config[key]
    elif key in os.environ:
        app.config[key] = os.environ[key]
        return app.config[key]
    return default

app.secret_key = conf('FLASK_SECRET_KEY', 'Bn1dcC2QDWXgtj')

app.config['BOOTSTRAP_GOOGLE_ANALYTICS_ACCOUNT'] = conf('BOOTSTRAP_GOOGLE_ANALYTICS_ACCOUNT')
Bootstrap(app)

oauth = OAuth()
meetup_oauth = oauth.remote_app('meetup',
    base_url='https://api.meetup.com/',
    request_token_url='https://api.meetup.com/oauth/request/',
    access_token_url='https://api.meetup.com/oauth/access/',
    authorize_url='http://www.meetup.com/authorize/',
    consumer_key=conf('MEETUP_OAUTH_CONSUMER_KEY'),
    consumer_secret=conf('MEETUP_OAUTH_CONSUMER_SECRET'),
)
meetup = Meetup(meetup_oauth)

app.config['MONGO_URI'] = conf('MONGOHQ_URL', 'mongodb://localhost/meetups')
mongo = PyMongo(app)

sendgrid_api = sendgrid.Sendgrid(
    username=conf('SENDGRID_USERNAME'),
Exemplo n.º 28
0
from flask.ext.oauth import OAuth

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# configuration
DATABASE_URI = 'sqlite:////tmp/flask-oauth.db'
SECRET_KEY = 'development key'
DEBUG = True

# setup flask
app = Flask(__name__)
app.debug = DEBUG
app.secret_key = SECRET_KEY
oauth = OAuth()

# Use Twitter as example remote application
twitter = oauth.remote_app('twitter',
    # unless absolute urls are used to make requests, this will be added
    # before all URLs.  This is also true for request_token_url and others.
    base_url='http://api.twitter.com/1/',
    # where flask should look for new request tokens
    request_token_url='http://api.twitter.com/oauth/request_token',
    # where flask should exchange the token with the remote application
    access_token_url='http://api.twitter.com/oauth/access_token',
    # twitter knows two authorizatiom URLs.  /authorize and /authenticate.
    # they mostly work the same, but for sign on /authenticate is
    # expected because this will give the user a slightly different
    # user interface on the twitter side.
    authorize_url='http://api.twitter.com/oauth/authenticate',
Exemplo n.º 29
0
from flask.ext.oauth import OAuth

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# configuration
DATABASE_URI = 'sqlite:////tmp/flask-oauth.db'
SECRET_KEY = 'development key'
DEBUG = True

# setup flask
app = Flask(__name__)
app.debug = DEBUG
app.secret_key = SECRET_KEY
oauth = OAuth()

# Use Twitter as example remote application
twitter = oauth.remote_app(
    'twitter',
    # unless absolute urls are used to make requests, this will be added
    # before all URLs.  This is also true for request_token_url and others.
    base_url='http://api.twitter.com/1/',
    # where flask should look for new request tokens
    request_token_url='http://api.twitter.com/oauth/request_token',
    # where flask should exchange the token with the remote application
    access_token_url='http://api.twitter.com/oauth/access_token',
    # twitter knows two authorizatiom URLs.  /authorize and /authenticate.
    # they mostly work the same, but for sign on /authenticate is
    # expected because this will give the user a slightly different
    # user interface on the twitter side.
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'],
    )
Exemplo n.º 31
0
from flask import Flask, url_for, session, redirect, render_template, request, jsonify
from flask.ext.oauth import OAuth
from app import app
from app import db, models

app.secret_key = 'my secret-key-!@#$'

oauth = OAuth()
trello = oauth.remote_app(
    'trello',
    base_url='',
    request_token_url='https://trello.com/1/OAuthGetRequestToken',
    access_token_url='https://trello.com/1/OAuthGetAccessToken',
    authorize_url='https://trello.com/1/OAuthAuthorizeToken',
    consumer_key='0c967eff30367539f04c711d283aba53',
    consumer_secret=
    '0a5ad962770bc02019b8f0737c5cb429760e5dadc25236e47067d45db3c1d162')


@trello.tokengetter
def token_getter(token=None):
    return session.get('token')


@app.route('/')
def index():
    return trello.authorize(callback=url_for('authorized'))


@app.route('/authorized/')
@trello.authorized_handler
Exemplo n.º 32
0
# Create application object
app = Flask(__name__)

app.config.from_object('alerting.defaults')
app.config.from_envvar('APPLICATION_SETTINGS', silent=True)

# Create logging
if app.config.get('LOG_FILE') == True:
    import logging
    from logging import FileHandler
    file_handler = FileHandler('log.txt')
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)

oauth = OAuth()

facebook = oauth.remote_app('facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key=app.config.get('FACEBOOK_APP_ID'),
    consumer_secret=app.config.get('FACEBOOK_APP_SECRET'),
    request_token_params={'scope': 'email'}
    )
google = oauth.remote_app('google',
    base_url='https://www.google.com/accounts/',
    request_token_url=None,
    access_token_url='https://accounts.google.com/o/oauth2/token',
    authorize_url='https://accounts.google.com/o/oauth2/auth',
Exemplo n.º 33
0
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.oauth import OAuth
from flask.ext.assets import Environment

import certifi
from celery import Celery

from nomenklatura import default_settings

logging.basicConfig(level=logging.DEBUG)

app = Flask(__name__)
app.config.from_object(default_settings)
app.config.from_envvar('NOMENKLATURA_SETTINGS', silent=True)

db = SQLAlchemy(app)
assets = Environment(app)

celery = Celery('nomenklatura', broker=app.config['CELERY_BROKER_URL'])

oauth = OAuth()
github = oauth.remote_app(
    'github',
    base_url='https://github.com/login/oauth/',
    authorize_url='https://github.com/login/oauth/authorize',
    request_token_url=None,
    access_token_url='https://github.com/login/oauth/access_token',
    consumer_key=app.config.get('GITHUB_CLIENT_ID'),
    consumer_secret=app.config.get('GITHUB_CLIENT_SECRET'))

github._client.ca_certs = certifi.where()
Exemplo n.º 34
0
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask
    return celery


celery = init_celery(app)

oauth = OAuth()
google = 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/userinfo.email',
        '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=app.config['GOOGLE_CLIENT_ID'],
    consumer_secret=app.config['GOOGLE_CLIENT_SECRET'])
Exemplo n.º 35
0
from flask.ext.openid import OpenID
from flask.ext.principal import Principal, Permission, RoleNeed
from flask.ext.restful import Api
from flask.ext.youtube import Youtube

admin = Admin()
assets_env = Environment()
bcrypt = Bcrypt()
cache = Cache()
celery = Celery()
debug_toolbar = DebugToolbarExtension()
gzip = GZip()
login_manager = LoginManager()
mail = Mail()
mongo = MongoEngine()
oauth = OAuth()
oid = OpenID()
principals = Principal()
rest_api = Api()
youtube_ext = Youtube()

main_css = Bundle('css/site.css', filters='cssmin', output='css/common.css')

main_js = Bundle('js/site.js', filters='jsmin', output='js/common.js')


@oid.after_login
def create_or_login(resp):
    from models import db, User
    username = resp.fullname or resp.nickname or resp.email
    if not username:
Exemplo n.º 36
0
import hashlib, simplejson, requests, random
from datetime import datetime
import time
import pymongo, bson
from flask import Flask, render_template, request, Response, redirect, abort, session, send_from_directory, g, url_for
from flask.ext.pymongo import PyMongo
from flask.ext.oauth import OAuth
import config
import bleach
import markdown

app = Flask("index")
app.config.from_object(config)
app.secret_key = config.SECRET
mongo = PyMongo(app)
oauth = OAuth()

twitter = oauth.remote_app(
    'KittyCheck',
    consumer_key=config.TWITTER["consumer_key"],
    consumer_secret=config.TWITTER["consumer_secret"],
    base_url='https://api.twitter.com/1.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',
)


def jsonify(hash, callback=None):
    if hash.has_key('_id'):
        del hash['_id']
Exemplo n.º 37
0
class Acode(Base):
    __tablename__ = 'acode'

    id = Column(Integer, primary_key=True)
    code = Column(String)
    date_created = Column(DateTime,  default=datetime.utcnow)

    def __init__(self, code):
         self.code = code
def init_db():
    Base.metadata.create_all(bind=engine)

def drop_db():
    Base.metadata.drop_all(bind=engine)

oauth = OAuth()

vk = oauth.remote_app('vkontakte',
    base_url='https://api.vk.com/method/',
    request_token_url=None,
    access_token_url='https://api.vk.com/oauth/token',
    authorize_url='http://api.vk.com/oauth/authorize',
    consumer_key='2904906',
    consumer_secret='xpyuJye6NozdTazuuRvM',
    request_token_params={'scope': 'offline'}
)

@app.before_request
def before_request():
    g.code=getattr(g,'code',None)
    if not g.code:
Exemplo n.º 38
0
from datetime import datetime
from flask import Flask, request, url_for, redirect, g, session, flash, \
     abort, render_template
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.oauth import OAuth
from juggernaut import Juggernaut


app = Flask(__name__)
app.config.from_pyfile('config.cfg')
db = SQLAlchemy(app)
oauth = OAuth()
jug = Juggernaut()

facebook = oauth.remote_app('facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key='188477911223606',
    consumer_secret='621413ddea2bcc5b2e83d42fc40495de',
    request_token_params={'scope': 'email'}
)


def url_for_other_page(page):
    args = request.view_args.copy()
    args['page'] = page
    return url_for(request.endpoint, **args)
app.jinja_env.globals['url_for_other_page'] = url_for_other_page
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'],
    )

    def better_parse_response(resp, content, strict=False):
        ct, options = parse_options_header(resp['content-type'])
        if ct in ('application/json', 'text/javascript'):
            try:
                return json.loads(content)
            # handle json decode errors from parse_response
            # this is useful in the identify call because the response is
            # 'application/json' but the content is encoded
            except:
                return content
        elif ct in ('application/xml', 'text/xml'):
            # technically, text/xml is ascii based but because many
            # implementations get that wrong and utf-8 is a superset
            # of utf-8 anyways, so there is not much harm in assuming
            # utf-8 here
            charset = options.get('charset', 'utf-8')
            return get_etree().fromstring(content.decode(charset))
        elif ct != 'application/x-www-form-urlencoded':
            if strict:
                return content
        charset = options.get('charset', 'utf-8')
        return url_decode(content, charset=charset).to_dict()

    # TODO: Even worse, definitely patch upstream or consider switching to rauth
    nasty_patch_to_oauth.parse_response = better_parse_response

    # TODO: patch upstream
    # NOTE: a million thanks to Merlijn_van_Deen, author of
    # https://wikitech.wikimedia.org/wiki/Setting_up_Flask_cgi_app_as_a_tool/OAuth
    class MediaWikiOAuthRemoteApp(OAuthRemoteApp):
        def handle_oauth1_response(self):
            """
            Handles an oauth1 authorization response.  The return value of
            this method is forwarded as the first argument to the handling
            view function.
            """
            client = self.make_client()
            resp, content = client.request(
                '{0}&oauth_verifier={1}'.format(
                    self.expand_url(self.access_token_url),
                    request.args['oauth_verifier'],
                ),
                self.access_token_method
            )
            data = nasty_patch_to_oauth.parse_response(resp, content)
            if not self.status_okay(resp):
                raise OAuthException(
                    'Invalid response from ' + self.name,
                    type='invalid_response',
                    data=data
                )
            return data

    global meta_mw
    meta_mw_base_url = app.config['META_MW_BASE_URL']
    meta_mw = MediaWikiOAuthRemoteApp(
        oauth,
        'meta_mw',
        base_url=meta_mw_base_url,
        request_token_url=meta_mw_base_url + app.config['META_MW_BASE_INDEX'],
        request_token_params={
            'title': 'Special:MWOAuth/initiate',
            'oauth_callback': 'oob'
        },
        access_token_url=meta_mw_base_url + app.config['META_MW_TOKEN_URI'],
        authorize_url=meta_mw_base_url + app.config['META_MW_AUTH_URI'],
        consumer_key=app.config['META_MW_CONSUMER_KEY'],
        consumer_secret=app.config['META_MW_CLIENT_SECRET'],
    )
    oauth.remote_apps['meta_mw'] = meta_mw
Exemplo n.º 40
0
from flask import Flask, redirect, url_for, session, request
from flask.ext.oauth import OAuth

SECRET_KEY = 'development key'
DEBUG = True
FACEBOOK_APP_ID = '188477911223606'
FACEBOOK_APP_SECRET = '621413ddea2bcc5b2e83d42fc40495de'

app = Flask(__name__)
app.debug = DEBUG
app.secret_key = SECRET_KEY
oauth = OAuth()

facebook = oauth.remote_app(
    'facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key=FACEBOOK_APP_ID,
    consumer_secret=FACEBOOK_APP_SECRET,
    request_token_params={'scope': 'email'})


@app.route('/')
def index():
    return redirect(url_for('login'))


@app.route('/login')
def login():
Exemplo n.º 41
0

db = SQLAlchemy(app)

"""
In models.py we import 'db' from 'app'. So, we have
circular dependency here. Import 'Account' after 'db'
to temporarily resolve this.
"""
from models import Account


###########################


oauth = OAuth()

facebook = oauth.remote_app('facebook',
    base_url = 'https://graph.facebook.com/',
    request_token_url = None,
    access_token_url = '/oauth/access_token',
    authorize_url = 'https://www.facebook.com/dialog/oauth',
    consumer_key = settings.FACEBOOK_APP_ID,
    consumer_secret = settings.FACEBOOK_APP_SECRET,
    request_token_params = { 'scope': settings.FACEBOOK_APP_SCOPE }
)


###########################

Exemplo n.º 42
0
Arquivo: user.py Projeto: RCReddy/frp
                     ProfileForm,
                     MemoryForm,
                     LANGUAGE_CHOICES,
                     STATES,
                     BENEFICIARY_CATEGORY)
from ..service import signup as signup_service
from ..service import user as user_service
from ..service import donate as donate_service
from flask_user import current_user, login_required, roles_required
from ..helpers import allowed_file
from ..models import db, BaseNameMixin, BaseMixin
from ..mailer import Mailer

mailer = Mailer()
# Facebook requirements
oauth = OAuth()

facebook = oauth.remote_app(
    'facebook',
    request_token_url=None,
    base_url='https://graph.facebook.com/',
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key=app.config.get('FACEBOOK_CONSUMER_KEY'),
    consumer_secret=app.config.get('FACEBOOK_CONSUMER_SECRET'),
    request_token_params={'scope': 'email'})

@facebook.tokengetter
def get_facebook_token():
    return session.get('facebook_token')
Exemplo n.º 43
0
import json
import os
import urllib2, urllib

from flask import Module
from flask import redirect, request, session, url_for
from flask.ext.oauth import OAuth

from db import Database
from util import *

login = Module(__name__)
oauth = OAuth()

facebook = oauth.remote_app(
    'facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key="178485798938752",
    consumer_secret="3fc3c9f171bbb5221403307113662fe5",
    request_token_params={
        'scope': 'email,user_likes,friends_likes,user_location'
    })


def cookieUser(email, extra_data=None):
    if extra_data is None:
        extra_data = dict()
    userObjData = {'email': email}
Exemplo n.º 44
0
import re
import os
import boto
from datetime import datetime, timedelta
from flask import (Flask, request, session, g, redirect, url_for, abort,
                   render_template, flash, send_from_directory)
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, AnonymousUser
from flask.ext.oauth import OAuth
from allangles.middleware import MethodRewriteMiddleware

app = Flask(__name__)
app.config.from_object('allangles.configuration')
app.wsgi_app = MethodRewriteMiddleware(app.wsgi_app)

oauth = OAuth()
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.anonymous_user = AnonymousUser
login_manager.login_view = 'login'
login_manager.login_message = u'Please log in to access this page'
@login_manager.user_loader
def load_user(id):
    from allangles.models import User
    return User.query.filter_by(id=id).first()
login_manager.setup_app(app)

facebook = oauth.remote_app('facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
Exemplo n.º 45
0
from flask.ext.mail import Mail, Message

from flaskext.bcrypt import Bcrypt

from flask_debugtoolbar import DebugToolbarExtension


from flask.ext.oauth import OAuth

from sqlalchemy.orm import aliased, contains_eager

from datetime import datetime

from wtforms import Form

oauth = OAuth()


facebook = oauth.remote_app('facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key='233700133415330',
    consumer_secret='1d28dccf888bb41517693847b1d335d8',
    request_token_params={'scope': 'email'}
)

toolbar = DebugToolbarExtension(app)

bcrypt = Bcrypt()
Exemplo n.º 46
0
    """
    if key in app.config:
        return app.config[key]
    elif key in os.environ:
        app.config[key] = os.environ[key]
        return app.config[key]
    return default


app.secret_key = conf('FLASK_SECRET_KEY', 'Bn1dcC2QDWXgtj')

app.config['BOOTSTRAP_GOOGLE_ANALYTICS_ACCOUNT'] = conf(
    'BOOTSTRAP_GOOGLE_ANALYTICS_ACCOUNT')
Bootstrap(app)

oauth = OAuth()
meetup_oauth = oauth.remote_app(
    'meetup',
    base_url='https://api.meetup.com/',
    request_token_url='https://api.meetup.com/oauth/request/',
    access_token_url='https://api.meetup.com/oauth/access/',
    authorize_url='http://www.meetup.com/authorize/',
    consumer_key=conf('MEETUP_OAUTH_CONSUMER_KEY'),
    consumer_secret=conf('MEETUP_OAUTH_CONSUMER_SECRET'),
)
meetup = Meetup(meetup_oauth)

app.config['MONGO_URI'] = conf('MONGOHQ_URL', 'mongodb://localhost/meetups')
mongo = PyMongo(app)

sendgrid_api = sendgrid.Sendgrid(
Exemplo n.º 47
0
# -*- coding: utf-8 -*-

from flask import Blueprint, flash, g, redirect, render_template, request, session, url_for
from flask.ext.oauth import OAuth

from app import db
from .forms import LoginForm, RegistrationForm
from .model import User
import controller

oauth = OAuth()

oauth_twitter = oauth.remote_app('twitter',
        base_url = 'http://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',
        #authorize_url = 'https://api.twitter.com/oauth/authorize',
        consumer_key = '<CONSUMER_KEY>',
        consumer_secret = '<CONSUMER_SECRET>'
        )

MODULE_NAME = 'users'
MODULE_PREFIX = '/user'

module = Blueprint(MODULE_NAME, __name__, url_prefix=MODULE_PREFIX)

Exemplo n.º 48
0
from urllib2 import urlopen, URLError
from urlparse import parse_qs

from flask import request, session, redirect, flash, url_for, json
from flask.ext.oauth import OAuth, OAuthException  # OAuth 1.0a
from httplib import BadStatusLine
from coaster import valid_username
from coaster.views import get_next_url

from lastuserapp import app
from lastuserapp.models import db, UserExternalId, UserEmail, User
from lastuserapp.views.helpers import login_internal, register_internal
from lastuserapp.utils import get_gravatar_md5sum

# OAuth 1.0a handlers
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=app.config.get('OAUTH_TWITTER_KEY'),
    consumer_secret=app.config.get('OAUTH_TWITTER_SECRET'),
)


def get_extid_token(service):
    useridinfo = session.get('userid_external')
    if useridinfo:
        if service != useridinfo.get('service'):
            return None
Exemplo n.º 49
0
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)
Exemplo n.º 50
0
INDEXES = (Index('imdb_string_id_hash_index', Movie.imdb_string_id, postgresql_using='hash'),
           Index('recommendations_index', Movie.recomendations, postgresql_using='gin',
                                                                postgresql_ops={"recomendations": 'gin__int_ops'}),
           Index('languages_index', Movie.languages, postgresql_using='gin'),
           Index('title_index', Movie.title, postgresql_using='hash'),
    )

for ix in INDEXES:
    try:
        ix.create(db.engine)
    except Exception, e:
        #print e
        pass


oauth = OAuth()

facebook = oauth.remote_app('facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key=app.config["FACEBOOK_APP_ID"],
    consumer_secret=app.config["FACEBOOK_APP_SECRET"],
    request_token_params={'scope': 'email'}
)

_old_render = render_template

USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19"
Exemplo n.º 51
0
import json
import os
import urllib2,urllib

from flask import Module
from flask import redirect,request,session,url_for
from flask.ext.oauth import OAuth

from db import Database
from util import *

login = Module(__name__)
oauth = OAuth()


facebook = oauth.remote_app('facebook',
    base_url='https://graph.facebook.com/',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    authorize_url='https://www.facebook.com/dialog/oauth',
    consumer_key="178485798938752",
    consumer_secret="3fc3c9f171bbb5221403307113662fe5",
    request_token_params={'scope': 'email,user_likes,friends_likes,user_location'}
)

def cookieUser(email,extra_data=None):
    if extra_data is None:
        extra_data = dict()
    userObjData =  {
        'email':  email
    }
Exemplo n.º 52
0
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):
Exemplo n.º 53
0
from models import *
from forms import RegistrationForm,AddProjectForm,LoginForm,CommentForm,MessageForm
from functools import wraps
import helpers

from flask.ext.gravatar import Gravatar
from flask.ext.oauth import OAuth
from flaskext.babel import Babel
from extensions import db


# create our little application :)
app = Flask(__name__)
app.config.from_pyfile('config.py')

oauth = OAuth()
babel = Babel(app)

db.init_app(app)

gravatar = Gravatar(app,
        size=100,
        rating='g',
        default='retro',
        force_default=False,
        force_lower=False)

facebook = oauth.remote_app('facebook',
        base_url='https://graph.facebook.com/',
        request_token_url=None,
        access_token_url='/oauth/access_token',
Exemplo n.º 54
0
import hashlib, simplejson, requests, random
from datetime import datetime
import time
import pymongo, bson
from flask import Flask, render_template, request, Response, redirect, abort, session, send_from_directory, g, url_for
from flask.ext.pymongo import PyMongo
from flask.ext.oauth import OAuth
import config
import bleach
import markdown

app = Flask("index")
app.config.from_object(config)
app.secret_key = config.SECRET
mongo = PyMongo(app)
oauth = OAuth()

twitter = oauth.remote_app('KittyCheck',
    consumer_key=config.TWITTER["consumer_key"],
    consumer_secret=config.TWITTER["consumer_secret"],

    base_url='https://api.twitter.com/1.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',
)

def jsonify(hash, callback = None):
    if hash.has_key('_id'):
        del hash['_id']
    res = simplejson.dumps(hash, ensure_ascii=False)
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'],
    )